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