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