]> git.ipfire.org Git - thirdparty/openvpn.git/blob - src/openvpn/socket.c
Fix some unintialized variable warnings
[thirdparty/openvpn.git] / src / openvpn / socket.c
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.
7 *
8 * Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9 *
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.
13 *
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.
18 *
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
23 */
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #elif defined(_MSC_VER)
28 #include "config-msvc.h"
29 #endif
30
31 #include "syshead.h"
32
33 #include "socket.h"
34 #include "fdmisc.h"
35 #include "misc.h"
36 #include "gremlin.h"
37 #include "plugin.h"
38 #include "ps.h"
39 #include "manage.h"
40 #include "misc.h"
41 #include "manage.h"
42 #include "openvpn.h"
43
44 #include "memdbg.h"
45
46 const int proto_overhead[] = { /* indexed by PROTO_x */
47 0,
48 IPv4_UDP_HEADER_SIZE, /* IPv4 */
49 IPv4_TCP_HEADER_SIZE,
50 IPv4_TCP_HEADER_SIZE,
51 IPv6_UDP_HEADER_SIZE, /* IPv6 */
52 IPv6_TCP_HEADER_SIZE,
53 IPv6_TCP_HEADER_SIZE,
54 IPv6_TCP_HEADER_SIZE,
55 };
56
57 /*
58 * Convert sockflags/getaddr_flags into getaddr_flags
59 */
60 static unsigned int
61 sf2gaf(const unsigned int getaddr_flags,
62 const unsigned int sockflags)
63 {
64 if (sockflags & SF_HOST_RANDOMIZE)
65 return getaddr_flags | GETADDR_RANDOMIZE;
66 else
67 return getaddr_flags;
68 }
69
70 /*
71 * Functions related to the translation of DNS names to IP addresses.
72 */
73
74 static const char*
75 h_errno_msg(int h_errno_err)
76 {
77 switch (h_errno_err)
78 {
79 case HOST_NOT_FOUND:
80 return "[HOST_NOT_FOUND] The specified host is unknown.";
81 case NO_DATA:
82 return "[NO_DATA] The requested name is valid but does not have an IP address.";
83 case NO_RECOVERY:
84 return "[NO_RECOVERY] A non-recoverable name server error occurred.";
85 case TRY_AGAIN:
86 return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
87 }
88 return "[unknown h_errno value]";
89 }
90
91 /*
92 * Translate IP addr or hostname to in_addr_t.
93 * If resolve error, try again for
94 * resolve_retry_seconds seconds.
95 */
96 in_addr_t
97 getaddr (unsigned int flags,
98 const char *hostname,
99 int resolve_retry_seconds,
100 bool *succeeded,
101 volatile int *signal_received)
102 {
103 struct addrinfo *ai;
104 int status;
105 status = openvpn_getaddrinfo (flags & ~GETADDR_HOST_ORDER, hostname, NULL,
106 resolve_retry_seconds, signal_received, AF_INET, &ai);
107 if(status==0) {
108 struct in_addr ia;
109 if(succeeded)
110 *succeeded=true;
111 ia = ((struct sockaddr_in*)ai->ai_addr)->sin_addr;
112 freeaddrinfo(ai);
113 return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
114 } else {
115 if(succeeded)
116 *succeeded =false;
117 return 0;
118 }
119 }
120
121 static inline bool
122 streqnull (const char* a, const char* b)
123 {
124 if (a == NULL && b == NULL)
125 return true;
126 else if (a == NULL || b == NULL)
127 return false;
128 else
129 return streq (a, b);
130 }
131
132 /*
133 get_cached_dns_entry return 0 on success and -1
134 otherwise. (like getaddrinfo)
135 */
136 static int
137 get_cached_dns_entry (struct cached_dns_entry* dns_cache,
138 const char* hostname,
139 const char* servname,
140 int ai_family,
141 int resolve_flags,
142 struct addrinfo **ai)
143 {
144 struct cached_dns_entry *ph;
145 int flags;
146
147 /* Only use flags that are relevant for the structure */
148 flags = resolve_flags & GETADDR_CACHE_MASK;
149
150 for (ph = dns_cache; ph ; ph = ph->next)
151 {
152 if (streqnull (ph->hostname, hostname) &&
153 streqnull (ph->servname, servname) &&
154 ph->ai_family == ai_family &&
155 ph->flags == flags)
156 {
157 *ai = ph->ai;
158 return 0;
159 }
160 }
161 return -1;
162 }
163
164
165 static int
166 do_preresolve_host (struct context *c,
167 const char *hostname,
168 const char *servname,
169 const int af,
170 const int flags)
171 {
172 struct addrinfo *ai;
173 int status;
174
175 if (get_cached_dns_entry(c->c1.dns_cache,
176 hostname,
177 servname,
178 af,
179 flags,
180 &ai) == 0 )
181 {
182 /* entry already cached, return success */
183 return 0;
184 }
185
186 status = openvpn_getaddrinfo (flags, hostname, servname,
187 c->options.resolve_retry_seconds, NULL,
188 af, &ai);
189 if (status == 0)
190 {
191 struct cached_dns_entry *ph;
192
193 ALLOC_OBJ_CLEAR_GC (ph, struct cached_dns_entry, &c->gc);
194 ph->ai = ai;
195 ph->hostname = hostname;
196 ph->servname = servname;
197 ph->flags = flags & GETADDR_CACHE_MASK;
198
199 if (!c->c1.dns_cache)
200 c->c1.dns_cache = ph;
201 else
202 {
203 struct cached_dns_entry *prev = c->c1.dns_cache;
204 while (prev->next)
205 prev = prev->next;
206 prev->next = ph;
207 }
208
209 gc_addspecial (ai, &gc_freeaddrinfo_callback, &c->gc);
210
211 }
212 return status;
213 }
214
215 void
216 do_preresolve (struct context *c)
217 {
218 int i;
219 struct connection_list *l = c->options.connection_list;
220 const unsigned int preresolve_flags = GETADDR_RESOLVE|
221 GETADDR_UPDATE_MANAGEMENT_STATE|
222 GETADDR_MENTION_RESOLVE_RETRY|
223 GETADDR_FATAL;
224
225
226 for (i = 0; i < l->len; ++i)
227 {
228 int status;
229 const char *remote;
230 int flags = preresolve_flags;
231
232 struct connection_entry* ce = c->options.connection_list->array[i];
233
234 if (proto_is_dgram(ce->proto))
235 flags |= GETADDR_DATAGRAM;
236
237 if (c->options.sockflags & SF_HOST_RANDOMIZE)
238 flags |= GETADDR_RANDOMIZE;
239
240 if (c->options.ip_remote_hint)
241 remote = c->options.ip_remote_hint;
242 else
243 remote = ce->remote;
244
245 /* HTTP remote hostname does not need to be resolved */
246 if (! ce->http_proxy_options)
247 {
248 status = do_preresolve_host (c, remote, ce->remote_port, ce->af, flags);
249 if (status != 0)
250 goto err;
251 }
252
253 /* Preresolve proxy */
254 if (ce->http_proxy_options)
255 {
256 status = do_preresolve_host (c,
257 ce->http_proxy_options->server,
258 ce->http_proxy_options->port,
259 ce->af,
260 preresolve_flags);
261
262 if (status != 0)
263 goto err;
264 }
265
266 if (ce->socks_proxy_server)
267 {
268 status = do_preresolve_host (c,
269 ce->socks_proxy_server,
270 ce->socks_proxy_port,
271 ce->af,
272 flags);
273 if (status != 0)
274 goto err;
275 }
276
277 if (ce->bind_local)
278 {
279 flags |= GETADDR_PASSIVE;
280 flags &= ~GETADDR_RANDOMIZE;
281 status = do_preresolve_host (c, ce->local, ce->local_port, ce->af, flags);
282 if (status != 0)
283 goto err;
284
285 }
286
287 }
288 return;
289
290 err:
291 throw_signal_soft (SIGHUP, "Preresolving failed");
292 }
293
294 /*
295 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
296 * If resolve error, try again for resolve_retry_seconds seconds.
297 */
298 int
299 openvpn_getaddrinfo (unsigned int flags,
300 const char *hostname,
301 const char *servname,
302 int resolve_retry_seconds,
303 volatile int *signal_received,
304 int ai_family,
305 struct addrinfo **res)
306 {
307 struct addrinfo hints;
308 int status;
309 int sigrec = 0;
310 int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
311 struct gc_arena gc = gc_new ();
312 const char *print_hostname;
313 const char *print_servname;
314
315 ASSERT(res);
316
317 #if defined(HAVE_RES_INIT)
318 res_init ();
319 #endif
320
321 ASSERT (hostname || servname);
322 ASSERT (!(flags & GETADDR_HOST_ORDER));
323
324 if (hostname && (flags & GETADDR_RANDOMIZE))
325 hostname = hostname_randomize(hostname, &gc);
326
327 if(hostname)
328 print_hostname = hostname;
329 else
330 print_hostname = "undefined";
331
332 if(servname)
333 print_servname = servname;
334 else
335 print_servname = "";
336
337 if (flags & GETADDR_MSG_VIRT_OUT)
338 msglevel |= M_MSG_VIRT_OUT;
339
340 if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
341 && !signal_received)
342 signal_received = &sigrec;
343
344 /* try numeric ipv6 addr first */
345 CLEAR(hints);
346 hints.ai_family = ai_family;
347 hints.ai_flags = AI_NUMERICHOST;
348
349 if(flags & GETADDR_PASSIVE)
350 hints.ai_flags |= AI_PASSIVE;
351
352 if(flags & GETADDR_DATAGRAM)
353 hints.ai_socktype = SOCK_DGRAM;
354 else
355 hints.ai_socktype = SOCK_STREAM;
356
357 status = getaddrinfo(hostname, servname, &hints, res);
358
359 if (status != 0) /* parse as numeric address failed? */
360 {
361 const int fail_wait_interval = 5; /* seconds */
362 /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
363 int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 :
364 ((resolve_retry_seconds + 4)/ fail_wait_interval);
365 const char *fmt;
366 int level = 0;
367
368 fmt = "RESOLVE: Cannot resolve host address: %s:%s (%s)";
369 if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
370 && !resolve_retry_seconds)
371 fmt = "RESOLVE: Cannot resolve host address: %s:%s (%s) (I would have retried this name query if you had specified the --resolv-retry option.)";
372
373 if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
374 {
375 msg (msglevel, "RESOLVE: Cannot parse IP address: %s:%s (%s)",
376 print_hostname,print_servname, gai_strerror(status));
377 goto done;
378 }
379
380 #ifdef ENABLE_MANAGEMENT
381 if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
382 {
383 if (management)
384 management_set_state (management,
385 OPENVPN_STATE_RESOLVE,
386 NULL,
387 (in_addr_t)0,
388 (in_addr_t)0);
389 }
390 #endif
391
392 /*
393 * Resolve hostname
394 */
395 while (true)
396 {
397 /* try hostname lookup */
398 hints.ai_flags &= ~AI_NUMERICHOST;
399 dmsg (D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
400 flags, hints.ai_family, hints.ai_socktype);
401 status = getaddrinfo(hostname, servname, &hints, res);
402
403 if (signal_received)
404 {
405 get_signal (signal_received);
406 if (*signal_received) /* were we interrupted by a signal? */
407 {
408 if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
409 {
410 msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
411 *signal_received = 0;
412 }
413 else
414 {
415 if (0 == status) {
416 ASSERT(res);
417 freeaddrinfo(*res);
418 res = NULL;
419 }
420 goto done;
421 }
422 }
423 }
424
425 /* success? */
426 if (0 == status)
427 break;
428
429 /* resolve lookup failed, should we
430 continue or fail? */
431 level = msglevel;
432 if (resolve_retries > 0)
433 level = D_RESOLVE_ERRORS;
434
435 msg (level,
436 fmt,
437 print_hostname,
438 print_servname,
439 gai_strerror(status));
440
441 if (--resolve_retries <= 0)
442 goto done;
443
444 openvpn_sleep (fail_wait_interval);
445 }
446
447 ASSERT(res);
448
449 /* hostname resolve succeeded */
450
451 /*
452 * Do not choose an IP Addresse by random or change the order *
453 * of IP addresses, doing so will break RFC 3484 address selection *
454 */
455 }
456 else
457 {
458 /* IP address parse succeeded */
459 }
460
461 done:
462 if (signal_received && *signal_received)
463 {
464 int level = 0;
465 if (flags & GETADDR_FATAL_ON_SIGNAL)
466 level = M_FATAL;
467 else if (flags & GETADDR_WARN_ON_SIGNAL)
468 level = M_WARN;
469 msg (level, "RESOLVE: signal received during DNS resolution attempt");
470 }
471
472 gc_free (&gc);
473 return status;
474 }
475
476 /*
477 * We do our own inet_aton because the glibc function
478 * isn't very good about error checking.
479 */
480 int
481 openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
482 {
483 unsigned int a, b, c, d;
484
485 CLEAR (*addr);
486 if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
487 {
488 if (a < 256 && b < 256 && c < 256 && d < 256)
489 {
490 addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
491 return OIA_IP; /* good dotted quad */
492 }
493 }
494 if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
495 return OIA_ERROR; /* probably a badly formatted dotted quad */
496 else
497 return OIA_HOSTNAME; /* probably a hostname */
498 }
499
500 bool
501 ip_addr_dotted_quad_safe (const char *dotted_quad)
502 {
503 /* verify non-NULL */
504 if (!dotted_quad)
505 return false;
506
507 /* verify length is within limits */
508 if (strlen (dotted_quad) > 15)
509 return false;
510
511 /* verify that all chars are either numeric or '.' and that no numeric
512 substring is greater than 3 chars */
513 {
514 int nnum = 0;
515 const char *p = dotted_quad;
516 int c;
517
518 while ((c = *p++))
519 {
520 if (c >= '0' && c <= '9')
521 {
522 ++nnum;
523 if (nnum > 3)
524 return false;
525 }
526 else if (c == '.')
527 {
528 nnum = 0;
529 }
530 else
531 return false;
532 }
533 }
534
535 /* verify that string will convert to IP address */
536 {
537 struct in_addr a;
538 return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
539 }
540 }
541
542 bool
543 ipv6_addr_safe (const char *ipv6_text_addr)
544 {
545 /* verify non-NULL */
546 if (!ipv6_text_addr)
547 return false;
548
549 /* verify length is within limits */
550 if (strlen (ipv6_text_addr) > INET6_ADDRSTRLEN )
551 return false;
552
553 /* verify that string will convert to IPv6 address */
554 {
555 struct in6_addr a6;
556 return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) == 1;
557 }
558 }
559
560 static bool
561 dns_addr_safe (const char *addr)
562 {
563 if (addr)
564 {
565 const size_t len = strlen (addr);
566 return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
567 }
568 else
569 return false;
570 }
571
572 bool
573 ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
574 {
575 if (ip_addr_dotted_quad_safe (addr))
576 return true;
577 else if (allow_fqdn)
578 return dns_addr_safe (addr);
579 else
580 return false;
581 }
582
583 bool
584 mac_addr_safe (const char *mac_addr)
585 {
586 /* verify non-NULL */
587 if (!mac_addr)
588 return false;
589
590 /* verify length is within limits */
591 if (strlen (mac_addr) > 17)
592 return false;
593
594 /* verify that all chars are either alphanumeric or ':' and that no
595 alphanumeric substring is greater than 2 chars */
596 {
597 int nnum = 0;
598 const char *p = mac_addr;
599 int c;
600
601 while ((c = *p++))
602 {
603 if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
604 {
605 ++nnum;
606 if (nnum > 2)
607 return false;
608 }
609 else if (c == ':')
610 {
611 nnum = 0;
612 }
613 else
614 return false;
615 }
616 }
617
618 /* error-checking is left to script invoked in lladdr.c */
619 return true;
620 }
621
622 static int
623 socket_get_sndbuf (int sd)
624 {
625 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
626 int val;
627 socklen_t len;
628
629 len = sizeof (val);
630 if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
631 && len == sizeof (val))
632 return val;
633 #endif
634 return 0;
635 }
636
637 static void
638 socket_set_sndbuf (int sd, int size)
639 {
640 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
641 if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
642 {
643 if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
644 {
645 msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
646 }
647 }
648 #endif
649 }
650
651 static int
652 socket_get_rcvbuf (int sd)
653 {
654 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
655 int val;
656 socklen_t len;
657
658 len = sizeof (val);
659 if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
660 && len == sizeof (val))
661 return val;
662 #endif
663 return 0;
664 }
665
666 static bool
667 socket_set_rcvbuf (int sd, int size)
668 {
669 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
670 if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
671 {
672 if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
673 {
674 msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
675 return false;
676 }
677 }
678 return true;
679 #endif
680 }
681
682 static void
683 socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
684 {
685 if (sbs)
686 {
687 const int sndbuf_old = socket_get_sndbuf (fd);
688 const int rcvbuf_old = socket_get_rcvbuf (fd);
689
690 if (sbs->sndbuf)
691 socket_set_sndbuf (fd, sbs->sndbuf);
692
693 if (sbs->rcvbuf)
694 socket_set_rcvbuf (fd, sbs->rcvbuf);
695
696 msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
697 rcvbuf_old,
698 socket_get_rcvbuf (fd),
699 sndbuf_old,
700 socket_get_sndbuf (fd));
701 }
702 }
703
704 /*
705 * Set other socket options
706 */
707
708 static bool
709 socket_set_tcp_nodelay (int sd, int state)
710 {
711 #if defined(WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
712 if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
713 {
714 msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
715 return false;
716 }
717 else
718 {
719 dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
720 return true;
721 }
722 #else
723 msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
724 return false;
725 #endif
726 }
727
728 static inline void
729 socket_set_mark (int sd, int mark)
730 {
731 #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
732 if (mark && setsockopt (sd, SOL_SOCKET, SO_MARK, &mark, sizeof (mark)) != 0)
733 msg (M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
734 #endif
735 }
736
737 static bool
738 socket_set_flags (int sd, unsigned int sockflags)
739 {
740 if (sockflags & SF_TCP_NODELAY)
741 return socket_set_tcp_nodelay (sd, 1);
742 else
743 return true;
744 }
745
746 bool
747 link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
748 {
749 if (ls && socket_defined (ls->sd))
750 return socket_set_flags (ls->sd, ls->sockflags = sockflags);
751 else
752 return false;
753 }
754
755 void
756 link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
757 {
758 if (ls && socket_defined (ls->sd))
759 {
760 ls->socket_buffer_sizes.sndbuf = sndbuf;
761 ls->socket_buffer_sizes.rcvbuf = rcvbuf;
762 socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
763 }
764 }
765
766 /*
767 * SOCKET INITALIZATION CODE.
768 * Create a TCP/UDP socket
769 */
770
771 socket_descriptor_t
772 create_socket_tcp (struct addrinfo* addrinfo)
773 {
774 socket_descriptor_t sd;
775
776 ASSERT (addrinfo);
777 ASSERT (addrinfo->ai_socktype == SOCK_STREAM);
778
779 if ((sd = socket (addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol)) < 0)
780 msg (M_ERR, "Cannot create TCP socket");
781
782 #ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
783 /* set SO_REUSEADDR on socket */
784 {
785 int on = 1;
786 if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
787 (void *) &on, sizeof (on)) < 0)
788 msg (M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
789 }
790 #endif
791
792 return sd;
793 }
794
795 static socket_descriptor_t
796 create_socket_udp (struct addrinfo* addrinfo, const unsigned int flags)
797 {
798 socket_descriptor_t sd;
799
800 ASSERT (addrinfo);
801 ASSERT (addrinfo->ai_socktype == SOCK_DGRAM);
802
803 if ((sd = socket (addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol)) < 0)
804 msg (M_ERR, "UDP: Cannot create UDP/UDP6 socket");
805 #if ENABLE_IP_PKTINFO
806 else if (flags & SF_USE_IP_PKTINFO)
807 {
808 int pad = 1;
809 if(addrinfo->ai_family == AF_INET)
810 {
811 #ifdef IP_PKTINFO
812 if (setsockopt (sd, SOL_IP, IP_PKTINFO,
813 (void*)&pad, sizeof(pad)) < 0)
814 msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
815 #elif defined(IP_RECVDSTADDR)
816 if (setsockopt (sd, IPPROTO_IP, IP_RECVDSTADDR,
817 (void*)&pad, sizeof(pad)) < 0)
818 msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
819 #else
820 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
821 #endif
822 }
823 else if (addrinfo->ai_family == AF_INET6 )
824 {
825 #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
826 if (setsockopt (sd, IPPROTO_IPV6, IPV6_PKTINFO,
827 (void*)&pad, sizeof(pad)) < 0)
828 #else
829 if (setsockopt (sd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
830 (void*)&pad, sizeof(pad)) < 0)
831 #endif
832 msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");
833 }
834 }
835 #endif
836 return sd;
837 }
838
839 static void bind_local (struct link_socket *sock, const sa_family_t ai_family)
840 {
841 /* bind to local address/port */
842 if (sock->bind_local)
843 {
844 if (sock->socks_proxy && sock->info.proto == PROTO_UDP)
845 socket_bind (sock->ctrl_sd, sock->info.lsa->bind_local,
846 ai_family, "SOCKS", false);
847 else
848 socket_bind (sock->sd, sock->info.lsa->bind_local,
849 ai_family,
850 "TCP/UDP", sock->info.bind_ipv6_only);
851 }
852 }
853
854 static void
855 create_socket (struct link_socket* sock, struct addrinfo* addr)
856 {
857 if (addr->ai_protocol == IPPROTO_UDP || addr->ai_socktype == SOCK_DGRAM)
858 {
859 sock->sd = create_socket_udp (addr, sock->sockflags);
860 sock->sockflags |= SF_GETADDRINFO_DGRAM;
861
862 /* Assume that control socket and data socket to the socks proxy
863 * are using the same IP family */
864 if (sock->socks_proxy)
865 {
866 /* Construct a temporary addrinfo to create the socket,
867 * currently resolve two remote addresses is not supported,
868 * TODO: Rewrite the whole resolve_remote */
869 struct addrinfo addrinfo_tmp = *addr;
870 addrinfo_tmp.ai_socktype = SOCK_STREAM;
871 addrinfo_tmp.ai_protocol = IPPROTO_TCP;
872 sock->ctrl_sd = create_socket_tcp (&addrinfo_tmp);
873 }
874 }
875 else if (addr->ai_protocol == IPPROTO_TCP || addr->ai_socktype == SOCK_STREAM)
876 {
877 sock->sd = create_socket_tcp (addr);
878 }
879 else
880 {
881 ASSERT (0);
882 }
883 /* set socket buffers based on --sndbuf and --rcvbuf options */
884 socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
885
886 /* set socket to --mark packets with given value */
887 socket_set_mark (sock->sd, sock->mark);
888
889 bind_local (sock, addr->ai_family);
890 }
891
892 #ifdef TARGET_ANDROID
893 static void protect_fd_nonlocal (int fd, const struct sockaddr* addr)
894 {
895 /* pass socket FD to management interface to pass on to VPNService API
896 * as "protected socket" (exempt from being routed into tunnel)
897 */
898 if (addr_local (addr)) {
899 msg(M_DEBUG, "Address is local, not protecting socket fd %d", fd);
900 return;
901 }
902
903 msg(M_DEBUG, "Protecting socket fd %d", fd);
904 management->connection.fdtosend = fd;
905 management_android_control (management, "PROTECTFD", __func__);
906 }
907 #endif
908
909 /*
910 * Functions used for establishing a TCP stream connection.
911 */
912 static void
913 socket_do_listen (socket_descriptor_t sd,
914 const struct addrinfo *local,
915 bool do_listen,
916 bool do_set_nonblock)
917 {
918 struct gc_arena gc = gc_new ();
919 if (do_listen)
920 {
921 ASSERT(local);
922 msg (M_INFO, "Listening for incoming TCP connection on %s",
923 print_sockaddr (local->ai_addr, &gc));
924 if (listen (sd, 1))
925 msg (M_ERR, "TCP: listen() failed");
926 }
927
928 /* set socket to non-blocking mode */
929 if (do_set_nonblock)
930 set_nonblock (sd);
931
932 gc_free (&gc);
933 }
934
935 socket_descriptor_t
936 socket_do_accept (socket_descriptor_t sd,
937 struct link_socket_actual *act,
938 const bool nowait)
939 {
940 /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
941 * are compiled because act is empty here.
942 * could use getsockname() to support later remote_len check
943 */
944 socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
945 socklen_t remote_len = sizeof(act->dest.addr);
946 socket_descriptor_t new_sd = SOCKET_UNDEFINED;
947
948 CLEAR (*act);
949
950 #ifdef HAVE_GETPEERNAME
951 if (nowait)
952 {
953 new_sd = getpeername (sd, &act->dest.addr.sa, &remote_len);
954
955 if (!socket_defined (new_sd))
956 msg (D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
957 else
958 new_sd = sd;
959 }
960 #else
961 if (nowait)
962 msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
963 #endif
964 else
965 {
966 new_sd = accept (sd, &act->dest.addr.sa, &remote_len);
967 }
968
969 #if 0 /* For debugging only, test the effect of accept() failures */
970 {
971 static int foo = 0;
972 ++foo;
973 if (foo & 1)
974 new_sd = -1;
975 }
976 #endif
977
978 if (!socket_defined (new_sd))
979 {
980 msg (D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", sd);
981 }
982 /* only valid if we have remote_len_af!=0 */
983 else if (remote_len_af && remote_len != remote_len_af)
984 {
985 msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
986 openvpn_close_socket (new_sd);
987 new_sd = SOCKET_UNDEFINED;
988 }
989 return new_sd;
990 }
991
992 static void
993 tcp_connection_established (const struct link_socket_actual *act)
994 {
995 struct gc_arena gc = gc_new ();
996 msg (M_INFO, "TCP connection established with %s",
997 print_link_socket_actual (act, &gc));
998 gc_free (&gc);
999 }
1000
1001 static int
1002 socket_listen_accept (socket_descriptor_t sd,
1003 struct link_socket_actual *act,
1004 const char *remote_dynamic,
1005 const struct addrinfo *local,
1006 bool do_listen,
1007 bool nowait,
1008 volatile int *signal_received)
1009 {
1010 struct gc_arena gc = gc_new ();
1011 /* struct openvpn_sockaddr *remote = &act->dest; */
1012 struct openvpn_sockaddr remote_verify = act->dest;
1013 int new_sd = SOCKET_UNDEFINED;
1014
1015 CLEAR (*act);
1016 socket_do_listen (sd, local, do_listen, true);
1017
1018 while (true)
1019 {
1020 int status;
1021 fd_set reads;
1022 struct timeval tv;
1023
1024 FD_ZERO (&reads);
1025 FD_SET (sd, &reads);
1026 tv.tv_sec = 0;
1027 tv.tv_usec = 0;
1028
1029 status = select (sd + 1, &reads, NULL, NULL, &tv);
1030
1031 get_signal (signal_received);
1032 if (*signal_received)
1033 {
1034 gc_free (&gc);
1035 return sd;
1036 }
1037
1038 if (status < 0)
1039 msg (D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
1040
1041 if (status <= 0)
1042 {
1043 openvpn_sleep (1);
1044 continue;
1045 }
1046
1047 new_sd = socket_do_accept (sd, act, nowait);
1048
1049 if (socket_defined (new_sd))
1050 {
1051 struct addrinfo* ai = NULL;
1052 if(remote_dynamic)
1053 openvpn_getaddrinfo(0, remote_dynamic, NULL, 1, NULL,
1054 remote_verify.addr.sa.sa_family, &ai);
1055
1056 if(ai && !addrlist_match(&remote_verify, ai))
1057 {
1058 msg (M_WARN,
1059 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
1060 print_link_socket_actual (act, &gc));
1061 if (openvpn_close_socket (new_sd))
1062 msg (M_ERR, "TCP: close socket failed (new_sd)");
1063 freeaddrinfo(ai);
1064 }
1065 else
1066 {
1067 if(ai)
1068 freeaddrinfo(ai);
1069 break;
1070 }
1071 }
1072 openvpn_sleep (1);
1073 }
1074
1075 if (!nowait && openvpn_close_socket (sd))
1076 msg (M_ERR, "TCP: close socket failed (sd)");
1077
1078 tcp_connection_established (act);
1079
1080 gc_free (&gc);
1081 return new_sd;
1082 }
1083
1084 void
1085 socket_bind (socket_descriptor_t sd,
1086 struct addrinfo *local,
1087 int ai_family,
1088 const char *prefix,
1089 bool ipv6only)
1090 {
1091 struct gc_arena gc = gc_new ();
1092
1093 /* FIXME (schwabe)
1094 * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
1095 * entries for the requested protocol.
1096 * For example if an address has multiple A records
1097 * What is the correct way to deal with it?
1098 */
1099
1100 struct addrinfo* cur;
1101
1102 ASSERT(local);
1103
1104
1105 /* find the first addrinfo with correct ai_family */
1106 for (cur = local; cur; cur=cur->ai_next)
1107 {
1108 if(cur->ai_family == ai_family)
1109 break;
1110 }
1111 if (!cur)
1112 msg (M_FATAL, "%s: Socket bind failed: Addr to bind has no %s record",
1113 prefix, addr_family_name(ai_family));
1114
1115 if (ai_family == AF_INET6)
1116 {
1117 int v6only = ipv6only ? 1: 0; /* setsockopt must have an "int" */
1118
1119 msg (M_INFO, "setsockopt(IPV6_V6ONLY=%d)", v6only);
1120 if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)))
1121 {
1122 msg (M_NONFATAL|M_ERRNO, "Setting IPV6_V6ONLY=%d failed", v6only);
1123 }
1124 }
1125 if (bind (sd, cur->ai_addr, cur->ai_addrlen))
1126 {
1127 const int errnum = openvpn_errno ();
1128 msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
1129 prefix,
1130 print_sockaddr_ex (local->ai_addr, ":", PS_SHOW_PORT, &gc),
1131 strerror_ts (errnum, &gc));
1132 }
1133 gc_free (&gc);
1134 }
1135
1136 int
1137 openvpn_connect (socket_descriptor_t sd,
1138 const struct sockaddr *remote,
1139 int connect_timeout,
1140 volatile int *signal_received)
1141 {
1142 int status = 0;
1143
1144 #ifdef TARGET_ANDROID
1145 protect_fd_nonlocal(sd, remote);
1146 #endif
1147
1148 #ifdef CONNECT_NONBLOCK
1149 set_nonblock (sd);
1150 status = connect (sd, remote, af_addr_size(remote->sa_family));
1151 if (status)
1152 status = openvpn_errno ();
1153 if (
1154 #ifdef WIN32
1155 status == WSAEWOULDBLOCK
1156 #else
1157 status == EINPROGRESS
1158 #endif
1159 )
1160 {
1161 while (true)
1162 {
1163 fd_set writes;
1164 struct timeval tv;
1165
1166 FD_ZERO (&writes);
1167 FD_SET (sd, &writes);
1168 tv.tv_sec = 0;
1169 tv.tv_usec = 0;
1170
1171 status = select (sd + 1, NULL, &writes, NULL, &tv);
1172
1173 if (signal_received)
1174 {
1175 get_signal (signal_received);
1176 if (*signal_received)
1177 {
1178 status = 0;
1179 break;
1180 }
1181 }
1182 if (status < 0)
1183 {
1184 status = openvpn_errno ();
1185 break;
1186 }
1187 if (status <= 0)
1188 {
1189 if (--connect_timeout < 0)
1190 {
1191 status = ETIMEDOUT;
1192 break;
1193 }
1194 openvpn_sleep (1);
1195 continue;
1196 }
1197
1198 /* got it */
1199 {
1200 int val = 0;
1201 socklen_t len;
1202
1203 len = sizeof (val);
1204 if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
1205 && len == sizeof (val))
1206 status = val;
1207 else
1208 status = openvpn_errno ();
1209 break;
1210 }
1211 }
1212 }
1213 #else
1214 status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
1215 if (status)
1216 status = openvpn_errno ();
1217 #endif
1218
1219 return status;
1220 }
1221
1222 void set_actual_address (struct link_socket_actual* actual, struct addrinfo* ai)
1223 {
1224 CLEAR (*actual);
1225 ASSERT (ai);
1226
1227 if (ai->ai_family == AF_INET)
1228 actual->dest.addr.in4 =
1229 *((struct sockaddr_in*) ai->ai_addr);
1230 else if (ai->ai_family == AF_INET6)
1231 actual->dest.addr.in6 =
1232 *((struct sockaddr_in6*) ai->ai_addr);
1233 else
1234 ASSERT(0);
1235
1236 }
1237
1238 void
1239 socket_connect (socket_descriptor_t* sd,
1240 const struct sockaddr* dest,
1241 const int connect_timeout,
1242 struct signal_info* sig_info)
1243 {
1244 struct gc_arena gc = gc_new ();
1245 int status;
1246
1247 #ifdef CONNECT_NONBLOCK
1248 msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
1249 print_sockaddr (dest, &gc));
1250 #else
1251 msg (M_INFO, "Attempting to establish TCP connection with %s",
1252 print_sockaddr (dest, &gc));
1253 #endif
1254
1255 #ifdef ENABLE_MANAGEMENT
1256 if (management)
1257 management_set_state (management,
1258 OPENVPN_STATE_TCP_CONNECT,
1259 NULL,
1260 (in_addr_t)0,
1261 (in_addr_t)0);
1262 #endif
1263
1264 /* Set the actual address */
1265 status = openvpn_connect (*sd, dest, connect_timeout, &sig_info->signal_received);
1266
1267 get_signal (&sig_info->signal_received);
1268 if (sig_info->signal_received)
1269 goto done;
1270
1271 if (status) {
1272
1273 msg (D_LINK_ERRORS,
1274 "TCP: connect to %s failed: %s",
1275 print_sockaddr (dest, &gc),
1276 strerror_ts (status, &gc));
1277
1278 openvpn_close_socket (*sd);
1279 *sd = SOCKET_UNDEFINED;
1280 sig_info->signal_received = SIGUSR1;
1281 sig_info->source = SIG_SOURCE_CONNECTION_FAILED;
1282 } else {
1283 msg (M_INFO, "TCP connection established with %s",
1284 print_sockaddr (dest, &gc));
1285 }
1286
1287 done:
1288 gc_free (&gc);
1289 }
1290
1291 /* For stream protocols, allocate a buffer to build up packet.
1292 Called after frame has been finalized. */
1293
1294 static void
1295 socket_frame_init (const struct frame *frame, struct link_socket *sock)
1296 {
1297 #ifdef WIN32
1298 overlapped_io_init (&sock->reads, frame, FALSE, false);
1299 overlapped_io_init (&sock->writes, frame, TRUE, false);
1300 sock->rw_handle.read = sock->reads.overlapped.hEvent;
1301 sock->rw_handle.write = sock->writes.overlapped.hEvent;
1302 #endif
1303
1304 if (link_socket_connection_oriented (sock))
1305 {
1306 #ifdef WIN32
1307 stream_buf_init (&sock->stream_buf,
1308 &sock->reads.buf_init,
1309 sock->sockflags,
1310 sock->info.proto);
1311 #else
1312 alloc_buf_sock_tun (&sock->stream_buf_data,
1313 frame,
1314 false,
1315 FRAME_HEADROOM_MARKER_READ_STREAM);
1316
1317 stream_buf_init (&sock->stream_buf,
1318 &sock->stream_buf_data,
1319 sock->sockflags,
1320 sock->info.proto);
1321 #endif
1322 }
1323 }
1324
1325 /*
1326 * Adjust frame structure based on a Path MTU value given
1327 * to us by the OS.
1328 */
1329 void
1330 frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
1331 {
1332 frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
1333 }
1334
1335 static void
1336 resolve_bind_local (struct link_socket *sock, const sa_family_t af)
1337 {
1338 struct gc_arena gc = gc_new ();
1339
1340 /* resolve local address if undefined */
1341 if (!sock->info.lsa->bind_local)
1342 {
1343 int flags = GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL |
1344 GETADDR_FATAL | GETADDR_PASSIVE;
1345 int status;
1346
1347 if(proto_is_dgram(sock->info.proto))
1348 flags |= GETADDR_DATAGRAM;
1349
1350 /* will return AF_{INET|INET6}from local_host */
1351 status = get_cached_dns_entry (sock->dns_cache,
1352 sock->local_host,
1353 sock->local_port,
1354 af,
1355 flags,
1356 &sock->info.lsa->bind_local);
1357
1358 if (status)
1359 status = openvpn_getaddrinfo(flags, sock->local_host, sock->local_port, 0,
1360 NULL, af, &sock->info.lsa->bind_local);
1361
1362 if(status !=0) {
1363 msg (M_FATAL, "getaddrinfo() failed for local \"%s:%s\": %s",
1364 sock->local_host, sock->local_port,
1365 gai_strerror(status));
1366 }
1367 }
1368
1369 gc_free (&gc);
1370 }
1371
1372 static void
1373 resolve_remote (struct link_socket *sock,
1374 int phase,
1375 const char **remote_dynamic,
1376 volatile int *signal_received)
1377 {
1378 struct gc_arena gc = gc_new ();
1379
1380 /* resolve remote address if undefined */
1381 if (!sock->info.lsa->remote_list)
1382 {
1383 if (sock->remote_host)
1384 {
1385 unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
1386 int retry = 0;
1387 int status = -1;
1388 struct addrinfo* ai;
1389 if (proto_is_dgram(sock->info.proto))
1390 flags |= GETADDR_DATAGRAM;
1391
1392 if (sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
1393 {
1394 if (phase == 2)
1395 flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1396 retry = 0;
1397 }
1398 else if (phase == 1)
1399 {
1400 if (sock->resolve_retry_seconds)
1401 {
1402 retry = 0;
1403 }
1404 else
1405 {
1406 flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
1407 retry = 0;
1408 }
1409 }
1410 else if (phase == 2)
1411 {
1412 if (sock->resolve_retry_seconds)
1413 {
1414 flags |= GETADDR_FATAL;
1415 retry = sock->resolve_retry_seconds;
1416 }
1417 else
1418 {
1419 ASSERT (0);
1420 }
1421 }
1422 else
1423 {
1424 ASSERT (0);
1425 }
1426
1427
1428 status = get_cached_dns_entry (sock->dns_cache,
1429 sock->remote_host,
1430 sock->remote_port,
1431 sock->info.af,
1432 flags, &ai);
1433 if (status)
1434 status = openvpn_getaddrinfo (flags, sock->remote_host, sock->remote_port,
1435 retry, signal_received, sock->info.af, &ai);
1436
1437 if(status == 0) {
1438 sock->info.lsa->remote_list = ai;
1439 sock->info.lsa->current_remote = ai;
1440
1441 dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1442 flags,
1443 phase,
1444 retry,
1445 signal_received ? *signal_received : -1,
1446 status);
1447 }
1448 if (signal_received)
1449 {
1450 if (*signal_received)
1451 goto done;
1452 }
1453 if (status!=0)
1454 {
1455 if (signal_received)
1456 *signal_received = SIGUSR1;
1457 goto done;
1458 }
1459 }
1460 }
1461
1462 /* should we re-use previous active remote address? */
1463 if (link_socket_actual_defined (&sock->info.lsa->actual))
1464 {
1465 msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1466 print_link_socket_actual (&sock->info.lsa->actual, &gc));
1467 if (remote_dynamic)
1468 *remote_dynamic = NULL;
1469 }
1470 else
1471 {
1472 CLEAR (sock->info.lsa->actual);
1473 if(sock->info.lsa->current_remote)
1474 {
1475 set_actual_address (&sock->info.lsa->actual,
1476 sock->info.lsa->current_remote);
1477 }
1478 }
1479
1480 done:
1481 gc_free (&gc);
1482 }
1483
1484
1485
1486 struct link_socket *
1487 link_socket_new (void)
1488 {
1489 struct link_socket *sock;
1490
1491 ALLOC_OBJ_CLEAR (sock, struct link_socket);
1492 sock->sd = SOCKET_UNDEFINED;
1493 sock->ctrl_sd = SOCKET_UNDEFINED;
1494 return sock;
1495 }
1496
1497 void
1498 link_socket_init_phase1 (struct link_socket *sock,
1499 const char *local_host,
1500 const char *local_port,
1501 const char *remote_host,
1502 const char *remote_port,
1503 struct cached_dns_entry *dns_cache,
1504 int proto,
1505 sa_family_t af,
1506 bool bind_ipv6_only,
1507 int mode,
1508 const struct link_socket *accept_from,
1509 struct http_proxy_info *http_proxy,
1510 struct socks_proxy_info *socks_proxy,
1511 #ifdef ENABLE_DEBUG
1512 int gremlin,
1513 #endif
1514 bool bind_local,
1515 bool remote_float,
1516 int inetd,
1517 struct link_socket_addr *lsa,
1518 const char *ipchange_command,
1519 const struct plugin_list *plugins,
1520 int resolve_retry_seconds,
1521 int connect_timeout,
1522 int mtu_discover_type,
1523 int rcvbuf,
1524 int sndbuf,
1525 int mark,
1526 unsigned int sockflags)
1527 {
1528 ASSERT (sock);
1529
1530 sock->local_host = local_host;
1531 sock->local_port = local_port;
1532 sock->remote_host = remote_host;
1533 sock->remote_port = remote_port;
1534 sock->dns_cache = dns_cache;
1535 sock->http_proxy = http_proxy;
1536 sock->socks_proxy = socks_proxy;
1537 sock->bind_local = bind_local;
1538 sock->inetd = inetd;
1539 sock->resolve_retry_seconds = resolve_retry_seconds;
1540 sock->connect_timeout = connect_timeout;
1541 sock->mtu_discover_type = mtu_discover_type;
1542
1543 #ifdef ENABLE_DEBUG
1544 sock->gremlin = gremlin;
1545 #endif
1546
1547 sock->socket_buffer_sizes.rcvbuf = rcvbuf;
1548 sock->socket_buffer_sizes.sndbuf = sndbuf;
1549
1550 sock->sockflags = sockflags;
1551 sock->mark = mark;
1552
1553 sock->info.proto = proto;
1554 sock->info.af = af;
1555 sock->info.remote_float = remote_float;
1556 sock->info.lsa = lsa;
1557 sock->info.bind_ipv6_only = bind_ipv6_only;
1558 sock->info.ipchange_command = ipchange_command;
1559 sock->info.plugins = plugins;
1560
1561 sock->mode = mode;
1562 if (mode == LS_MODE_TCP_ACCEPT_FROM)
1563 {
1564 ASSERT (accept_from);
1565 ASSERT (sock->info.proto == PROTO_TCP_SERVER);
1566 ASSERT (!sock->inetd);
1567 sock->sd = accept_from->sd;
1568 }
1569
1570 if (false)
1571 ;
1572 /* are we running in HTTP proxy mode? */
1573 else if (sock->http_proxy)
1574 {
1575 ASSERT (sock->info.proto == PROTO_TCP_CLIENT);
1576 ASSERT (!sock->inetd);
1577
1578 /* the proxy server */
1579 sock->remote_host = http_proxy->options.server;
1580 sock->remote_port = http_proxy->options.port;
1581
1582 /* the OpenVPN server we will use the proxy to connect to */
1583 sock->proxy_dest_host = remote_host;
1584 sock->proxy_dest_port = remote_port;
1585 }
1586 /* or in Socks proxy mode? */
1587 else if (sock->socks_proxy)
1588 {
1589 ASSERT (!sock->inetd);
1590
1591 /* the proxy server */
1592 sock->remote_host = socks_proxy->server;
1593 sock->remote_port = socks_proxy->port;
1594
1595 /* the OpenVPN server we will use the proxy to connect to */
1596 sock->proxy_dest_host = remote_host;
1597 sock->proxy_dest_port = remote_port;
1598 }
1599 else
1600 {
1601 sock->remote_host = remote_host;
1602 sock->remote_port = remote_port;
1603 }
1604
1605 /* bind behavior for TCP server vs. client */
1606 if (sock->info.proto == PROTO_TCP_SERVER)
1607 {
1608 if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1609 sock->bind_local = false;
1610 else
1611 sock->bind_local = true;
1612 }
1613
1614 /* were we started by inetd or xinetd? */
1615 if (sock->inetd)
1616 {
1617 ASSERT (sock->info.proto != PROTO_TCP_CLIENT);
1618 ASSERT (socket_defined (inetd_socket_descriptor));
1619 sock->sd = inetd_socket_descriptor;
1620 }
1621 else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1622 {
1623 if (sock->bind_local) {
1624 resolve_bind_local (sock, sock->info.af);
1625 }
1626 resolve_remote (sock, 1, NULL, NULL);
1627 }
1628 }
1629
1630 static
1631 void phase2_inetd (struct link_socket* sock, const struct frame *frame,
1632 const char *remote_dynamic, volatile int *signal_received)
1633 {
1634 bool remote_changed = false;
1635
1636 if (sock->info.proto == PROTO_TCP_SERVER) {
1637 /* AF_INET as default (and fallback) for inetd */
1638 sock->info.lsa->actual.dest.addr.sa.sa_family = AF_INET;
1639 #ifdef HAVE_GETSOCKNAME
1640 {
1641 /* inetd: hint family type for dest = local's */
1642 struct openvpn_sockaddr local_addr;
1643 socklen_t addrlen = sizeof(local_addr);
1644 if (getsockname (sock->sd, &local_addr.addr.sa, &addrlen) == 0) {
1645 sock->info.lsa->actual.dest.addr.sa.sa_family = local_addr.addr.sa.sa_family;
1646 dmsg (D_SOCKET_DEBUG, "inetd(%s): using sa_family=%d from getsockname(%d)",
1647 proto2ascii(sock->info.proto, sock->info.af, false),
1648 local_addr.addr.sa.sa_family, sock->sd);
1649 } else
1650 msg (M_WARN, "inetd(%s): getsockname(%d) failed, using AF_INET",
1651 proto2ascii(sock->info.proto, sock->info.af, false), sock->sd);
1652 }
1653 #else
1654 msg (M_WARN, "inetd(%s): this OS does not provide the getsockname() "
1655 "function, using AF_INET",
1656 proto2ascii(sock->info.proto, false));
1657 #endif
1658 sock->sd =
1659 socket_listen_accept (sock->sd,
1660 &sock->info.lsa->actual,
1661 remote_dynamic,
1662 sock->info.lsa->bind_local,
1663 false,
1664 sock->inetd == INETD_NOWAIT,
1665 signal_received);
1666
1667 }
1668 ASSERT (!remote_changed);
1669 }
1670
1671 static void
1672 phase2_set_socket_flags (struct link_socket* sock)
1673 {
1674 /* set misc socket parameters */
1675 socket_set_flags (sock->sd, sock->sockflags);
1676
1677 /* set socket to non-blocking mode */
1678 set_nonblock (sock->sd);
1679
1680 /* set socket file descriptor to not pass across execs, so that
1681 scripts don't have access to it */
1682 set_cloexec (sock->sd);
1683
1684 if (socket_defined (sock->ctrl_sd))
1685 set_cloexec (sock->ctrl_sd);
1686
1687 /* set Path MTU discovery options on the socket */
1688 set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
1689
1690 #if EXTENDED_SOCKET_ERROR_CAPABILITY
1691 /* if the OS supports it, enable extended error passing on the socket */
1692 set_sock_extended_error_passing (sock->sd);
1693 #endif
1694 }
1695
1696
1697 static void
1698 linksock_print_addr (struct link_socket *sock)
1699 {
1700 struct gc_arena gc = gc_new ();
1701 const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
1702
1703 /* print local address */
1704 if (sock->inetd)
1705 msg (msglevel, "%s link local: [inetd]", proto2ascii (sock->info.proto, sock->info.af, true));
1706 else if (sock->bind_local)
1707 {
1708 sa_family_t ai_family = sock->info.lsa->actual.dest.addr.sa.sa_family;
1709 /* Socket is always bound on the first matching address,
1710 * For bound sockets with no remote addr this is the element of
1711 * the list */
1712 struct addrinfo *cur;
1713 for (cur = sock->info.lsa->bind_local; cur; cur=cur->ai_next)
1714 {
1715 if(!ai_family || ai_family == cur->ai_family)
1716 break;
1717 }
1718 ASSERT (cur);
1719 msg (msglevel, "%s link local (bound): %s",
1720 proto2ascii (sock->info.proto, sock->info.af, true),
1721 print_sockaddr(cur->ai_addr,&gc));
1722 }
1723 else
1724 msg (msglevel, "%s link local: (not bound)",
1725 proto2ascii (sock->info.proto, sock->info.af, true));
1726
1727 /* print active remote address */
1728 msg (msglevel, "%s link remote: %s",
1729 proto2ascii (sock->info.proto, sock->info.af, true),
1730 print_link_socket_actual_ex (&sock->info.lsa->actual,
1731 ":",
1732 PS_SHOW_PORT_IF_DEFINED,
1733 &gc));
1734 gc_free(&gc);
1735 }
1736
1737 static void
1738 phase2_tcp_server (struct link_socket *sock, const char *remote_dynamic,
1739 volatile int *signal_received)
1740 {
1741 switch (sock->mode)
1742 {
1743 case LS_MODE_DEFAULT:
1744 sock->sd = socket_listen_accept (sock->sd,
1745 &sock->info.lsa->actual,
1746 remote_dynamic,
1747 sock->info.lsa->bind_local,
1748 true,
1749 false,
1750 signal_received);
1751 break;
1752 case LS_MODE_TCP_LISTEN:
1753 socket_do_listen (sock->sd,
1754 sock->info.lsa->bind_local,
1755 true,
1756 false);
1757 break;
1758 case LS_MODE_TCP_ACCEPT_FROM:
1759 sock->sd = socket_do_accept (sock->sd,
1760 &sock->info.lsa->actual,
1761 false);
1762 if (!socket_defined (sock->sd))
1763 {
1764 *signal_received = SIGTERM;
1765 return;
1766 }
1767 tcp_connection_established (&sock->info.lsa->actual);
1768 break;
1769 default:
1770 ASSERT (0);
1771 }
1772 }
1773
1774
1775 static void
1776 phase2_tcp_client (struct link_socket *sock, struct signal_info *sig_info)
1777 {
1778 bool proxy_retry = false;
1779 do {
1780 socket_connect (&sock->sd,
1781 sock->info.lsa->current_remote->ai_addr,
1782 sock->connect_timeout,
1783 sig_info);
1784
1785 if (sig_info->signal_received)
1786 return;
1787
1788 if (false)
1789 ;
1790 else if (sock->http_proxy)
1791 {
1792 proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
1793 sock->sd,
1794 sock->proxy_dest_host,
1795 sock->proxy_dest_port,
1796 &sock->stream_buf.residual,
1797 &sig_info->signal_received);
1798 }
1799 else if (sock->socks_proxy)
1800 {
1801 establish_socks_proxy_passthru (sock->socks_proxy,
1802 sock->sd,
1803 sock->proxy_dest_host,
1804 sock->proxy_dest_port,
1805 &sig_info->signal_received);
1806 }
1807 if (proxy_retry)
1808 {
1809 openvpn_close_socket (sock->sd);
1810 sock->sd = create_socket_tcp (sock->info.lsa->current_remote);
1811 }
1812
1813 } while (proxy_retry);
1814
1815 }
1816
1817 static void
1818 phase2_socks_client (struct link_socket *sock, struct signal_info *sig_info)
1819 {
1820 socket_connect (&sock->ctrl_sd,
1821 sock->info.lsa->current_remote->ai_addr,
1822 sock->connect_timeout,
1823 sig_info);
1824
1825 if (sig_info->signal_received)
1826 return;
1827
1828 establish_socks_proxy_udpassoc (sock->socks_proxy,
1829 sock->ctrl_sd,
1830 sock->sd,
1831 &sock->socks_relay.dest,
1832 &sig_info->signal_received);
1833
1834 if (sig_info->signal_received)
1835 return;
1836
1837 sock->remote_host = sock->proxy_dest_host;
1838 sock->remote_port = sock->proxy_dest_port;
1839
1840 addr_zero_host(&sock->info.lsa->actual.dest);
1841 if (sock->info.lsa->remote_list)
1842 {
1843 freeaddrinfo(sock->info.lsa->remote_list);
1844 sock->info.lsa->current_remote = NULL;
1845 sock->info.lsa->remote_list = NULL;
1846 }
1847
1848 resolve_remote (sock, 1, NULL, &sig_info->signal_received);
1849 }
1850
1851 /* finalize socket initialization */
1852 void
1853 link_socket_init_phase2 (struct link_socket *sock,
1854 const struct frame *frame,
1855 struct signal_info *sig_info)
1856 {
1857 const char *remote_dynamic = NULL;
1858 int sig_save = 0;
1859
1860 ASSERT (sock);
1861
1862 if (sig_info && sig_info->signal_received)
1863 {
1864 sig_save = sig_info->signal_received;
1865 sig_info->signal_received = 0;
1866 }
1867
1868 /* initialize buffers */
1869 socket_frame_init (frame, sock);
1870
1871 /*
1872 * Pass a remote name to connect/accept so that
1873 * they can test for dynamic IP address changes
1874 * and throw a SIGUSR1 if appropriate.
1875 */
1876 if (sock->resolve_retry_seconds)
1877 remote_dynamic = sock->remote_host;
1878
1879 /* were we started by inetd or xinetd? */
1880 if (sock->inetd)
1881 {
1882 phase2_inetd (sock, frame, remote_dynamic, &sig_info->signal_received);
1883 if (sig_info && sig_info->signal_received)
1884 goto done;
1885
1886 }
1887 else
1888 {
1889 /* Second chance to resolv/create socket */
1890 resolve_remote (sock, 2, &remote_dynamic, &sig_info->signal_received);
1891
1892 /* If a valid remote has been found, create the socket with its addrinfo */
1893 if (sock->info.lsa->current_remote)
1894 create_socket (sock, sock->info.lsa->current_remote);
1895
1896 /* If socket has not already been created create it now */
1897 if (sock->sd == SOCKET_UNDEFINED)
1898 {
1899 /* If we have no --remote and have still not figured out the
1900 * protocol family to use we will use the first of the bind */
1901
1902 if (sock->bind_local && !sock->remote_host && sock->info.lsa->bind_local)
1903 {
1904 /* Warn if this is because neither v4 or v6 was specified
1905 * and we should not connect a remote */
1906 if (sock->info.af == AF_UNSPEC)
1907 msg (M_WARN, "Could not determine IPv4/IPv6 protocol. Using %s",
1908 addr_family_name(sock->info.lsa->bind_local->ai_family));
1909
1910 create_socket (sock, sock->info.lsa->bind_local);
1911 }
1912 }
1913
1914 /* Socket still undefined, give a warning and abort connection */
1915 if (sock->sd == SOCKET_UNDEFINED)
1916 {
1917 msg (M_WARN, "Could not determine IPv4/IPv6 protocol");
1918 sig_info->signal_received = SIGUSR1;
1919 goto done;
1920 }
1921
1922 if (sig_info && sig_info->signal_received)
1923 goto done;
1924
1925 if (sock->info.proto == PROTO_TCP_SERVER)
1926 {
1927 phase2_tcp_server (sock, remote_dynamic,
1928 &sig_info->signal_received);
1929 }
1930 else if (sock->info.proto == PROTO_TCP_CLIENT)
1931 {
1932 phase2_tcp_client (sock, sig_info);
1933
1934 }
1935 else if (sock->info.proto == PROTO_UDP && sock->socks_proxy)
1936 {
1937 phase2_socks_client (sock, sig_info);
1938 }
1939 #ifdef TARGET_ANDROID
1940 if (sock->sd != -1)
1941 protect_fd_nonlocal (sock->sd, &sock->info.lsa->actual.dest.addr.sa);
1942 #endif
1943 if (sig_info && sig_info->signal_received)
1944 goto done;
1945 }
1946
1947 phase2_set_socket_flags(sock);
1948 linksock_print_addr(sock);
1949
1950 done:
1951 if (sig_save && sig_info)
1952 {
1953 if (!sig_info->signal_received)
1954 sig_info->signal_received = sig_save;
1955 }
1956 }
1957
1958 void
1959 link_socket_close (struct link_socket *sock)
1960 {
1961 if (sock)
1962 {
1963 #ifdef ENABLE_DEBUG
1964 const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1965 #else
1966 const int gremlin = 0;
1967 #endif
1968
1969 if (socket_defined (sock->sd))
1970 {
1971 #ifdef WIN32
1972 close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1973 #endif
1974 if (!gremlin)
1975 {
1976 msg (D_LOW, "TCP/UDP: Closing socket");
1977 if (openvpn_close_socket (sock->sd))
1978 msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
1979 }
1980 sock->sd = SOCKET_UNDEFINED;
1981 #ifdef WIN32
1982 if (!gremlin)
1983 {
1984 overlapped_io_close (&sock->reads);
1985 overlapped_io_close (&sock->writes);
1986 }
1987 #endif
1988 }
1989
1990 if (socket_defined (sock->ctrl_sd))
1991 {
1992 if (openvpn_close_socket (sock->ctrl_sd))
1993 msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
1994 sock->ctrl_sd = SOCKET_UNDEFINED;
1995 }
1996
1997 stream_buf_close (&sock->stream_buf);
1998 free_buf (&sock->stream_buf_data);
1999 if (!gremlin)
2000 free (sock);
2001 }
2002 }
2003
2004 /* for stream protocols, allow for packet length prefix */
2005 void
2006 socket_adjust_frame_parameters (struct frame *frame, int proto)
2007 {
2008 if (link_socket_proto_connection_oriented (proto))
2009 frame_add_to_extra_frame (frame, sizeof (packet_size_type));
2010 }
2011
2012 void
2013 setenv_trusted (struct env_set *es, const struct link_socket_info *info)
2014 {
2015 setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
2016 }
2017
2018 static void
2019 ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
2020 {
2021 const char *host = print_sockaddr_ex (&info->lsa->actual.dest.addr.sa, " ", PS_SHOW_PORT , gc);
2022 if (include_cmd)
2023 argv_printf (argv, "%sc %s",
2024 info->ipchange_command,
2025 host);
2026 else
2027 argv_printf (argv, "%s", host);
2028
2029 }
2030
2031 void
2032 link_socket_connection_initiated (const struct buffer *buf,
2033 struct link_socket_info *info,
2034 const struct link_socket_actual *act,
2035 const char *common_name,
2036 struct env_set *es)
2037 {
2038 struct gc_arena gc = gc_new ();
2039
2040 info->lsa->actual = *act; /* Note: skip this line for --force-dest */
2041 setenv_trusted (es, info);
2042 info->connection_established = true;
2043
2044 /* Print connection initiated message, with common name if available */
2045 {
2046 struct buffer out = alloc_buf_gc (256, &gc);
2047 if (common_name)
2048 buf_printf (&out, "[%s] ", common_name);
2049 buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
2050 msg (M_INFO, "%s", BSTR (&out));
2051 }
2052
2053 /* set environmental vars */
2054 setenv_str (es, "common_name", common_name);
2055
2056 /* Process --ipchange plugin */
2057 if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
2058 {
2059 struct argv argv = argv_new ();
2060 ipchange_fmt (false, &argv, info, &gc);
2061 if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
2062 msg (M_WARN, "WARNING: ipchange plugin call failed");
2063 argv_reset (&argv);
2064 }
2065
2066 /* Process --ipchange option */
2067 if (info->ipchange_command)
2068 {
2069 struct argv argv = argv_new ();
2070 setenv_str (es, "script_type", "ipchange");
2071 ipchange_fmt (true, &argv, info, &gc);
2072 openvpn_run_script (&argv, es, 0, "--ipchange");
2073 argv_reset (&argv);
2074 }
2075
2076 gc_free (&gc);
2077 }
2078
2079 void
2080 link_socket_bad_incoming_addr (struct buffer *buf,
2081 const struct link_socket_info *info,
2082 const struct link_socket_actual *from_addr)
2083 {
2084 struct gc_arena gc = gc_new ();
2085 struct addrinfo* ai;
2086
2087 switch(from_addr->dest.addr.sa.sa_family)
2088 {
2089 case AF_INET:
2090 case AF_INET6:
2091 msg (D_LINK_ERRORS,
2092 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2093 print_link_socket_actual (from_addr, &gc),
2094 (int)from_addr->dest.addr.sa.sa_family,
2095 print_sockaddr_ex (info->lsa->remote_list->ai_addr,":" ,PS_SHOW_PORT, &gc));
2096 /* print additional remote addresses */
2097 for(ai=info->lsa->remote_list->ai_next;ai;ai=ai->ai_next) {
2098 msg(D_LINK_ERRORS,"or from peer address: %s",
2099 print_sockaddr_ex(ai->ai_addr,":",PS_SHOW_PORT, &gc));
2100 }
2101 break;
2102 }
2103 buf->len = 0;
2104 gc_free (&gc);
2105 }
2106
2107 void
2108 link_socket_bad_outgoing_addr (void)
2109 {
2110 dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
2111 }
2112
2113 in_addr_t
2114 link_socket_current_remote (const struct link_socket_info *info)
2115 {
2116 const struct link_socket_addr *lsa = info->lsa;
2117
2118 /*
2119 * This logic supports "redirect-gateway" semantic, which
2120 * makes sense only for PF_INET routes over PF_INET endpoints
2121 *
2122 * Maybe in the future consider PF_INET6 endpoints also ...
2123 * by now just ignore it
2124 *
2125 * For --remote entries with multiple addresses this
2126 * only return the actual endpoint we have sucessfully connected to
2127 */
2128 if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
2129 return IPV4_INVALID_ADDR;
2130
2131 if (link_socket_actual_defined (&lsa->actual))
2132 return ntohl (lsa->actual.dest.addr.in4.sin_addr.s_addr);
2133 else if (lsa->current_remote)
2134 return ntohl (((struct sockaddr_in*)lsa->current_remote->ai_addr)
2135 ->sin_addr.s_addr);
2136 else
2137 return 0;
2138 }
2139
2140 /*
2141 * Return a status string describing socket state.
2142 */
2143 const char *
2144 socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
2145 {
2146 struct buffer out = alloc_buf_gc (64, gc);
2147 if (s)
2148 {
2149 if (rwflags & EVENT_READ)
2150 {
2151 buf_printf (&out, "S%s",
2152 (s->rwflags_debug & EVENT_READ) ? "R" : "r");
2153 #ifdef WIN32
2154 buf_printf (&out, "%s",
2155 overlapped_io_state_ascii (&s->reads));
2156 #endif
2157 }
2158 if (rwflags & EVENT_WRITE)
2159 {
2160 buf_printf (&out, "S%s",
2161 (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
2162 #ifdef WIN32
2163 buf_printf (&out, "%s",
2164 overlapped_io_state_ascii (&s->writes));
2165 #endif
2166 }
2167 }
2168 else
2169 {
2170 buf_printf (&out, "S?");
2171 }
2172 return BSTR (&out);
2173 }
2174
2175 /*
2176 * Stream buffer functions, used to packetize a TCP
2177 * stream connection.
2178 */
2179
2180 static inline void
2181 stream_buf_reset (struct stream_buf *sb)
2182 {
2183 dmsg (D_STREAM_DEBUG, "STREAM: RESET");
2184 sb->residual_fully_formed = false;
2185 sb->buf = sb->buf_init;
2186 buf_reset (&sb->next);
2187 sb->len = -1;
2188 }
2189
2190 void
2191 stream_buf_init (struct stream_buf *sb,
2192 struct buffer *buf,
2193 const unsigned int sockflags,
2194 const int proto)
2195 {
2196 sb->buf_init = *buf;
2197 sb->maxlen = sb->buf_init.len;
2198 sb->buf_init.len = 0;
2199 sb->residual = alloc_buf (sb->maxlen);
2200 sb->error = false;
2201 #if PORT_SHARE
2202 sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCP_SERVER))
2203 ? PS_ENABLED
2204 : PS_DISABLED;
2205 #endif
2206 stream_buf_reset (sb);
2207
2208 dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
2209 }
2210
2211 static inline void
2212 stream_buf_set_next (struct stream_buf *sb)
2213 {
2214 /* set up 'next' for next i/o read */
2215 sb->next = sb->buf;
2216 sb->next.offset = sb->buf.offset + sb->buf.len;
2217 sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
2218 dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2219 sb->buf.offset, sb->buf.len,
2220 sb->next.offset, sb->next.len,
2221 sb->len, sb->maxlen);
2222 ASSERT (sb->next.len > 0);
2223 ASSERT (buf_safe (&sb->buf, sb->next.len));
2224 }
2225
2226 static inline void
2227 stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
2228 {
2229 dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
2230 buf_defined (&sb->buf) ? sb->buf.len : -1);
2231 ASSERT (buf_defined (&sb->buf));
2232 *buf = sb->buf;
2233 }
2234
2235 static inline void
2236 stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
2237 {
2238 dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
2239 buf_defined (&sb->next) ? sb->next.len : -1);
2240 ASSERT (buf_defined (&sb->next));
2241 *buf = sb->next;
2242 }
2243
2244 bool
2245 stream_buf_read_setup_dowork (struct link_socket* sock)
2246 {
2247 if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
2248 {
2249 ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
2250 ASSERT (buf_init (&sock->stream_buf.residual, 0));
2251 sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
2252 dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2253 sock->stream_buf.residual_fully_formed ? "YES" : "NO",
2254 sock->stream_buf.residual.len);
2255 }
2256
2257 if (!sock->stream_buf.residual_fully_formed)
2258 stream_buf_set_next (&sock->stream_buf);
2259 return !sock->stream_buf.residual_fully_formed;
2260 }
2261
2262 bool
2263 stream_buf_added (struct stream_buf *sb,
2264 int length_added)
2265 {
2266 dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
2267 if (length_added > 0)
2268 sb->buf.len += length_added;
2269
2270 /* if length unknown, see if we can get the length prefix from
2271 the head of the buffer */
2272 if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
2273 {
2274 packet_size_type net_size;
2275
2276 #if PORT_SHARE
2277 if (sb->port_share_state == PS_ENABLED)
2278 {
2279 if (!is_openvpn_protocol (&sb->buf))
2280 {
2281 msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
2282 sb->port_share_state = PS_FOREIGN;
2283 sb->error = true;
2284 return false;
2285 }
2286 else
2287 sb->port_share_state = PS_DISABLED;
2288 }
2289 #endif
2290
2291 ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
2292 sb->len = ntohps (net_size);
2293
2294 if (sb->len < 1 || sb->len > sb->maxlen)
2295 {
2296 msg (M_WARN, "WARNING: Bad encapsulated packet length from peer (%d), which must be > 0 and <= %d -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link -- [Attempting restart...]", sb->len, sb->maxlen);
2297 stream_buf_reset (sb);
2298 sb->error = true;
2299 return false;
2300 }
2301 }
2302
2303 /* is our incoming packet fully read? */
2304 if (sb->len > 0 && sb->buf.len >= sb->len)
2305 {
2306 /* save any residual data that's part of the next packet */
2307 ASSERT (buf_init (&sb->residual, 0));
2308 if (sb->buf.len > sb->len)
2309 ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
2310 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2311 BLEN (&sb->buf),
2312 BLEN (&sb->residual));
2313 return true;
2314 }
2315 else
2316 {
2317 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
2318 stream_buf_set_next (sb);
2319 return false;
2320 }
2321 }
2322
2323 void
2324 stream_buf_close (struct stream_buf* sb)
2325 {
2326 free_buf (&sb->residual);
2327 }
2328
2329 /*
2330 * The listen event is a special event whose sole purpose is
2331 * to tell us that there's a new incoming connection on a
2332 * TCP socket, for use in server mode.
2333 */
2334 event_t
2335 socket_listen_event_handle (struct link_socket *s)
2336 {
2337 #ifdef WIN32
2338 if (!defined_net_event_win32 (&s->listen_handle))
2339 init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
2340 return &s->listen_handle;
2341 #else
2342 return s->sd;
2343 #endif
2344 }
2345
2346 /*
2347 * Format IP addresses in ascii
2348 */
2349
2350 const char *
2351 print_sockaddr_ex (const struct sockaddr *sa,
2352 const char* separator,
2353 const unsigned int flags,
2354 struct gc_arena *gc)
2355 {
2356 struct buffer out = alloc_buf_gc (128, gc);
2357 bool addr_is_defined = false;
2358 char hostaddr[NI_MAXHOST] = "";
2359 char servname[NI_MAXSERV] = "";
2360 int status;
2361
2362 socklen_t salen = 0;
2363 switch(sa->sa_family)
2364 {
2365 case AF_INET:
2366 buf_puts (&out, "[AF_INET]");
2367 salen = sizeof (struct sockaddr_in);
2368 addr_is_defined = ((struct sockaddr_in*) sa)->sin_addr.s_addr != 0;
2369 break;
2370 case AF_INET6:
2371 buf_puts (&out, "[AF_INET6]");
2372 salen = sizeof (struct sockaddr_in6);
2373 addr_is_defined = !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6*) sa)->sin6_addr);
2374 break;
2375 case AF_UNSPEC:
2376 return "[AF_UNSPEC]";
2377 default:
2378 ASSERT(0);
2379 }
2380
2381 status = getnameinfo(sa, salen, hostaddr, sizeof (hostaddr),
2382 servname, sizeof(servname), NI_NUMERICHOST | NI_NUMERICSERV);
2383
2384 if(status!=0) {
2385 buf_printf(&out,"[nameinfo() err: %s]",gai_strerror(status));
2386 return BSTR(&out);
2387 }
2388
2389 if (!(flags & PS_DONT_SHOW_ADDR))
2390 {
2391 if (addr_is_defined)
2392 buf_puts (&out, hostaddr);
2393 else
2394 buf_puts (&out, "[undef]");
2395 }
2396
2397 if ((flags & PS_SHOW_PORT) || (flags & PS_SHOW_PORT_IF_DEFINED))
2398 {
2399 if (separator)
2400 buf_puts (&out, separator);
2401
2402 buf_puts (&out, servname);
2403 }
2404
2405 return BSTR (&out);
2406 }
2407
2408 const char *
2409 print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
2410 {
2411 return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
2412 }
2413
2414 #ifndef IF_NAMESIZE
2415 #define IF_NAMESIZE 16
2416 #endif
2417
2418 const char *
2419 print_link_socket_actual_ex (const struct link_socket_actual *act,
2420 const char *separator,
2421 const unsigned int flags,
2422 struct gc_arena *gc)
2423 {
2424 if (act)
2425 {
2426 char ifname[IF_NAMESIZE] = "[undef]";
2427 struct buffer out = alloc_buf_gc (128, gc);
2428 buf_printf (&out, "%s", print_sockaddr_ex (&act->dest.addr.sa, separator, flags, gc));
2429 #if ENABLE_IP_PKTINFO
2430 if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
2431 {
2432 switch(act->dest.addr.sa.sa_family)
2433 {
2434 case AF_INET:
2435 {
2436 struct openvpn_sockaddr sa;
2437 CLEAR (sa);
2438 sa.addr.in4.sin_family = AF_INET;
2439 #ifdef IP_PKTINFO
2440 sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
2441 if_indextoname(act->pi.in4.ipi_ifindex, ifname);
2442 #elif defined(IP_RECVDSTADDR)
2443 sa.addr.in4.sin_addr = act->pi.in4;
2444 ifname[0]=0;
2445 #else
2446 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2447 #endif
2448 buf_printf (&out, " (via %s%%%s)",
2449 print_sockaddr_ex (&sa.addr.sa, separator, 0, gc),
2450 ifname);
2451 }
2452 break;
2453 case AF_INET6:
2454 {
2455 struct sockaddr_in6 sin6;
2456 char buf[INET6_ADDRSTRLEN] = "[undef]";
2457 CLEAR(sin6);
2458 sin6.sin6_family = AF_INET6;
2459 sin6.sin6_addr = act->pi.in6.ipi6_addr;
2460 if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
2461 if (getnameinfo((struct sockaddr *)&sin6, sizeof (struct sockaddr_in6),
2462 buf, sizeof (buf), NULL, 0, NI_NUMERICHOST) == 0)
2463 buf_printf (&out, " (via %s%%%s)", buf, ifname);
2464 else
2465 buf_printf (&out, " (via [getnameinfo() err]%%%s)", ifname);
2466 }
2467 break;
2468 }
2469 }
2470 #endif
2471 return BSTR (&out);
2472 }
2473 else
2474 return "[NULL]";
2475 }
2476
2477 /*
2478 * Convert an in_addr_t in host byte order
2479 * to an ascii dotted quad.
2480 */
2481 const char *
2482 print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2483 {
2484 struct in_addr ia;
2485 struct buffer out = alloc_buf_gc (64, gc);
2486
2487 if (addr || !(flags & IA_EMPTY_IF_UNDEF))
2488 {
2489 CLEAR (ia);
2490 ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
2491
2492 buf_printf (&out, "%s", inet_ntoa (ia));
2493 }
2494 return BSTR (&out);
2495 }
2496
2497 /*
2498 * Convert an in6_addr in host byte order
2499 * to an ascii representation of an IPv6 address
2500 */
2501 const char *
2502 print_in6_addr (struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
2503 {
2504 struct buffer out = alloc_buf_gc (64, gc);
2505 char tmp_out_buf[64]; /* inet_ntop wants pointer to buffer */
2506
2507 if ( memcmp(&a6, &in6addr_any, sizeof(a6)) != 0 ||
2508 !(flags & IA_EMPTY_IF_UNDEF))
2509 {
2510 inet_ntop (AF_INET6, &a6, tmp_out_buf, sizeof(tmp_out_buf)-1);
2511 buf_printf (&out, "%s", tmp_out_buf );
2512 }
2513 return BSTR (&out);
2514 }
2515
2516 #ifndef UINT8_MAX
2517 # define UINT8_MAX 0xff
2518 #endif
2519
2520 /* add some offset to an ipv6 address
2521 * (add in steps of 8 bits, taking overflow into next round)
2522 */
2523 struct in6_addr add_in6_addr( struct in6_addr base, uint32_t add )
2524 {
2525 int i;
2526
2527 for( i=15; i>=0 && add > 0 ; i-- )
2528 {
2529 register int carry;
2530 register uint32_t h;
2531
2532 h = (unsigned char) base.s6_addr[i];
2533 base.s6_addr[i] = (h+add) & UINT8_MAX;
2534
2535 /* using explicit carry for the 8-bit additions will catch
2536 * 8-bit and(!) 32-bit overruns nicely
2537 */
2538 carry = ((h & 0xff) + (add & 0xff)) >> 8;
2539 add = (add>>8) + carry;
2540 }
2541 return base;
2542 }
2543
2544 /* set environmental variables for ip/port in *addr */
2545 void
2546 setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
2547 {
2548 char name_buf[256];
2549
2550 char buf[128];
2551 switch(addr->addr.sa.sa_family)
2552 {
2553 case AF_INET:
2554 if (flags & SA_IP_PORT)
2555 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
2556 else
2557 openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
2558
2559 setenv_str (es, name_buf, inet_ntoa (addr->addr.in4.sin_addr));
2560
2561 if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
2562 {
2563 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
2564 setenv_int (es, name_buf, ntohs (addr->addr.in4.sin_port));
2565 }
2566 break;
2567 case AF_INET6:
2568 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip6", name_prefix);
2569 getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
2570 buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
2571 setenv_str (es, name_buf, buf);
2572
2573 if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
2574 {
2575 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
2576 setenv_int (es, name_buf, ntohs (addr->addr.in6.sin6_port));
2577 }
2578 break;
2579 }
2580 }
2581
2582 void
2583 setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
2584 {
2585 if (addr || !(flags & SA_SET_IF_NONZERO))
2586 {
2587 struct openvpn_sockaddr si;
2588 CLEAR (si);
2589 si.addr.in4.sin_family = AF_INET;
2590 si.addr.in4.sin_addr.s_addr = htonl (addr);
2591 setenv_sockaddr (es, name_prefix, &si, flags);
2592 }
2593 }
2594
2595 void
2596 setenv_link_socket_actual (struct env_set *es,
2597 const char *name_prefix,
2598 const struct link_socket_actual *act,
2599 const unsigned int flags)
2600 {
2601 setenv_sockaddr (es, name_prefix, &act->dest, flags);
2602 }
2603
2604 /*
2605 * Convert protocol names between index and ascii form.
2606 */
2607
2608 struct proto_names {
2609 const char *short_form;
2610 const char *display_form;
2611 sa_family_t proto_af;
2612 int proto;
2613 };
2614
2615 /* Indexed by PROTO_x */
2616 static const struct proto_names proto_names[] = {
2617 {"proto-uninitialized", "proto-NONE", AF_UNSPEC, PROTO_NONE},
2618 /* try IPv4 and IPv6 (client), bind dual-stack (server) */
2619 {"udp", "UDP", AF_UNSPEC, PROTO_UDP},
2620 {"tcp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
2621 {"tcp-client", "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
2622 {"tcp", "TCP", AF_UNSPEC, PROTO_TCP},
2623 /* force IPv4 */
2624 {"udp4", "UDPv4", AF_INET, PROTO_UDP},
2625 {"tcp4-server","TCPv4_SERVER", AF_INET, PROTO_TCP_SERVER},
2626 {"tcp4-client","TCPv4_CLIENT", AF_INET, PROTO_TCP_CLIENT},
2627 {"tcp4", "TCPv4", AF_INET, PROTO_TCP},
2628 /* force IPv6 */
2629 {"udp6" ,"UDPv6", AF_INET6, PROTO_UDP},
2630 {"tcp6-server","TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
2631 {"tcp6-client","TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
2632 {"tcp6" ,"TCPv6", AF_INET6, PROTO_TCP},
2633 };
2634
2635 bool
2636 proto_is_net(int proto)
2637 {
2638 if (proto < 0 || proto >= PROTO_N)
2639 ASSERT(0);
2640 return proto != PROTO_NONE;
2641 }
2642 bool
2643 proto_is_dgram(int proto)
2644 {
2645 return proto_is_udp(proto);
2646 }
2647
2648 bool
2649 proto_is_udp(int proto)
2650 {
2651 if (proto < 0 || proto >= PROTO_N)
2652 ASSERT(0);
2653 return proto == PROTO_UDP;
2654 }
2655
2656 bool
2657 proto_is_tcp(int proto)
2658 {
2659 if (proto < 0 || proto >= PROTO_N)
2660 ASSERT(0);
2661 return proto == PROTO_TCP_CLIENT || proto == PROTO_TCP_SERVER || proto == PROTO_TCP_CLIENT;
2662 }
2663
2664 int
2665 ascii2proto (const char* proto_name)
2666 {
2667 int i;
2668 for (i = 0; i < SIZE (proto_names); ++i)
2669 if (!strcmp (proto_name, proto_names[i].short_form))
2670 return proto_names[i].proto;
2671 return -1;
2672 }
2673
2674 sa_family_t
2675 ascii2af (const char* proto_name)
2676 {
2677 int i;
2678 for (i = 0; i < SIZE (proto_names); ++i)
2679 if (!strcmp (proto_name, proto_names[i].short_form))
2680 return proto_names[i].proto_af;
2681 return 0;
2682 }
2683
2684 const char *
2685 proto2ascii (int proto, sa_family_t af, bool display_form)
2686 {
2687 unsigned int i;
2688 for (i = 0; i < SIZE (proto_names); ++i)
2689 {
2690 if(proto_names[i].proto_af == af && proto_names[i].proto == proto)
2691 {
2692 if(display_form)
2693 return proto_names[i].display_form;
2694 else
2695 return proto_names[i].short_form;
2696 }
2697 }
2698
2699 return "[unknown protocol]";
2700 }
2701
2702 const char *
2703 proto2ascii_all (struct gc_arena *gc)
2704 {
2705 struct buffer out = alloc_buf_gc (256, gc);
2706 int i;
2707
2708 for (i = 0; i < SIZE (proto_names); ++i)
2709 {
2710 if (i)
2711 buf_printf(&out, " ");
2712 buf_printf(&out, "[%s]", proto_names[i].short_form);
2713 }
2714 return BSTR (&out);
2715 }
2716
2717 const char *
2718 addr_family_name (int af)
2719 {
2720 switch (af)
2721 {
2722 case AF_INET: return "AF_INET";
2723 case AF_INET6: return "AF_INET6";
2724 }
2725 return "AF_UNSPEC";
2726 }
2727
2728 /*
2729 * Given a local proto, return local proto
2730 * if !remote, or compatible remote proto
2731 * if remote.
2732 *
2733 * This is used for options compatibility
2734 * checking.
2735 *
2736 * IPv6 and IPv4 protocols are comptabile but OpenVPN
2737 * has always sent UDPv4, TCPv4 over the wire. Keep these
2738 * strings for backward compatbility
2739 */
2740 const char*
2741 proto_remote (int proto, bool remote)
2742 {
2743 ASSERT (proto >= 0 && proto < PROTO_N);
2744 if (proto == PROTO_UDP)
2745 return "UDPv4";
2746
2747 if ( (remote && proto == PROTO_TCP_CLIENT) ||
2748 (!remote && proto == PROTO_TCP_SERVER))
2749 return "TCPv4_SERVER";
2750 if ( (remote && proto == PROTO_TCP_SERVER) ||
2751 (!remote && proto == PROTO_TCP_CLIENT))
2752 return "TCPv4_CLIENT";
2753
2754 ASSERT (0);
2755 return ""; /* Make the compiler happy */
2756 }
2757
2758 /*
2759 * Bad incoming address lengths that differ from what
2760 * we expect are considered to be fatal errors.
2761 */
2762 void
2763 bad_address_length (int actual, int expected)
2764 {
2765 msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
2766 actual,
2767 expected);
2768 }
2769
2770 /*
2771 * Socket Read Routines
2772 */
2773
2774 int
2775 link_socket_read_tcp (struct link_socket *sock,
2776 struct buffer *buf)
2777 {
2778 int len = 0;
2779
2780 if (!sock->stream_buf.residual_fully_formed)
2781 {
2782 #ifdef WIN32
2783 len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
2784 #else
2785 struct buffer frag;
2786 stream_buf_get_next (&sock->stream_buf, &frag);
2787 len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
2788 #endif
2789
2790 if (!len)
2791 sock->stream_reset = true;
2792 if (len <= 0)
2793 return buf->len = len;
2794 }
2795
2796 if (sock->stream_buf.residual_fully_formed
2797 || stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
2798 {
2799 stream_buf_get_final (&sock->stream_buf, buf);
2800 stream_buf_reset (&sock->stream_buf);
2801 return buf->len;
2802 }
2803 else
2804 return buf->len = 0; /* no error, but packet is still incomplete */
2805 }
2806
2807 #ifndef WIN32
2808
2809 #if ENABLE_IP_PKTINFO
2810
2811 #pragma pack(1) /* needed to keep structure size consistent for 32 vs. 64-bit architectures */
2812 struct openvpn_in4_pktinfo
2813 {
2814 struct cmsghdr cmsghdr;
2815 #ifdef HAVE_IN_PKTINFO
2816 struct in_pktinfo pi4;
2817 #elif defined(IP_RECVDSTADDR)
2818 struct in_addr pi4;
2819 #endif
2820 };
2821 struct openvpn_in6_pktinfo
2822 {
2823 struct cmsghdr cmsghdr;
2824 struct in6_pktinfo pi6;
2825 };
2826
2827 union openvpn_pktinfo {
2828 struct openvpn_in4_pktinfo msgpi4;
2829 struct openvpn_in6_pktinfo msgpi6;
2830 };
2831 #pragma pack()
2832
2833 static socklen_t
2834 link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
2835 struct buffer *buf,
2836 int maxsize,
2837 struct link_socket_actual *from)
2838 {
2839 struct iovec iov;
2840 union openvpn_pktinfo opi;
2841 struct msghdr mesg;
2842 socklen_t fromlen = sizeof (from->dest.addr);
2843
2844 iov.iov_base = BPTR (buf);
2845 iov.iov_len = maxsize;
2846 mesg.msg_iov = &iov;
2847 mesg.msg_iovlen = 1;
2848 mesg.msg_name = &from->dest.addr;
2849 mesg.msg_namelen = fromlen;
2850 mesg.msg_control = &opi;
2851 mesg.msg_controllen = sizeof opi;
2852 buf->len = recvmsg (sock->sd, &mesg, 0);
2853 if (buf->len >= 0)
2854 {
2855 struct cmsghdr *cmsg;
2856 fromlen = mesg.msg_namelen;
2857 cmsg = CMSG_FIRSTHDR (&mesg);
2858 if (cmsg != NULL
2859 && CMSG_NXTHDR (&mesg, cmsg) == NULL
2860 #ifdef IP_PKTINFO
2861 && cmsg->cmsg_level == SOL_IP
2862 && cmsg->cmsg_type == IP_PKTINFO
2863 #elif defined(IP_RECVDSTADDR)
2864 && cmsg->cmsg_level == IPPROTO_IP
2865 && cmsg->cmsg_type == IP_RECVDSTADDR
2866 #else
2867 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2868 #endif
2869 && cmsg->cmsg_len >= sizeof (struct openvpn_in4_pktinfo))
2870 {
2871 #ifdef IP_PKTINFO
2872 struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2873 from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
2874 from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
2875 #elif defined(IP_RECVDSTADDR)
2876 from->pi.in4 = *(struct in_addr*) CMSG_DATA (cmsg);
2877 #else
2878 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2879 #endif
2880 }
2881 else if (cmsg != NULL
2882 && CMSG_NXTHDR (&mesg, cmsg) == NULL
2883 && cmsg->cmsg_level == IPPROTO_IPV6
2884 && cmsg->cmsg_type == IPV6_PKTINFO
2885 && cmsg->cmsg_len >= sizeof (struct openvpn_in6_pktinfo))
2886 {
2887 struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
2888 from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
2889 from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
2890 }
2891 else if (cmsg != NULL)
2892 {
2893 msg(M_WARN, "CMSG received that cannot be parsed (cmsg_level=%d, cmsg_type=%d, cmsg=len=%d)", (int)cmsg->cmsg_level, (int)cmsg->cmsg_type, (int)cmsg->cmsg_len );
2894 }
2895 }
2896
2897 return fromlen;
2898 }
2899 #endif
2900
2901 int
2902 link_socket_read_udp_posix (struct link_socket *sock,
2903 struct buffer *buf,
2904 int maxsize,
2905 struct link_socket_actual *from)
2906 {
2907 socklen_t fromlen = sizeof (from->dest.addr);
2908 socklen_t expectedlen = af_addr_size(sock->info.af);
2909 addr_zero_host(&from->dest);
2910 ASSERT (buf_safe (buf, maxsize));
2911 #if ENABLE_IP_PKTINFO
2912 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
2913 if (sock->info.proto == PROTO_UDP && sock->sockflags & SF_USE_IP_PKTINFO)
2914 fromlen = link_socket_read_udp_posix_recvmsg (sock, buf, maxsize, from);
2915 else
2916 #endif
2917 buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
2918 &from->dest.addr.sa, &fromlen);
2919 if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
2920 bad_address_length (fromlen, expectedlen);
2921 return buf->len;
2922 }
2923
2924 #endif
2925
2926 /*
2927 * Socket Write Routines
2928 */
2929
2930 int
2931 link_socket_write_tcp (struct link_socket *sock,
2932 struct buffer *buf,
2933 struct link_socket_actual *to)
2934 {
2935 packet_size_type len = BLEN (buf);
2936 dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
2937 ASSERT (len <= sock->stream_buf.maxlen);
2938 len = htonps (len);
2939 ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
2940 #ifdef WIN32
2941 return link_socket_write_win32 (sock, buf, to);
2942 #else
2943 return link_socket_write_tcp_posix (sock, buf, to);
2944 #endif
2945 }
2946
2947 #if ENABLE_IP_PKTINFO
2948
2949 size_t
2950 link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
2951 struct buffer *buf,
2952 struct link_socket_actual *to)
2953 {
2954 struct iovec iov;
2955 struct msghdr mesg;
2956 struct cmsghdr *cmsg;
2957 union openvpn_pktinfo opi;
2958
2959 iov.iov_base = BPTR (buf);
2960 iov.iov_len = BLEN (buf);
2961 mesg.msg_iov = &iov;
2962 mesg.msg_iovlen = 1;
2963 switch (to->dest.addr.sa.sa_family)
2964 {
2965 case AF_INET:
2966 {
2967 mesg.msg_name = &to->dest.addr.sa;
2968 mesg.msg_namelen = sizeof (struct sockaddr_in);
2969 mesg.msg_control = &opi;
2970 mesg.msg_flags = 0;
2971 #ifdef HAVE_IN_PKTINFO
2972 mesg.msg_controllen = sizeof (struct openvpn_in4_pktinfo);
2973 cmsg = CMSG_FIRSTHDR (&mesg);
2974 cmsg->cmsg_len = sizeof (struct openvpn_in4_pktinfo);
2975 cmsg->cmsg_level = SOL_IP;
2976 cmsg->cmsg_type = IP_PKTINFO;
2977 {
2978 struct in_pktinfo *pkti;
2979 pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2980 pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
2981 pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
2982 pkti->ipi_addr.s_addr = 0;
2983 }
2984 #elif defined(IP_RECVDSTADDR)
2985 ASSERT( CMSG_SPACE(sizeof (struct in_addr)) <= sizeof(opi) );
2986 mesg.msg_controllen = CMSG_SPACE(sizeof (struct in_addr));
2987 cmsg = CMSG_FIRSTHDR (&mesg);
2988 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
2989 cmsg->cmsg_level = IPPROTO_IP;
2990 cmsg->cmsg_type = IP_RECVDSTADDR;
2991 *(struct in_addr *) CMSG_DATA (cmsg) = to->pi.in4;
2992 #else
2993 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2994 #endif
2995 break;
2996 }
2997 case AF_INET6:
2998 {
2999 struct in6_pktinfo *pkti6;
3000 mesg.msg_name = &to->dest.addr.sa;
3001 mesg.msg_namelen = sizeof (struct sockaddr_in6);
3002 mesg.msg_control = &opi;
3003 mesg.msg_controllen = sizeof (struct openvpn_in6_pktinfo);
3004 mesg.msg_flags = 0;
3005 cmsg = CMSG_FIRSTHDR (&mesg);
3006 cmsg->cmsg_len = sizeof (struct openvpn_in6_pktinfo);
3007 cmsg->cmsg_level = IPPROTO_IPV6;
3008 cmsg->cmsg_type = IPV6_PKTINFO;
3009 pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
3010 pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
3011 pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
3012 break;
3013 }
3014 default: ASSERT(0);
3015 }
3016 return sendmsg (sock->sd, &mesg, 0);
3017 }
3018
3019 #endif
3020
3021 /*
3022 * Win32 overlapped socket I/O functions.
3023 */
3024
3025 #ifdef WIN32
3026
3027 int
3028 socket_recv_queue (struct link_socket *sock, int maxsize)
3029 {
3030 if (sock->reads.iostate == IOSTATE_INITIAL)
3031 {
3032 WSABUF wsabuf[1];
3033 int status;
3034
3035 /* reset buf to its initial state */
3036 if (proto_is_udp(sock->info.proto))
3037 {
3038 sock->reads.buf = sock->reads.buf_init;
3039 }
3040 else if (proto_is_tcp(sock->info.proto))
3041 {
3042 stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
3043 }
3044 else
3045 {
3046 ASSERT (0);
3047 }
3048
3049 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3050 wsabuf[0].buf = BPTR (&sock->reads.buf);
3051 wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
3052
3053 /* check for buffer overflow */
3054 ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
3055
3056 /* the overlapped read will signal this event on I/O completion */
3057 ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
3058 sock->reads.flags = 0;
3059
3060 if (proto_is_udp(sock->info.proto))
3061 {
3062 sock->reads.addr_defined = true;
3063 if (sock->info.af == AF_INET)
3064 sock->reads.addrlen = sizeof (sock->reads.addr);
3065 else
3066 sock->reads.addrlen = sizeof (sock->reads.addr6);
3067 status = WSARecvFrom(
3068 sock->sd,
3069 wsabuf,
3070 1,
3071 &sock->reads.size,
3072 &sock->reads.flags,
3073 (struct sockaddr *) &sock->reads.addr,
3074 &sock->reads.addrlen,
3075 &sock->reads.overlapped,
3076 NULL);
3077 }
3078 else if (proto_is_tcp(sock->info.proto))
3079 {
3080 sock->reads.addr_defined = false;
3081 status = WSARecv(
3082 sock->sd,
3083 wsabuf,
3084 1,
3085 &sock->reads.size,
3086 &sock->reads.flags,
3087 &sock->reads.overlapped,
3088 NULL);
3089 }
3090 else
3091 {
3092 status = 0;
3093 ASSERT (0);
3094 }
3095
3096 if (!status) /* operation completed immediately? */
3097 {
3098 int addrlen = af_addr_size(sock->info.lsa->local.addr.sa.sa_family);
3099 if (sock->reads.addr_defined && sock->reads.addrlen != addrlen)
3100 bad_address_length (sock->reads.addrlen, addrlen);
3101 sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
3102
3103 /* since we got an immediate return, we must signal the event object ourselves */
3104 ASSERT (SetEvent (sock->reads.overlapped.hEvent));
3105 sock->reads.status = 0;
3106
3107 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3108 (int) wsabuf[0].len,
3109 (int) sock->reads.size);
3110 }
3111 else
3112 {
3113 status = WSAGetLastError ();
3114 if (status == WSA_IO_PENDING) /* operation queued? */
3115 {
3116 sock->reads.iostate = IOSTATE_QUEUED;
3117 sock->reads.status = status;
3118 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
3119 (int) wsabuf[0].len);
3120 }
3121 else /* error occurred */
3122 {
3123 struct gc_arena gc = gc_new ();
3124 ASSERT (SetEvent (sock->reads.overlapped.hEvent));
3125 sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
3126 sock->reads.status = status;
3127 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
3128 (int) wsabuf[0].len,
3129 strerror_win32 (status, &gc));
3130 gc_free (&gc);
3131 }
3132 }
3133 }
3134 return sock->reads.iostate;
3135 }
3136
3137 int
3138 socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
3139 {
3140 if (sock->writes.iostate == IOSTATE_INITIAL)
3141 {
3142 WSABUF wsabuf[1];
3143 int status;
3144
3145 /* make a private copy of buf */
3146 sock->writes.buf = sock->writes.buf_init;
3147 sock->writes.buf.len = 0;
3148 ASSERT (buf_copy (&sock->writes.buf, buf));
3149
3150 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3151 wsabuf[0].buf = BPTR (&sock->writes.buf);
3152 wsabuf[0].len = BLEN (&sock->writes.buf);
3153
3154 /* the overlapped write will signal this event on I/O completion */
3155 ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
3156 sock->writes.flags = 0;
3157
3158 if (proto_is_udp(sock->info.proto))
3159 {
3160 /* set destination address for UDP writes */
3161 sock->writes.addr_defined = true;
3162 if (sock->info.af == AF_INET6)
3163 {
3164 sock->writes.addr6 = to->dest.addr.in6;
3165 sock->writes.addrlen = sizeof (sock->writes.addr6);
3166 }
3167 else
3168 {
3169 sock->writes.addr = to->dest.addr.in4;
3170 sock->writes.addrlen = sizeof (sock->writes.addr);
3171 }
3172
3173 status = WSASendTo(
3174 sock->sd,
3175 wsabuf,
3176 1,
3177 &sock->writes.size,
3178 sock->writes.flags,
3179 (struct sockaddr *) &sock->writes.addr,
3180 sock->writes.addrlen,
3181 &sock->writes.overlapped,
3182 NULL);
3183 }
3184 else if (proto_is_tcp(sock->info.proto))
3185 {
3186 /* destination address for TCP writes was established on connection initiation */
3187 sock->writes.addr_defined = false;
3188
3189 status = WSASend(
3190 sock->sd,
3191 wsabuf,
3192 1,
3193 &sock->writes.size,
3194 sock->writes.flags,
3195 &sock->writes.overlapped,
3196 NULL);
3197 }
3198 else
3199 {
3200 status = 0;
3201 ASSERT (0);
3202 }
3203
3204 if (!status) /* operation completed immediately? */
3205 {
3206 sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
3207
3208 /* since we got an immediate return, we must signal the event object ourselves */
3209 ASSERT (SetEvent (sock->writes.overlapped.hEvent));
3210
3211 sock->writes.status = 0;
3212
3213 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3214 (int) wsabuf[0].len,
3215 (int) sock->writes.size);
3216 }
3217 else
3218 {
3219 status = WSAGetLastError ();
3220 if (status == WSA_IO_PENDING) /* operation queued? */
3221 {
3222 sock->writes.iostate = IOSTATE_QUEUED;
3223 sock->writes.status = status;
3224 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
3225 (int) wsabuf[0].len);
3226 }
3227 else /* error occurred */
3228 {
3229 struct gc_arena gc = gc_new ();
3230 ASSERT (SetEvent (sock->writes.overlapped.hEvent));
3231 sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
3232 sock->writes.status = status;
3233
3234 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
3235 (int) wsabuf[0].len,
3236 strerror_win32 (status, &gc));
3237
3238 gc_free (&gc);
3239 }
3240 }
3241 }
3242 return sock->writes.iostate;
3243 }
3244
3245 int
3246 socket_finalize (SOCKET s,
3247 struct overlapped_io *io,
3248 struct buffer *buf,
3249 struct link_socket_actual *from)
3250 {
3251 int ret = -1;
3252 BOOL status;
3253
3254 switch (io->iostate)
3255 {
3256 case IOSTATE_QUEUED:
3257 status = WSAGetOverlappedResult(
3258 s,
3259 &io->overlapped,
3260 &io->size,
3261 FALSE,
3262 &io->flags
3263 );
3264 if (status)
3265 {
3266 /* successful return for a queued operation */
3267 if (buf)
3268 *buf = io->buf;
3269 ret = io->size;
3270 io->iostate = IOSTATE_INITIAL;
3271 ASSERT (ResetEvent (io->overlapped.hEvent));
3272
3273 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
3274 }
3275 else
3276 {
3277 /* error during a queued operation */
3278 ret = -1;
3279 if (WSAGetLastError() != WSA_IO_INCOMPLETE)
3280 {
3281 /* if no error (i.e. just not finished yet), then DON'T execute this code */
3282 io->iostate = IOSTATE_INITIAL;
3283 ASSERT (ResetEvent (io->overlapped.hEvent));
3284 msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion error");
3285 }
3286 }
3287 break;
3288
3289 case IOSTATE_IMMEDIATE_RETURN:
3290 io->iostate = IOSTATE_INITIAL;
3291 ASSERT (ResetEvent (io->overlapped.hEvent));
3292 if (io->status)
3293 {
3294 /* error return for a non-queued operation */
3295 WSASetLastError (io->status);
3296 ret = -1;
3297 msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion non-queued error");
3298 }
3299 else
3300 {
3301 /* successful return for a non-queued operation */
3302 if (buf)
3303 *buf = io->buf;
3304 ret = io->size;
3305 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
3306 }
3307 break;
3308
3309 case IOSTATE_INITIAL: /* were we called without proper queueing? */
3310 WSASetLastError (WSAEINVAL);
3311 ret = -1;
3312 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
3313 break;
3314
3315 default:
3316 ASSERT (0);
3317 }
3318
3319 /* return from address if requested */
3320 if (from)
3321 {
3322 if (ret >= 0 && io->addr_defined)
3323 {
3324 /* TODO(jjo): streamline this mess */
3325 /* in this func we dont have relevant info about the PF_ of this
3326 * endpoint, as link_socket_actual will be zero for the 1st received packet
3327 *
3328 * Test for inets PF_ possible sizes
3329 */
3330 switch (io->addrlen)
3331 {
3332 case sizeof(struct sockaddr_in):
3333 case sizeof(struct sockaddr_in6):
3334 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3335 * under WIN32*/
3336 case sizeof(struct sockaddr_in6)-4:
3337 break;
3338 default:
3339 bad_address_length (io->addrlen, af_addr_size(io->addr.sin_family));
3340 }
3341
3342 switch (io->addr.sin_family)
3343 {
3344 case AF_INET:
3345 from->dest.addr.in4 = io->addr;
3346 break;
3347 case AF_INET6:
3348 from->dest.addr.in6 = io->addr6;
3349 break;
3350 }
3351 }
3352 else
3353 CLEAR (from->dest.addr);
3354 }
3355
3356 if (buf)
3357 buf->len = ret;
3358 return ret;
3359 }
3360
3361 #endif /* WIN32 */
3362
3363 /*
3364 * Socket event notification
3365 */
3366
3367 unsigned int
3368 socket_set (struct link_socket *s,
3369 struct event_set *es,
3370 unsigned int rwflags,
3371 void *arg,
3372 unsigned int *persistent)
3373 {
3374 if (s)
3375 {
3376 if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
3377 {
3378 ASSERT (!persistent);
3379 rwflags &= ~EVENT_READ;
3380 }
3381
3382 #ifdef WIN32
3383 if (rwflags & EVENT_READ)
3384 socket_recv_queue (s, 0);
3385 #endif
3386
3387 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3388 if (!persistent || *persistent != rwflags)
3389 {
3390 event_ctl (es, socket_event_handle (s), rwflags, arg);
3391 if (persistent)
3392 *persistent = rwflags;
3393 }
3394
3395 s->rwflags_debug = rwflags;
3396 }
3397 return rwflags;
3398 }
3399
3400 void
3401 sd_close (socket_descriptor_t *sd)
3402 {
3403 if (sd && socket_defined (*sd))
3404 {
3405 openvpn_close_socket (*sd);
3406 *sd = SOCKET_UNDEFINED;
3407 }
3408 }
3409
3410 #if UNIX_SOCK_SUPPORT
3411
3412 /*
3413 * code for unix domain sockets
3414 */
3415
3416 const char *
3417 sockaddr_unix_name (const struct sockaddr_un *local, const char *null)
3418 {
3419 if (local && local->sun_family == PF_UNIX)
3420 return local->sun_path;
3421 else
3422 return null;
3423 }
3424
3425 socket_descriptor_t
3426 create_socket_unix (void)
3427 {
3428 socket_descriptor_t sd;
3429
3430 if ((sd = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
3431 msg (M_ERR, "Cannot create unix domain socket");
3432 return sd;
3433 }
3434
3435 void
3436 socket_bind_unix (socket_descriptor_t sd,
3437 struct sockaddr_un *local,
3438 const char *prefix)
3439 {
3440 struct gc_arena gc = gc_new ();
3441
3442 #ifdef HAVE_UMASK
3443 const mode_t orig_umask = umask (0);
3444 #endif
3445
3446 if (bind (sd, (struct sockaddr *) local, sizeof (struct sockaddr_un)))
3447 {
3448 const int errnum = openvpn_errno ();
3449 msg (M_FATAL, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
3450 prefix,
3451 (int)sd,
3452 sockaddr_unix_name (local, "NULL"),
3453 strerror_ts (errnum, &gc));
3454 }
3455
3456 #ifdef HAVE_UMASK
3457 umask (orig_umask);
3458 #endif
3459
3460 gc_free (&gc);
3461 }
3462
3463 socket_descriptor_t
3464 socket_accept_unix (socket_descriptor_t sd,
3465 struct sockaddr_un *remote)
3466 {
3467 socklen_t remote_len = sizeof (struct sockaddr_un);
3468 socket_descriptor_t ret;
3469
3470 CLEAR (*remote);
3471 ret = accept (sd, (struct sockaddr *) remote, &remote_len);
3472 return ret;
3473 }
3474
3475 int
3476 socket_connect_unix (socket_descriptor_t sd,
3477 struct sockaddr_un *remote)
3478 {
3479 int status = connect (sd, (struct sockaddr *) remote, sizeof (struct sockaddr_un));
3480 if (status)
3481 status = openvpn_errno ();
3482 return status;
3483 }
3484
3485 void
3486 sockaddr_unix_init (struct sockaddr_un *local, const char *path)
3487 {
3488 local->sun_family = PF_UNIX;
3489 strncpynt (local->sun_path, path, sizeof (local->sun_path));
3490 }
3491
3492 void
3493 socket_delete_unix (const struct sockaddr_un *local)
3494 {
3495 const char *name = sockaddr_unix_name (local, NULL);
3496 #ifdef HAVE_UNLINK
3497 if (name && strlen (name))
3498 unlink (name);
3499 #endif
3500 }
3501
3502 bool
3503 unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
3504 {
3505 #ifdef HAVE_GETPEEREID
3506 uid_t u;
3507 gid_t g;
3508 if (getpeereid (sd, &u, &g) == -1)
3509 return false;
3510 if (uid)
3511 *uid = u;
3512 if (gid)
3513 *gid = g;
3514 return true;
3515 #elif defined(SO_PEERCRED)
3516 struct ucred peercred;
3517 socklen_t so_len = sizeof(peercred);
3518 if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
3519 return false;
3520 if (uid)
3521 *uid = peercred.uid;
3522 if (gid)
3523 *gid = peercred.gid;
3524 return true;
3525 #else
3526 return false;
3527 #endif
3528 }
3529
3530 #endif