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