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