1 // SPDX-License-Identifier: GPL-2.0
2 /* nettest - used for functional tests of networking APIs
3  *
4  * Copyright (c) 2013-2019 David Ahern <dsahern@gmail.com>. All rights reserved.
5  */
6 
7 #define _GNU_SOURCE
8 #include <features.h>
9 #include <sys/types.h>
10 #include <sys/ioctl.h>
11 #include <sys/socket.h>
12 #include <sys/wait.h>
13 #include <linux/tcp.h>
14 #include <linux/udp.h>
15 #include <arpa/inet.h>
16 #include <net/if.h>
17 #include <netinet/in.h>
18 #include <netinet/ip.h>
19 #include <netdb.h>
20 #include <fcntl.h>
21 #include <libgen.h>
22 #include <limits.h>
23 #include <sched.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <getopt.h>
32 
33 #include <linux/xfrm.h>
34 #include <linux/ipsec.h>
35 #include <linux/pfkeyv2.h>
36 
37 #ifndef IPV6_UNICAST_IF
38 #define IPV6_UNICAST_IF         76
39 #endif
40 #ifndef IPV6_MULTICAST_IF
41 #define IPV6_MULTICAST_IF       17
42 #endif
43 
44 #define DEFAULT_PORT 12345
45 
46 #define NS_PREFIX "/run/netns/"
47 
48 #ifndef MAX
49 #define MAX(a, b)  ((a) > (b) ? (a) : (b))
50 #endif
51 #ifndef MIN
52 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
53 #endif
54 
55 struct sock_args {
56 	/* local address */
57 	const char *local_addr_str;
58 	const char *client_local_addr_str;
59 	union {
60 		struct in_addr  in;
61 		struct in6_addr in6;
62 	} local_addr;
63 
64 	/* remote address */
65 	const char *remote_addr_str;
66 	union {
67 		struct in_addr  in;
68 		struct in6_addr in6;
69 	} remote_addr;
70 	int scope_id;  /* remote scope; v6 send only */
71 
72 	struct in_addr grp;     /* multicast group */
73 
74 	unsigned int has_local_ip:1,
75 		     has_remote_ip:1,
76 		     has_grp:1,
77 		     has_expected_laddr:1,
78 		     has_expected_raddr:1,
79 		     bind_test_only:1;
80 
81 	unsigned short port;
82 
83 	int type;      /* DGRAM, STREAM, RAW */
84 	int protocol;
85 	int version;   /* AF_INET/AF_INET6 */
86 
87 	int use_setsockopt;
88 	int use_freebind;
89 	int use_cmsg;
90 	const char *dev;
91 	const char *server_dev;
92 	int ifindex;
93 
94 	const char *clientns;
95 	const char *serverns;
96 
97 	const char *password;
98 	const char *client_pw;
99 	/* prefix for MD5 password */
100 	const char *md5_prefix_str;
101 	union {
102 		struct sockaddr_in v4;
103 		struct sockaddr_in6 v6;
104 	} md5_prefix;
105 	unsigned int prefix_len;
106 	/* 0: default, -1: force off, +1: force on */
107 	int bind_key_ifindex;
108 
109 	/* expected addresses and device index for connection */
110 	const char *expected_dev;
111 	const char *expected_server_dev;
112 	int expected_ifindex;
113 
114 	/* local address */
115 	const char *expected_laddr_str;
116 	union {
117 		struct in_addr  in;
118 		struct in6_addr in6;
119 	} expected_laddr;
120 
121 	/* remote address */
122 	const char *expected_raddr_str;
123 	union {
124 		struct in_addr  in;
125 		struct in6_addr in6;
126 	} expected_raddr;
127 
128 	/* ESP in UDP encap test */
129 	int use_xfrm;
130 
131 	/* use send() and connect() instead of sendto */
132 	int datagram_connect;
133 };
134 
135 static int server_mode;
136 static unsigned int prog_timeout = 5;
137 static unsigned int interactive;
138 static int iter = 1;
139 static char *msg = "Hello world!";
140 static int msglen;
141 static int quiet;
142 static int try_broadcast = 1;
143 
144 static char *timestamp(char *timebuf, int buflen)
145 {
146 	time_t now;
147 
148 	now = time(NULL);
149 	if (strftime(timebuf, buflen, "%T", localtime(&now)) == 0) {
150 		memset(timebuf, 0, buflen);
151 		strncpy(timebuf, "00:00:00", buflen-1);
152 	}
153 
154 	return timebuf;
155 }
156 
157 static void log_msg(const char *format, ...)
158 {
159 	char timebuf[64];
160 	va_list args;
161 
162 	if (quiet)
163 		return;
164 
165 	fprintf(stdout, "%s %s:",
166 		timestamp(timebuf, sizeof(timebuf)),
167 		server_mode ? "server" : "client");
168 	va_start(args, format);
169 	vfprintf(stdout, format, args);
170 	va_end(args);
171 
172 	fflush(stdout);
173 }
174 
175 static void log_error(const char *format, ...)
176 {
177 	char timebuf[64];
178 	va_list args;
179 
180 	if (quiet)
181 		return;
182 
183 	fprintf(stderr, "%s %s:",
184 		timestamp(timebuf, sizeof(timebuf)),
185 		server_mode ? "server" : "client");
186 	va_start(args, format);
187 	vfprintf(stderr, format, args);
188 	va_end(args);
189 
190 	fflush(stderr);
191 }
192 
193 static void log_err_errno(const char *fmt, ...)
194 {
195 	char timebuf[64];
196 	va_list args;
197 
198 	if (quiet)
199 		return;
200 
201 	fprintf(stderr, "%s %s: ",
202 		timestamp(timebuf, sizeof(timebuf)),
203 		server_mode ? "server" : "client");
204 	va_start(args, fmt);
205 	vfprintf(stderr, fmt, args);
206 	va_end(args);
207 
208 	fprintf(stderr, ": %d: %s\n", errno, strerror(errno));
209 	fflush(stderr);
210 }
211 
212 static void log_address(const char *desc, struct sockaddr *sa)
213 {
214 	char addrstr[64];
215 
216 	if (quiet)
217 		return;
218 
219 	if (sa->sa_family == AF_INET) {
220 		struct sockaddr_in *s = (struct sockaddr_in *) sa;
221 
222 		log_msg("%s %s:%d\n",
223 			desc,
224 			inet_ntop(AF_INET, &s->sin_addr, addrstr,
225 				  sizeof(addrstr)),
226 			ntohs(s->sin_port));
227 
228 	} else if (sa->sa_family == AF_INET6) {
229 		struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa;
230 
231 		log_msg("%s [%s]:%d\n",
232 			desc,
233 			inet_ntop(AF_INET6, &s6->sin6_addr, addrstr,
234 				  sizeof(addrstr)),
235 			ntohs(s6->sin6_port));
236 	}
237 
238 	fflush(stdout);
239 }
240 
241 static int switch_ns(const char *ns)
242 {
243 	char path[PATH_MAX];
244 	int fd, ret;
245 
246 	if (geteuid())
247 		log_error("warning: likely need root to set netns %s!\n", ns);
248 
249 	snprintf(path, sizeof(path), "%s%s", NS_PREFIX, ns);
250 	fd = open(path, 0);
251 	if (fd < 0) {
252 		log_err_errno("Failed to open netns path; can not switch netns");
253 		return 1;
254 	}
255 
256 	ret = setns(fd, CLONE_NEWNET);
257 	close(fd);
258 
259 	return ret;
260 }
261 
262 static int tcp_md5sig(int sd, void *addr, socklen_t alen, struct sock_args *args)
263 {
264 	int keylen = strlen(args->password);
265 	struct tcp_md5sig md5sig = {};
266 	int opt = TCP_MD5SIG;
267 	int rc;
268 
269 	md5sig.tcpm_keylen = keylen;
270 	memcpy(md5sig.tcpm_key, args->password, keylen);
271 
272 	if (args->prefix_len) {
273 		opt = TCP_MD5SIG_EXT;
274 		md5sig.tcpm_flags |= TCP_MD5SIG_FLAG_PREFIX;
275 
276 		md5sig.tcpm_prefixlen = args->prefix_len;
277 		addr = &args->md5_prefix;
278 	}
279 	memcpy(&md5sig.tcpm_addr, addr, alen);
280 
281 	if ((args->ifindex && args->bind_key_ifindex >= 0) || args->bind_key_ifindex >= 1) {
282 		opt = TCP_MD5SIG_EXT;
283 		md5sig.tcpm_flags |= TCP_MD5SIG_FLAG_IFINDEX;
284 
285 		md5sig.tcpm_ifindex = args->ifindex;
286 		log_msg("TCP_MD5SIG_FLAG_IFINDEX set tcpm_ifindex=%d\n", md5sig.tcpm_ifindex);
287 	} else {
288 		log_msg("TCP_MD5SIG_FLAG_IFINDEX off\n", md5sig.tcpm_ifindex);
289 	}
290 
291 	rc = setsockopt(sd, IPPROTO_TCP, opt, &md5sig, sizeof(md5sig));
292 	if (rc < 0) {
293 		/* ENOENT is harmless. Returned when a password is cleared */
294 		if (errno == ENOENT)
295 			rc = 0;
296 		else
297 			log_err_errno("setsockopt(TCP_MD5SIG)");
298 	}
299 
300 	return rc;
301 }
302 
303 static int tcp_md5_remote(int sd, struct sock_args *args)
304 {
305 	struct sockaddr_in sin = {
306 		.sin_family = AF_INET,
307 	};
308 	struct sockaddr_in6 sin6 = {
309 		.sin6_family = AF_INET6,
310 	};
311 	void *addr;
312 	int alen;
313 
314 	switch (args->version) {
315 	case AF_INET:
316 		sin.sin_port = htons(args->port);
317 		sin.sin_addr = args->md5_prefix.v4.sin_addr;
318 		addr = &sin;
319 		alen = sizeof(sin);
320 		break;
321 	case AF_INET6:
322 		sin6.sin6_port = htons(args->port);
323 		sin6.sin6_addr = args->md5_prefix.v6.sin6_addr;
324 		addr = &sin6;
325 		alen = sizeof(sin6);
326 		break;
327 	default:
328 		log_error("unknown address family\n");
329 		exit(1);
330 	}
331 
332 	if (tcp_md5sig(sd, addr, alen, args))
333 		return -1;
334 
335 	return 0;
336 }
337 
338 static int get_ifidx(const char *ifname)
339 {
340 	struct ifreq ifdata;
341 	int sd, rc;
342 
343 	if (!ifname || *ifname == '\0')
344 		return -1;
345 
346 	memset(&ifdata, 0, sizeof(ifdata));
347 
348 	strcpy(ifdata.ifr_name, ifname);
349 
350 	sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
351 	if (sd < 0) {
352 		log_err_errno("socket failed");
353 		return -1;
354 	}
355 
356 	rc = ioctl(sd, SIOCGIFINDEX, (char *)&ifdata);
357 	close(sd);
358 	if (rc != 0) {
359 		log_err_errno("ioctl(SIOCGIFINDEX) failed");
360 		return -1;
361 	}
362 
363 	return ifdata.ifr_ifindex;
364 }
365 
366 static int bind_to_device(int sd, const char *name)
367 {
368 	int rc;
369 
370 	rc = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, name, strlen(name)+1);
371 	if (rc < 0)
372 		log_err_errno("setsockopt(SO_BINDTODEVICE)");
373 
374 	return rc;
375 }
376 
377 static int get_bind_to_device(int sd, char *name, size_t len)
378 {
379 	int rc;
380 	socklen_t optlen = len;
381 
382 	name[0] = '\0';
383 	rc = getsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, name, &optlen);
384 	if (rc < 0)
385 		log_err_errno("setsockopt(SO_BINDTODEVICE)");
386 
387 	return rc;
388 }
389 
390 static int check_device(int sd, struct sock_args *args)
391 {
392 	int ifindex = 0;
393 	char name[32];
394 
395 	if (get_bind_to_device(sd, name, sizeof(name)))
396 		*name = '\0';
397 	else
398 		ifindex = get_ifidx(name);
399 
400 	log_msg("    bound to device %s/%d\n",
401 		*name ? name : "<none>", ifindex);
402 
403 	if (!args->expected_ifindex)
404 		return 0;
405 
406 	if (args->expected_ifindex != ifindex) {
407 		log_error("Device index mismatch: expected %d have %d\n",
408 			  args->expected_ifindex, ifindex);
409 		return 1;
410 	}
411 
412 	log_msg("Device index matches: expected %d have %d\n",
413 		args->expected_ifindex, ifindex);
414 
415 	return 0;
416 }
417 
418 static int set_pktinfo_v4(int sd)
419 {
420 	int one = 1;
421 	int rc;
422 
423 	rc = setsockopt(sd, SOL_IP, IP_PKTINFO, &one, sizeof(one));
424 	if (rc < 0 && rc != -ENOTSUP)
425 		log_err_errno("setsockopt(IP_PKTINFO)");
426 
427 	return rc;
428 }
429 
430 static int set_recvpktinfo_v6(int sd)
431 {
432 	int one = 1;
433 	int rc;
434 
435 	rc = setsockopt(sd, SOL_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one));
436 	if (rc < 0 && rc != -ENOTSUP)
437 		log_err_errno("setsockopt(IPV6_RECVPKTINFO)");
438 
439 	return rc;
440 }
441 
442 static int set_recverr_v4(int sd)
443 {
444 	int one = 1;
445 	int rc;
446 
447 	rc = setsockopt(sd, SOL_IP, IP_RECVERR, &one, sizeof(one));
448 	if (rc < 0 && rc != -ENOTSUP)
449 		log_err_errno("setsockopt(IP_RECVERR)");
450 
451 	return rc;
452 }
453 
454 static int set_recverr_v6(int sd)
455 {
456 	int one = 1;
457 	int rc;
458 
459 	rc = setsockopt(sd, SOL_IPV6, IPV6_RECVERR, &one, sizeof(one));
460 	if (rc < 0 && rc != -ENOTSUP)
461 		log_err_errno("setsockopt(IPV6_RECVERR)");
462 
463 	return rc;
464 }
465 
466 static int set_unicast_if(int sd, int ifindex, int version)
467 {
468 	int opt = IP_UNICAST_IF;
469 	int level = SOL_IP;
470 	int rc;
471 
472 	ifindex = htonl(ifindex);
473 
474 	if (version == AF_INET6) {
475 		opt = IPV6_UNICAST_IF;
476 		level = SOL_IPV6;
477 	}
478 	rc = setsockopt(sd, level, opt, &ifindex, sizeof(ifindex));
479 	if (rc < 0)
480 		log_err_errno("setsockopt(IP_UNICAST_IF)");
481 
482 	return rc;
483 }
484 
485 static int set_multicast_if(int sd, int ifindex)
486 {
487 	struct ip_mreqn mreq = { .imr_ifindex = ifindex };
488 	int rc;
489 
490 	rc = setsockopt(sd, SOL_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq));
491 	if (rc < 0)
492 		log_err_errno("setsockopt(IP_MULTICAST_IF)");
493 
494 	return rc;
495 }
496 
497 static int set_membership(int sd, uint32_t grp, uint32_t addr, int ifindex)
498 {
499 	uint32_t if_addr = addr;
500 	struct ip_mreqn mreq;
501 	int rc;
502 
503 	if (addr == htonl(INADDR_ANY) && !ifindex) {
504 		log_error("Either local address or device needs to be given for multicast membership\n");
505 		return -1;
506 	}
507 
508 	mreq.imr_multiaddr.s_addr = grp;
509 	mreq.imr_address.s_addr = if_addr;
510 	mreq.imr_ifindex = ifindex;
511 
512 	rc = setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
513 	if (rc < 0) {
514 		log_err_errno("setsockopt(IP_ADD_MEMBERSHIP)");
515 		return -1;
516 	}
517 
518 	return 0;
519 }
520 
521 static int set_freebind(int sd, int version)
522 {
523 	unsigned int one = 1;
524 	int rc = 0;
525 
526 	switch (version) {
527 	case AF_INET:
528 		if (setsockopt(sd, SOL_IP, IP_FREEBIND, &one, sizeof(one))) {
529 			log_err_errno("setsockopt(IP_FREEBIND)");
530 			rc = -1;
531 		}
532 		break;
533 	case AF_INET6:
534 		if (setsockopt(sd, SOL_IPV6, IPV6_FREEBIND, &one, sizeof(one))) {
535 			log_err_errno("setsockopt(IPV6_FREEBIND");
536 			rc = -1;
537 		}
538 		break;
539 	}
540 
541 	return rc;
542 }
543 
544 static int set_broadcast(int sd)
545 {
546 	unsigned int one = 1;
547 	int rc = 0;
548 
549 	if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) != 0) {
550 		log_err_errno("setsockopt(SO_BROADCAST)");
551 		rc = -1;
552 	}
553 
554 	return rc;
555 }
556 
557 static int set_reuseport(int sd)
558 {
559 	unsigned int one = 1;
560 	int rc = 0;
561 
562 	if (setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)) != 0) {
563 		log_err_errno("setsockopt(SO_REUSEPORT)");
564 		rc = -1;
565 	}
566 
567 	return rc;
568 }
569 
570 static int set_reuseaddr(int sd)
571 {
572 	unsigned int one = 1;
573 	int rc = 0;
574 
575 	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
576 		log_err_errno("setsockopt(SO_REUSEADDR)");
577 		rc = -1;
578 	}
579 
580 	return rc;
581 }
582 
583 static int str_to_uint(const char *str, int min, int max, unsigned int *value)
584 {
585 	int number;
586 	char *end;
587 
588 	errno = 0;
589 	number = (unsigned int) strtoul(str, &end, 0);
590 
591 	/* entire string should be consumed by conversion
592 	 * and value should be between min and max
593 	 */
594 	if (((*end == '\0') || (*end == '\n')) && (end != str) &&
595 	    (errno != ERANGE) && (min <= number) && (number <= max)) {
596 		*value = number;
597 		return 0;
598 	}
599 
600 	return -1;
601 }
602 
603 static int resolve_devices(struct sock_args *args)
604 {
605 	if (args->dev) {
606 		args->ifindex = get_ifidx(args->dev);
607 		if (args->ifindex < 0) {
608 			log_error("Invalid device name\n");
609 			return 1;
610 		}
611 	}
612 
613 	if (args->expected_dev) {
614 		unsigned int tmp;
615 
616 		if (str_to_uint(args->expected_dev, 0, INT_MAX, &tmp) == 0) {
617 			args->expected_ifindex = (int)tmp;
618 		} else {
619 			args->expected_ifindex = get_ifidx(args->expected_dev);
620 			if (args->expected_ifindex < 0) {
621 				fprintf(stderr, "Invalid expected device\n");
622 				return 1;
623 			}
624 		}
625 	}
626 
627 	return 0;
628 }
629 
630 static int expected_addr_match(struct sockaddr *sa, void *expected,
631 			       const char *desc)
632 {
633 	char addrstr[64];
634 	int rc = 0;
635 
636 	if (sa->sa_family == AF_INET) {
637 		struct sockaddr_in *s = (struct sockaddr_in *) sa;
638 		struct in_addr *exp_in = (struct in_addr *) expected;
639 
640 		if (s->sin_addr.s_addr != exp_in->s_addr) {
641 			log_error("%s address does not match expected %s\n",
642 				  desc,
643 				  inet_ntop(AF_INET, exp_in,
644 					    addrstr, sizeof(addrstr)));
645 			rc = 1;
646 		}
647 	} else if (sa->sa_family == AF_INET6) {
648 		struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa;
649 		struct in6_addr *exp_in = (struct in6_addr *) expected;
650 
651 		if (memcmp(&s6->sin6_addr, exp_in, sizeof(*exp_in))) {
652 			log_error("%s address does not match expected %s\n",
653 				  desc,
654 				  inet_ntop(AF_INET6, exp_in,
655 					    addrstr, sizeof(addrstr)));
656 			rc = 1;
657 		}
658 	} else {
659 		log_error("%s address does not match expected - unknown family\n",
660 			  desc);
661 		rc = 1;
662 	}
663 
664 	if (!rc)
665 		log_msg("%s address matches expected\n", desc);
666 
667 	return rc;
668 }
669 
670 static int show_sockstat(int sd, struct sock_args *args)
671 {
672 	struct sockaddr_in6 local_addr, remote_addr;
673 	socklen_t alen = sizeof(local_addr);
674 	struct sockaddr *sa;
675 	const char *desc;
676 	int rc = 0;
677 
678 	desc = server_mode ? "server local:" : "client local:";
679 	sa = (struct sockaddr *) &local_addr;
680 	if (getsockname(sd, sa, &alen) == 0) {
681 		log_address(desc, sa);
682 
683 		if (args->has_expected_laddr) {
684 			rc = expected_addr_match(sa, &args->expected_laddr,
685 						 "local");
686 		}
687 	} else {
688 		log_err_errno("getsockname failed");
689 	}
690 
691 	sa = (struct sockaddr *) &remote_addr;
692 	desc = server_mode ? "server peer:" : "client peer:";
693 	if (getpeername(sd, sa, &alen) == 0) {
694 		log_address(desc, sa);
695 
696 		if (args->has_expected_raddr) {
697 			rc |= expected_addr_match(sa, &args->expected_raddr,
698 						 "remote");
699 		}
700 	} else {
701 		log_err_errno("getpeername failed");
702 	}
703 
704 	return rc;
705 }
706 
707 enum addr_type {
708 	ADDR_TYPE_LOCAL,
709 	ADDR_TYPE_REMOTE,
710 	ADDR_TYPE_MCAST,
711 	ADDR_TYPE_EXPECTED_LOCAL,
712 	ADDR_TYPE_EXPECTED_REMOTE,
713 	ADDR_TYPE_MD5_PREFIX,
714 };
715 
716 static int convert_addr(struct sock_args *args, const char *_str,
717 			enum addr_type atype)
718 {
719 	int pfx_len_max = args->version == AF_INET6 ? 128 : 32;
720 	int family = args->version;
721 	char *str, *dev, *sep;
722 	struct in6_addr *in6;
723 	struct in_addr  *in;
724 	const char *desc;
725 	void *addr;
726 	int rc = 0;
727 
728 	str = strdup(_str);
729 	if (!str)
730 		return -ENOMEM;
731 
732 	switch (atype) {
733 	case ADDR_TYPE_LOCAL:
734 		desc = "local";
735 		addr = &args->local_addr;
736 		break;
737 	case ADDR_TYPE_REMOTE:
738 		desc = "remote";
739 		addr = &args->remote_addr;
740 		break;
741 	case ADDR_TYPE_MCAST:
742 		desc = "mcast grp";
743 		addr = &args->grp;
744 		break;
745 	case ADDR_TYPE_EXPECTED_LOCAL:
746 		desc = "expected local";
747 		addr = &args->expected_laddr;
748 		break;
749 	case ADDR_TYPE_EXPECTED_REMOTE:
750 		desc = "expected remote";
751 		addr = &args->expected_raddr;
752 		break;
753 	case ADDR_TYPE_MD5_PREFIX:
754 		desc = "md5 prefix";
755 		if (family == AF_INET) {
756 			args->md5_prefix.v4.sin_family = AF_INET;
757 			addr = &args->md5_prefix.v4.sin_addr;
758 		} else if (family == AF_INET6) {
759 			args->md5_prefix.v6.sin6_family = AF_INET6;
760 			addr = &args->md5_prefix.v6.sin6_addr;
761 		} else
762 			return 1;
763 
764 		sep = strchr(str, '/');
765 		if (sep) {
766 			*sep = '\0';
767 			sep++;
768 			if (str_to_uint(sep, 1, pfx_len_max,
769 					&args->prefix_len) != 0) {
770 				fprintf(stderr, "Invalid port\n");
771 				return 1;
772 			}
773 		} else {
774 			args->prefix_len = 0;
775 		}
776 		break;
777 	default:
778 		log_error("unknown address type\n");
779 		exit(1);
780 	}
781 
782 	switch (family) {
783 	case AF_INET:
784 		in  = (struct in_addr *) addr;
785 		if (str) {
786 			if (inet_pton(AF_INET, str, in) == 0) {
787 				log_error("Invalid %s IP address\n", desc);
788 				rc = -1;
789 				goto out;
790 			}
791 		} else {
792 			in->s_addr = htonl(INADDR_ANY);
793 		}
794 		break;
795 
796 	case AF_INET6:
797 		dev = strchr(str, '%');
798 		if (dev) {
799 			*dev = '\0';
800 			dev++;
801 		}
802 
803 		in6 = (struct in6_addr *) addr;
804 		if (str) {
805 			if (inet_pton(AF_INET6, str, in6) == 0) {
806 				log_error("Invalid %s IPv6 address\n", desc);
807 				rc = -1;
808 				goto out;
809 			}
810 		} else {
811 			*in6 = in6addr_any;
812 		}
813 		if (dev) {
814 			args->scope_id = get_ifidx(dev);
815 			if (args->scope_id < 0) {
816 				log_error("Invalid scope on %s IPv6 address\n",
817 					  desc);
818 				rc = -1;
819 				goto out;
820 			}
821 		}
822 		break;
823 
824 	default:
825 		log_error("Invalid address family\n");
826 	}
827 
828 out:
829 	free(str);
830 	return rc;
831 }
832 
833 static int validate_addresses(struct sock_args *args)
834 {
835 	if (args->local_addr_str &&
836 	    convert_addr(args, args->local_addr_str, ADDR_TYPE_LOCAL) < 0)
837 		return 1;
838 
839 	if (args->remote_addr_str &&
840 	    convert_addr(args, args->remote_addr_str, ADDR_TYPE_REMOTE) < 0)
841 		return 1;
842 
843 	if (args->md5_prefix_str &&
844 	    convert_addr(args, args->md5_prefix_str,
845 			 ADDR_TYPE_MD5_PREFIX) < 0)
846 		return 1;
847 
848 	if (args->expected_laddr_str &&
849 	    convert_addr(args, args->expected_laddr_str,
850 			 ADDR_TYPE_EXPECTED_LOCAL))
851 		return 1;
852 
853 	if (args->expected_raddr_str &&
854 	    convert_addr(args, args->expected_raddr_str,
855 			 ADDR_TYPE_EXPECTED_REMOTE))
856 		return 1;
857 
858 	return 0;
859 }
860 
861 static int get_index_from_cmsg(struct msghdr *m)
862 {
863 	struct cmsghdr *cm;
864 	int ifindex = 0;
865 	char buf[64];
866 
867 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(m);
868 	     m->msg_controllen != 0 && cm;
869 	     cm = (struct cmsghdr *)CMSG_NXTHDR(m, cm)) {
870 
871 		if (cm->cmsg_level == SOL_IP &&
872 		    cm->cmsg_type == IP_PKTINFO) {
873 			struct in_pktinfo *pi;
874 
875 			pi = (struct in_pktinfo *)(CMSG_DATA(cm));
876 			inet_ntop(AF_INET, &pi->ipi_addr, buf, sizeof(buf));
877 			ifindex = pi->ipi_ifindex;
878 		} else if (cm->cmsg_level == SOL_IPV6 &&
879 			   cm->cmsg_type == IPV6_PKTINFO) {
880 			struct in6_pktinfo *pi6;
881 
882 			pi6 = (struct in6_pktinfo *)(CMSG_DATA(cm));
883 			inet_ntop(AF_INET6, &pi6->ipi6_addr, buf, sizeof(buf));
884 			ifindex = pi6->ipi6_ifindex;
885 		}
886 	}
887 
888 	if (ifindex) {
889 		log_msg("    pktinfo: ifindex %d dest addr %s\n",
890 			ifindex, buf);
891 	}
892 	return ifindex;
893 }
894 
895 static int send_msg_no_cmsg(int sd, void *addr, socklen_t alen)
896 {
897 	int err;
898 
899 again:
900 	err = sendto(sd, msg, msglen, 0, addr, alen);
901 	if (err < 0) {
902 		if (errno == EACCES && try_broadcast) {
903 			try_broadcast = 0;
904 			if (!set_broadcast(sd))
905 				goto again;
906 			errno = EACCES;
907 		}
908 
909 		log_err_errno("sendto failed");
910 		return 1;
911 	}
912 
913 	return 0;
914 }
915 
916 static int send_msg_cmsg(int sd, void *addr, socklen_t alen,
917 			 int ifindex, int version)
918 {
919 	unsigned char cmsgbuf[64];
920 	struct iovec iov[2];
921 	struct cmsghdr *cm;
922 	struct msghdr m;
923 	int err;
924 
925 	iov[0].iov_base = msg;
926 	iov[0].iov_len = msglen;
927 	m.msg_iov = iov;
928 	m.msg_iovlen = 1;
929 	m.msg_name = (caddr_t)addr;
930 	m.msg_namelen = alen;
931 
932 	memset(cmsgbuf, 0, sizeof(cmsgbuf));
933 	cm = (struct cmsghdr *)cmsgbuf;
934 	m.msg_control = (caddr_t)cm;
935 
936 	if (version == AF_INET) {
937 		struct in_pktinfo *pi;
938 
939 		cm->cmsg_level = SOL_IP;
940 		cm->cmsg_type = IP_PKTINFO;
941 		cm->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
942 		pi = (struct in_pktinfo *)(CMSG_DATA(cm));
943 		pi->ipi_ifindex = ifindex;
944 
945 		m.msg_controllen = cm->cmsg_len;
946 
947 	} else if (version == AF_INET6) {
948 		struct in6_pktinfo *pi6;
949 
950 		cm->cmsg_level = SOL_IPV6;
951 		cm->cmsg_type = IPV6_PKTINFO;
952 		cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
953 
954 		pi6 = (struct in6_pktinfo *)(CMSG_DATA(cm));
955 		pi6->ipi6_ifindex = ifindex;
956 
957 		m.msg_controllen = cm->cmsg_len;
958 	}
959 
960 again:
961 	err = sendmsg(sd, &m, 0);
962 	if (err < 0) {
963 		if (errno == EACCES && try_broadcast) {
964 			try_broadcast = 0;
965 			if (!set_broadcast(sd))
966 				goto again;
967 			errno = EACCES;
968 		}
969 
970 		log_err_errno("sendmsg failed");
971 		return 1;
972 	}
973 
974 	return 0;
975 }
976 
977 
978 static int send_msg(int sd, void *addr, socklen_t alen, struct sock_args *args)
979 {
980 	if (args->type == SOCK_STREAM) {
981 		if (write(sd, msg, msglen) < 0) {
982 			log_err_errno("write failed sending msg to peer");
983 			return 1;
984 		}
985 	} else if (args->datagram_connect) {
986 		if (send(sd, msg, msglen, 0) < 0) {
987 			log_err_errno("send failed sending msg to peer");
988 			return 1;
989 		}
990 	} else if (args->ifindex && args->use_cmsg) {
991 		if (send_msg_cmsg(sd, addr, alen, args->ifindex, args->version))
992 			return 1;
993 	} else {
994 		if (send_msg_no_cmsg(sd, addr, alen))
995 			return 1;
996 	}
997 
998 	log_msg("Sent message:\n");
999 	log_msg("    %.24s%s\n", msg, msglen > 24 ? " ..." : "");
1000 
1001 	return 0;
1002 }
1003 
1004 static int socket_read_dgram(int sd, struct sock_args *args)
1005 {
1006 	unsigned char addr[sizeof(struct sockaddr_in6)];
1007 	struct sockaddr *sa = (struct sockaddr *) addr;
1008 	socklen_t alen = sizeof(addr);
1009 	struct iovec iov[2];
1010 	struct msghdr m = {
1011 		.msg_name = (caddr_t)addr,
1012 		.msg_namelen = alen,
1013 		.msg_iov = iov,
1014 		.msg_iovlen = 1,
1015 	};
1016 	unsigned char cmsgbuf[256];
1017 	struct cmsghdr *cm = (struct cmsghdr *)cmsgbuf;
1018 	char buf[16*1024];
1019 	int ifindex;
1020 	int len;
1021 
1022 	iov[0].iov_base = (caddr_t)buf;
1023 	iov[0].iov_len = sizeof(buf);
1024 
1025 	memset(cmsgbuf, 0, sizeof(cmsgbuf));
1026 	m.msg_control = (caddr_t)cm;
1027 	m.msg_controllen = sizeof(cmsgbuf);
1028 
1029 	len = recvmsg(sd, &m, 0);
1030 	if (len == 0) {
1031 		log_msg("peer closed connection.\n");
1032 		return 0;
1033 	} else if (len < 0) {
1034 		log_msg("failed to read message: %d: %s\n",
1035 			errno, strerror(errno));
1036 		return -1;
1037 	}
1038 
1039 	buf[len] = '\0';
1040 
1041 	log_address("Message from:", sa);
1042 	log_msg("    %.24s%s\n", buf, len > 24 ? " ..." : "");
1043 
1044 	ifindex = get_index_from_cmsg(&m);
1045 	if (args->expected_ifindex) {
1046 		if (args->expected_ifindex != ifindex) {
1047 			log_error("Device index mismatch: expected %d have %d\n",
1048 				  args->expected_ifindex, ifindex);
1049 			return -1;
1050 		}
1051 		log_msg("Device index matches: expected %d have %d\n",
1052 			args->expected_ifindex, ifindex);
1053 	}
1054 
1055 	if (!interactive && server_mode) {
1056 		if (sa->sa_family == AF_INET6) {
1057 			struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa;
1058 			struct in6_addr *in6 = &s6->sin6_addr;
1059 
1060 			if (IN6_IS_ADDR_V4MAPPED(in6)) {
1061 				const uint32_t *pa = (uint32_t *) &in6->s6_addr;
1062 				struct in_addr in4;
1063 				struct sockaddr_in *sin;
1064 
1065 				sin = (struct sockaddr_in *) addr;
1066 				pa += 3;
1067 				in4.s_addr = *pa;
1068 				sin->sin_addr = in4;
1069 				sin->sin_family = AF_INET;
1070 				if (send_msg_cmsg(sd, addr, alen,
1071 						  ifindex, AF_INET) < 0)
1072 					goto out_err;
1073 			}
1074 		}
1075 again:
1076 		iov[0].iov_len = len;
1077 
1078 		if (args->version == AF_INET6) {
1079 			struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa;
1080 
1081 			if (args->dev) {
1082 				/* avoid PKTINFO conflicts with bindtodev */
1083 				if (sendto(sd, buf, len, 0,
1084 					   (void *) addr, alen) < 0)
1085 					goto out_err;
1086 			} else {
1087 				/* kernel is allowing scope_id to be set to VRF
1088 				 * index for LLA. for sends to global address
1089 				 * reset scope id
1090 				 */
1091 				s6->sin6_scope_id = ifindex;
1092 				if (sendmsg(sd, &m, 0) < 0)
1093 					goto out_err;
1094 			}
1095 		} else {
1096 			int err;
1097 
1098 			err = sendmsg(sd, &m, 0);
1099 			if (err < 0) {
1100 				if (errno == EACCES && try_broadcast) {
1101 					try_broadcast = 0;
1102 					if (!set_broadcast(sd))
1103 						goto again;
1104 					errno = EACCES;
1105 				}
1106 				goto out_err;
1107 			}
1108 		}
1109 		log_msg("Sent message:\n");
1110 		log_msg("    %.24s%s\n", buf, len > 24 ? " ..." : "");
1111 	}
1112 
1113 	return 1;
1114 out_err:
1115 	log_err_errno("failed to send msg to peer");
1116 	return -1;
1117 }
1118 
1119 static int socket_read_stream(int sd)
1120 {
1121 	char buf[1024];
1122 	int len;
1123 
1124 	len = read(sd, buf, sizeof(buf)-1);
1125 	if (len == 0) {
1126 		log_msg("client closed connection.\n");
1127 		return 0;
1128 	} else if (len < 0) {
1129 		log_msg("failed to read message\n");
1130 		return -1;
1131 	}
1132 
1133 	buf[len] = '\0';
1134 	log_msg("Incoming message:\n");
1135 	log_msg("    %.24s%s\n", buf, len > 24 ? " ..." : "");
1136 
1137 	if (!interactive && server_mode) {
1138 		if (write(sd, buf, len) < 0) {
1139 			log_err_errno("failed to send buf");
1140 			return -1;
1141 		}
1142 		log_msg("Sent message:\n");
1143 		log_msg("     %.24s%s\n", buf, len > 24 ? " ..." : "");
1144 	}
1145 
1146 	return 1;
1147 }
1148 
1149 static int socket_read(int sd, struct sock_args *args)
1150 {
1151 	if (args->type == SOCK_STREAM)
1152 		return socket_read_stream(sd);
1153 
1154 	return socket_read_dgram(sd, args);
1155 }
1156 
1157 static int stdin_to_socket(int sd, int type, void *addr, socklen_t alen)
1158 {
1159 	char buf[1024];
1160 	int len;
1161 
1162 	if (fgets(buf, sizeof(buf), stdin) == NULL)
1163 		return 0;
1164 
1165 	len = strlen(buf);
1166 	if (type == SOCK_STREAM) {
1167 		if (write(sd, buf, len) < 0) {
1168 			log_err_errno("failed to send buf");
1169 			return -1;
1170 		}
1171 	} else {
1172 		int err;
1173 
1174 again:
1175 		err = sendto(sd, buf, len, 0, addr, alen);
1176 		if (err < 0) {
1177 			if (errno == EACCES && try_broadcast) {
1178 				try_broadcast = 0;
1179 				if (!set_broadcast(sd))
1180 					goto again;
1181 				errno = EACCES;
1182 			}
1183 			log_err_errno("failed to send msg to peer");
1184 			return -1;
1185 		}
1186 	}
1187 	log_msg("Sent message:\n");
1188 	log_msg("    %.24s%s\n", buf, len > 24 ? " ..." : "");
1189 
1190 	return 1;
1191 }
1192 
1193 static void set_recv_attr(int sd, int version)
1194 {
1195 	if (version == AF_INET6) {
1196 		set_recvpktinfo_v6(sd);
1197 		set_recverr_v6(sd);
1198 	} else {
1199 		set_pktinfo_v4(sd);
1200 		set_recverr_v4(sd);
1201 	}
1202 }
1203 
1204 static int msg_loop(int client, int sd, void *addr, socklen_t alen,
1205 		    struct sock_args *args)
1206 {
1207 	struct timeval timeout = { .tv_sec = prog_timeout }, *ptval = NULL;
1208 	fd_set rfds;
1209 	int nfds;
1210 	int rc;
1211 
1212 	if (args->type != SOCK_STREAM)
1213 		set_recv_attr(sd, args->version);
1214 
1215 	if (msg) {
1216 		msglen = strlen(msg);
1217 
1218 		/* client sends first message */
1219 		if (client) {
1220 			if (send_msg(sd, addr, alen, args))
1221 				return 1;
1222 		}
1223 		if (!interactive) {
1224 			ptval = &timeout;
1225 			if (!prog_timeout)
1226 				timeout.tv_sec = 5;
1227 		}
1228 	}
1229 
1230 	nfds = interactive ? MAX(fileno(stdin), sd)  + 1 : sd + 1;
1231 	while (1) {
1232 		FD_ZERO(&rfds);
1233 		FD_SET(sd, &rfds);
1234 		if (interactive)
1235 			FD_SET(fileno(stdin), &rfds);
1236 
1237 		rc = select(nfds, &rfds, NULL, NULL, ptval);
1238 		if (rc < 0) {
1239 			if (errno == EINTR)
1240 				continue;
1241 
1242 			rc = 1;
1243 			log_err_errno("select failed");
1244 			break;
1245 		} else if (rc == 0) {
1246 			log_error("Timed out waiting for response\n");
1247 			rc = 2;
1248 			break;
1249 		}
1250 
1251 		if (FD_ISSET(sd, &rfds)) {
1252 			rc = socket_read(sd, args);
1253 			if (rc < 0) {
1254 				rc = 1;
1255 				break;
1256 			}
1257 			if (rc == 0)
1258 				break;
1259 		}
1260 
1261 		rc = 0;
1262 
1263 		if (FD_ISSET(fileno(stdin), &rfds)) {
1264 			if (stdin_to_socket(sd, args->type, addr, alen) <= 0)
1265 				break;
1266 		}
1267 
1268 		if (interactive)
1269 			continue;
1270 
1271 		if (iter != -1) {
1272 			--iter;
1273 			if (iter == 0)
1274 				break;
1275 		}
1276 
1277 		log_msg("Going into quiet mode\n");
1278 		quiet = 1;
1279 
1280 		if (client) {
1281 			if (send_msg(sd, addr, alen, args)) {
1282 				rc = 1;
1283 				break;
1284 			}
1285 		}
1286 	}
1287 
1288 	return rc;
1289 }
1290 
1291 static int msock_init(struct sock_args *args, int server)
1292 {
1293 	uint32_t if_addr = htonl(INADDR_ANY);
1294 	struct sockaddr_in laddr = {
1295 		.sin_family = AF_INET,
1296 		.sin_port = htons(args->port),
1297 	};
1298 	int one = 1;
1299 	int sd;
1300 
1301 	if (!server && args->has_local_ip)
1302 		if_addr = args->local_addr.in.s_addr;
1303 
1304 	sd = socket(PF_INET, SOCK_DGRAM, 0);
1305 	if (sd < 0) {
1306 		log_err_errno("socket");
1307 		return -1;
1308 	}
1309 
1310 	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR,
1311 		       (char *)&one, sizeof(one)) < 0) {
1312 		log_err_errno("Setting SO_REUSEADDR error");
1313 		goto out_err;
1314 	}
1315 
1316 	if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST,
1317 		       (char *)&one, sizeof(one)) < 0)
1318 		log_err_errno("Setting SO_BROADCAST error");
1319 
1320 	if (args->dev && bind_to_device(sd, args->dev) != 0)
1321 		goto out_err;
1322 	else if (args->use_setsockopt &&
1323 		 set_multicast_if(sd, args->ifindex))
1324 		goto out_err;
1325 
1326 	laddr.sin_addr.s_addr = if_addr;
1327 
1328 	if (bind(sd, (struct sockaddr *) &laddr, sizeof(laddr)) < 0) {
1329 		log_err_errno("bind failed");
1330 		goto out_err;
1331 	}
1332 
1333 	if (server &&
1334 	    set_membership(sd, args->grp.s_addr,
1335 			   args->local_addr.in.s_addr, args->ifindex))
1336 		goto out_err;
1337 
1338 	return sd;
1339 out_err:
1340 	close(sd);
1341 	return -1;
1342 }
1343 
1344 static int msock_server(struct sock_args *args)
1345 {
1346 	return msock_init(args, 1);
1347 }
1348 
1349 static int msock_client(struct sock_args *args)
1350 {
1351 	return msock_init(args, 0);
1352 }
1353 
1354 static int bind_socket(int sd, struct sock_args *args)
1355 {
1356 	struct sockaddr_in serv_addr = {
1357 		.sin_family = AF_INET,
1358 	};
1359 	struct sockaddr_in6 serv6_addr = {
1360 		.sin6_family = AF_INET6,
1361 	};
1362 	void *addr;
1363 	socklen_t alen;
1364 
1365 	if (!args->has_local_ip && args->type == SOCK_RAW)
1366 		return 0;
1367 
1368 	switch (args->version) {
1369 	case AF_INET:
1370 		serv_addr.sin_port = htons(args->port);
1371 		serv_addr.sin_addr = args->local_addr.in;
1372 		addr = &serv_addr;
1373 		alen = sizeof(serv_addr);
1374 		break;
1375 
1376 	case AF_INET6:
1377 		serv6_addr.sin6_port = htons(args->port);
1378 		serv6_addr.sin6_addr = args->local_addr.in6;
1379 		addr = &serv6_addr;
1380 		alen = sizeof(serv6_addr);
1381 		break;
1382 
1383 	default:
1384 		log_error("Invalid address family\n");
1385 		return -1;
1386 	}
1387 
1388 	if (bind(sd, addr, alen) < 0) {
1389 		log_err_errno("error binding socket");
1390 		return -1;
1391 	}
1392 
1393 	return 0;
1394 }
1395 
1396 static int config_xfrm_policy(int sd, struct sock_args *args)
1397 {
1398 	struct xfrm_userpolicy_info policy = {};
1399 	int type = UDP_ENCAP_ESPINUDP;
1400 	int xfrm_af = IP_XFRM_POLICY;
1401 	int level = SOL_IP;
1402 
1403 	if (args->type != SOCK_DGRAM) {
1404 		log_error("Invalid socket type. Only DGRAM could be used for XFRM\n");
1405 		return 1;
1406 	}
1407 
1408 	policy.action = XFRM_POLICY_ALLOW;
1409 	policy.sel.family = args->version;
1410 	if (args->version == AF_INET6) {
1411 		xfrm_af = IPV6_XFRM_POLICY;
1412 		level = SOL_IPV6;
1413 	}
1414 
1415 	policy.dir = XFRM_POLICY_OUT;
1416 	if (setsockopt(sd, level, xfrm_af, &policy, sizeof(policy)) < 0)
1417 		return 1;
1418 
1419 	policy.dir = XFRM_POLICY_IN;
1420 	if (setsockopt(sd, level, xfrm_af, &policy, sizeof(policy)) < 0)
1421 		return 1;
1422 
1423 	if (setsockopt(sd, IPPROTO_UDP, UDP_ENCAP, &type, sizeof(type)) < 0) {
1424 		log_err_errno("Failed to set xfrm encap");
1425 		return 1;
1426 	}
1427 
1428 	return 0;
1429 }
1430 
1431 static int lsock_init(struct sock_args *args)
1432 {
1433 	long flags;
1434 	int sd;
1435 
1436 	sd = socket(args->version, args->type, args->protocol);
1437 	if (sd < 0) {
1438 		log_err_errno("Error opening socket");
1439 		return  -1;
1440 	}
1441 
1442 	if (set_reuseaddr(sd) != 0)
1443 		goto err;
1444 
1445 	if (set_reuseport(sd) != 0)
1446 		goto err;
1447 
1448 	if (args->dev && bind_to_device(sd, args->dev) != 0)
1449 		goto err;
1450 	else if (args->use_setsockopt &&
1451 		 set_unicast_if(sd, args->ifindex, args->version))
1452 		goto err;
1453 
1454 	if (args->use_freebind && set_freebind(sd, args->version))
1455 		goto err;
1456 
1457 	if (bind_socket(sd, args))
1458 		goto err;
1459 
1460 	if (args->bind_test_only)
1461 		goto out;
1462 
1463 	if (args->type == SOCK_STREAM && listen(sd, 1) < 0) {
1464 		log_err_errno("listen failed");
1465 		goto err;
1466 	}
1467 
1468 	flags = fcntl(sd, F_GETFL);
1469 	if ((flags < 0) || (fcntl(sd, F_SETFL, flags|O_NONBLOCK) < 0)) {
1470 		log_err_errno("Failed to set non-blocking option");
1471 		goto err;
1472 	}
1473 
1474 	if (fcntl(sd, F_SETFD, FD_CLOEXEC) < 0)
1475 		log_err_errno("Failed to set close-on-exec flag");
1476 
1477 	if (args->use_xfrm && config_xfrm_policy(sd, args)) {
1478 		log_err_errno("Failed to set xfrm policy");
1479 		goto err;
1480 	}
1481 
1482 out:
1483 	return sd;
1484 
1485 err:
1486 	close(sd);
1487 	return -1;
1488 }
1489 
1490 static void ipc_write(int fd, int message)
1491 {
1492 	/* Not in both_mode, so there's no process to signal */
1493 	if (fd < 0)
1494 		return;
1495 
1496 	if (write(fd, &message, sizeof(message)) < 0)
1497 		log_err_errno("Failed to send client status");
1498 }
1499 
1500 static int do_server(struct sock_args *args, int ipc_fd)
1501 {
1502 	/* ipc_fd = -1 if no parent process to signal */
1503 	struct timeval timeout = { .tv_sec = prog_timeout }, *ptval = NULL;
1504 	unsigned char addr[sizeof(struct sockaddr_in6)] = {};
1505 	socklen_t alen = sizeof(addr);
1506 	int lsd, csd = -1;
1507 
1508 	fd_set rfds;
1509 	int rc;
1510 
1511 	if (args->serverns) {
1512 		if (switch_ns(args->serverns)) {
1513 			log_error("Could not set server netns to %s\n",
1514 				  args->serverns);
1515 			goto err_exit;
1516 		}
1517 		log_msg("Switched server netns\n");
1518 	}
1519 
1520 	args->dev = args->server_dev;
1521 	args->expected_dev = args->expected_server_dev;
1522 	if (resolve_devices(args) || validate_addresses(args))
1523 		goto err_exit;
1524 
1525 	if (prog_timeout)
1526 		ptval = &timeout;
1527 
1528 	if (args->has_grp)
1529 		lsd = msock_server(args);
1530 	else
1531 		lsd = lsock_init(args);
1532 
1533 	if (lsd < 0)
1534 		goto err_exit;
1535 
1536 	if (args->bind_test_only) {
1537 		close(lsd);
1538 		ipc_write(ipc_fd, 1);
1539 		return 0;
1540 	}
1541 
1542 	if (args->type != SOCK_STREAM) {
1543 		ipc_write(ipc_fd, 1);
1544 		rc = msg_loop(0, lsd, (void *) addr, alen, args);
1545 		close(lsd);
1546 		return rc;
1547 	}
1548 
1549 	if (args->password && tcp_md5_remote(lsd, args)) {
1550 		close(lsd);
1551 		goto err_exit;
1552 	}
1553 
1554 	ipc_write(ipc_fd, 1);
1555 	while (1) {
1556 		log_msg("waiting for client connection.\n");
1557 		FD_ZERO(&rfds);
1558 		FD_SET(lsd, &rfds);
1559 
1560 		rc = select(lsd+1, &rfds, NULL, NULL, ptval);
1561 		if (rc == 0) {
1562 			rc = 2;
1563 			break;
1564 		}
1565 
1566 		if (rc < 0) {
1567 			if (errno == EINTR)
1568 				continue;
1569 
1570 			log_err_errno("select failed");
1571 			break;
1572 		}
1573 
1574 		if (FD_ISSET(lsd, &rfds)) {
1575 
1576 			csd = accept(lsd, (void *) addr, &alen);
1577 			if (csd < 0) {
1578 				log_err_errno("accept failed");
1579 				break;
1580 			}
1581 
1582 			rc = show_sockstat(csd, args);
1583 			if (rc)
1584 				break;
1585 
1586 			rc = check_device(csd, args);
1587 			if (rc)
1588 				break;
1589 		}
1590 
1591 		rc = msg_loop(0, csd, (void *) addr, alen, args);
1592 		close(csd);
1593 
1594 		if (!interactive)
1595 			break;
1596 	}
1597 
1598 	close(lsd);
1599 
1600 	return rc;
1601 err_exit:
1602 	ipc_write(ipc_fd, 0);
1603 	return 1;
1604 }
1605 
1606 static int wait_for_connect(int sd)
1607 {
1608 	struct timeval _tv = { .tv_sec = prog_timeout }, *tv = NULL;
1609 	fd_set wfd;
1610 	int val = 0, sz = sizeof(val);
1611 	int rc;
1612 
1613 	FD_ZERO(&wfd);
1614 	FD_SET(sd, &wfd);
1615 
1616 	if (prog_timeout)
1617 		tv = &_tv;
1618 
1619 	rc = select(FD_SETSIZE, NULL, &wfd, NULL, tv);
1620 	if (rc == 0) {
1621 		log_error("connect timed out\n");
1622 		return -2;
1623 	} else if (rc < 0) {
1624 		log_err_errno("select failed");
1625 		return -3;
1626 	}
1627 
1628 	if (getsockopt(sd, SOL_SOCKET, SO_ERROR, &val, (socklen_t *)&sz) < 0) {
1629 		log_err_errno("getsockopt(SO_ERROR) failed");
1630 		return -4;
1631 	}
1632 
1633 	if (val != 0) {
1634 		log_error("connect failed: %d: %s\n", val, strerror(val));
1635 		return -1;
1636 	}
1637 
1638 	return 0;
1639 }
1640 
1641 static int connectsock(void *addr, socklen_t alen, struct sock_args *args)
1642 {
1643 	int sd, rc = -1;
1644 	long flags;
1645 
1646 	sd = socket(args->version, args->type, args->protocol);
1647 	if (sd < 0) {
1648 		log_err_errno("Failed to create socket");
1649 		return -1;
1650 	}
1651 
1652 	flags = fcntl(sd, F_GETFL);
1653 	if ((flags < 0) || (fcntl(sd, F_SETFL, flags|O_NONBLOCK) < 0)) {
1654 		log_err_errno("Failed to set non-blocking option");
1655 		goto err;
1656 	}
1657 
1658 	if (set_reuseport(sd) != 0)
1659 		goto err;
1660 
1661 	if (args->dev && bind_to_device(sd, args->dev) != 0)
1662 		goto err;
1663 	else if (args->use_setsockopt &&
1664 		 set_unicast_if(sd, args->ifindex, args->version))
1665 		goto err;
1666 
1667 	if (args->has_local_ip && bind_socket(sd, args))
1668 		goto err;
1669 
1670 	if (args->type != SOCK_STREAM && !args->datagram_connect)
1671 		goto out;
1672 
1673 	if (args->password && tcp_md5sig(sd, addr, alen, args))
1674 		goto err;
1675 
1676 	if (args->bind_test_only)
1677 		goto out;
1678 
1679 	if (connect(sd, addr, alen) < 0) {
1680 		if (errno != EINPROGRESS) {
1681 			log_err_errno("Failed to connect to remote host");
1682 			rc = -1;
1683 			goto err;
1684 		}
1685 		rc = wait_for_connect(sd);
1686 		if (rc < 0)
1687 			goto err;
1688 	}
1689 out:
1690 	return sd;
1691 
1692 err:
1693 	close(sd);
1694 	return rc;
1695 }
1696 
1697 static int do_client(struct sock_args *args)
1698 {
1699 	struct sockaddr_in sin = {
1700 		.sin_family = AF_INET,
1701 	};
1702 	struct sockaddr_in6 sin6 = {
1703 		.sin6_family = AF_INET6,
1704 	};
1705 	void *addr;
1706 	int alen;
1707 	int rc = 0;
1708 	int sd;
1709 
1710 	if (!args->has_remote_ip && !args->has_grp) {
1711 		fprintf(stderr, "remote IP or multicast group not given\n");
1712 		return 1;
1713 	}
1714 
1715 	if (args->clientns) {
1716 		if (switch_ns(args->clientns)) {
1717 			log_error("Could not set client netns to %s\n",
1718 				  args->clientns);
1719 			return 1;
1720 		}
1721 		log_msg("Switched client netns\n");
1722 	}
1723 
1724 	args->local_addr_str = args->client_local_addr_str;
1725 	if (resolve_devices(args) || validate_addresses(args))
1726 		return 1;
1727 
1728 	if ((args->use_setsockopt || args->use_cmsg) && !args->ifindex) {
1729 		fprintf(stderr, "Device binding not specified\n");
1730 		return 1;
1731 	}
1732 	if (args->use_setsockopt || args->use_cmsg)
1733 		args->dev = NULL;
1734 
1735 	switch (args->version) {
1736 	case AF_INET:
1737 		sin.sin_port = htons(args->port);
1738 		if (args->has_grp)
1739 			sin.sin_addr = args->grp;
1740 		else
1741 			sin.sin_addr = args->remote_addr.in;
1742 		addr = &sin;
1743 		alen = sizeof(sin);
1744 		break;
1745 	case AF_INET6:
1746 		sin6.sin6_port = htons(args->port);
1747 		sin6.sin6_addr = args->remote_addr.in6;
1748 		sin6.sin6_scope_id = args->scope_id;
1749 		addr = &sin6;
1750 		alen = sizeof(sin6);
1751 		break;
1752 	}
1753 
1754 	args->password = args->client_pw;
1755 
1756 	if (args->has_grp)
1757 		sd = msock_client(args);
1758 	else
1759 		sd = connectsock(addr, alen, args);
1760 
1761 	if (sd < 0)
1762 		return -sd;
1763 
1764 	if (args->bind_test_only)
1765 		goto out;
1766 
1767 	if (args->type == SOCK_STREAM) {
1768 		rc = show_sockstat(sd, args);
1769 		if (rc != 0)
1770 			goto out;
1771 	}
1772 
1773 	rc = msg_loop(1, sd, addr, alen, args);
1774 
1775 out:
1776 	close(sd);
1777 
1778 	return rc;
1779 }
1780 
1781 static char *random_msg(int len)
1782 {
1783 	int i, n = 0, olen = len + 1;
1784 	char *m;
1785 
1786 	if (len <= 0)
1787 		return NULL;
1788 
1789 	m = malloc(olen);
1790 	if (!m)
1791 		return NULL;
1792 
1793 	while (len > 26) {
1794 		i = snprintf(m + n, olen - n, "%.26s",
1795 			     "abcdefghijklmnopqrstuvwxyz");
1796 		n += i;
1797 		len -= i;
1798 	}
1799 	i = snprintf(m + n, olen - n, "%.*s", len,
1800 		     "abcdefghijklmnopqrstuvwxyz");
1801 	return m;
1802 }
1803 
1804 static int ipc_child(int fd, struct sock_args *args)
1805 {
1806 	char *outbuf, *errbuf;
1807 	int rc = 1;
1808 
1809 	outbuf = malloc(4096);
1810 	errbuf = malloc(4096);
1811 	if (!outbuf || !errbuf) {
1812 		fprintf(stderr, "server: Failed to allocate buffers for stdout and stderr\n");
1813 		goto out;
1814 	}
1815 
1816 	setbuffer(stdout, outbuf, 4096);
1817 	setbuffer(stderr, errbuf, 4096);
1818 
1819 	server_mode = 1; /* to tell log_msg in case we are in both_mode */
1820 
1821 	/* when running in both mode, address validation applies
1822 	 * solely to client side
1823 	 */
1824 	args->has_expected_laddr = 0;
1825 	args->has_expected_raddr = 0;
1826 
1827 	rc = do_server(args, fd);
1828 
1829 out:
1830 	free(outbuf);
1831 	free(errbuf);
1832 
1833 	return rc;
1834 }
1835 
1836 static int ipc_parent(int cpid, int fd, struct sock_args *args)
1837 {
1838 	int client_status;
1839 	int status;
1840 	int buf;
1841 
1842 	/* do the client-side function here in the parent process,
1843 	 * waiting to be told when to continue
1844 	 */
1845 	if (read(fd, &buf, sizeof(buf)) <= 0) {
1846 		log_err_errno("Failed to read IPC status from status");
1847 		return 1;
1848 	}
1849 	if (!buf) {
1850 		log_error("Server failed; can not continue\n");
1851 		return 1;
1852 	}
1853 	log_msg("Server is ready\n");
1854 
1855 	client_status = do_client(args);
1856 	log_msg("parent is done!\n");
1857 
1858 	if (kill(cpid, 0) == 0)
1859 		kill(cpid, SIGKILL);
1860 
1861 	wait(&status);
1862 	return client_status;
1863 }
1864 
1865 #define GETOPT_STR  "sr:l:c:p:t:g:P:DRn:M:X:m:d:I:BN:O:SUCi6xL:0:1:2:3:Fbqf"
1866 #define OPT_FORCE_BIND_KEY_IFINDEX 1001
1867 #define OPT_NO_BIND_KEY_IFINDEX 1002
1868 
1869 static struct option long_opts[] = {
1870 	{"force-bind-key-ifindex", 0, 0, OPT_FORCE_BIND_KEY_IFINDEX},
1871 	{"no-bind-key-ifindex", 0, 0, OPT_NO_BIND_KEY_IFINDEX},
1872 	{0, 0, 0, 0}
1873 };
1874 
1875 static void print_usage(char *prog)
1876 {
1877 	printf(
1878 	"usage: %s OPTS\n"
1879 	"Required:\n"
1880 	"    -r addr       remote address to connect to (client mode only)\n"
1881 	"    -p port       port to connect to (client mode)/listen on (server mode)\n"
1882 	"                  (default: %d)\n"
1883 	"    -s            server mode (default: client mode)\n"
1884 	"    -t            timeout seconds (default: none)\n"
1885 	"\n"
1886 	"Optional:\n"
1887 	"    -B            do both client and server via fork and IPC\n"
1888 	"    -N ns         set client to network namespace ns (requires root)\n"
1889 	"    -O ns         set server to network namespace ns (requires root)\n"
1890 	"    -F            Restart server loop\n"
1891 	"    -6            IPv6 (default is IPv4)\n"
1892 	"    -P proto      protocol for socket: icmp, ospf (default: none)\n"
1893 	"    -D|R          datagram (D) / raw (R) socket (default stream)\n"
1894 	"    -l addr       local address to bind to in server mode\n"
1895 	"    -c addr       local address to bind to in client mode\n"
1896 	"    -x            configure XFRM policy on socket\n"
1897 	"\n"
1898 	"    -d dev        bind socket to given device name\n"
1899 	"    -I dev        bind socket to given device name - server mode\n"
1900 	"    -S            use setsockopt (IP_UNICAST_IF or IP_MULTICAST_IF)\n"
1901 	"                  to set device binding\n"
1902 	"    -U            Use connect() and send() for datagram sockets\n"
1903 	"    -f            bind socket with the IP[V6]_FREEBIND option\n"
1904 	"    -C            use cmsg and IP_PKTINFO to specify device binding\n"
1905 	"\n"
1906 	"    -L len        send random message of given length\n"
1907 	"    -n num        number of times to send message\n"
1908 	"\n"
1909 	"    -M password   use MD5 sum protection\n"
1910 	"    -X password   MD5 password for client mode\n"
1911 	"    -m prefix/len prefix and length to use for MD5 key\n"
1912 	"    --no-bind-key-ifindex: Force TCP_MD5SIG_FLAG_IFINDEX off\n"
1913 	"    --force-bind-key-ifindex: Force TCP_MD5SIG_FLAG_IFINDEX on\n"
1914 	"        (default: only if -I is passed)\n"
1915 	"\n"
1916 	"    -g grp        multicast group (e.g., 239.1.1.1)\n"
1917 	"    -i            interactive mode (default is echo and terminate)\n"
1918 	"\n"
1919 	"    -0 addr       Expected local address\n"
1920 	"    -1 addr       Expected remote address\n"
1921 	"    -2 dev        Expected device name (or index) to receive packet\n"
1922 	"    -3 dev        Expected device name (or index) to receive packets - server mode\n"
1923 	"\n"
1924 	"    -b            Bind test only.\n"
1925 	"    -q            Be quiet. Run test without printing anything.\n"
1926 	, prog, DEFAULT_PORT);
1927 }
1928 
1929 int main(int argc, char *argv[])
1930 {
1931 	struct sock_args args = {
1932 		.version = AF_INET,
1933 		.type    = SOCK_STREAM,
1934 		.port    = DEFAULT_PORT,
1935 	};
1936 	struct protoent *pe;
1937 	int both_mode = 0;
1938 	unsigned int tmp;
1939 	int forever = 0;
1940 	int fd[2];
1941 	int cpid;
1942 
1943 	/* process inputs */
1944 	extern char *optarg;
1945 	int rc = 0;
1946 
1947 	/*
1948 	 * process input args
1949 	 */
1950 
1951 	while ((rc = getopt_long(argc, argv, GETOPT_STR, long_opts, NULL)) != -1) {
1952 		switch (rc) {
1953 		case 'B':
1954 			both_mode = 1;
1955 			break;
1956 		case 's':
1957 			server_mode = 1;
1958 			break;
1959 		case 'F':
1960 			forever = 1;
1961 			break;
1962 		case 'l':
1963 			args.has_local_ip = 1;
1964 			args.local_addr_str = optarg;
1965 			break;
1966 		case 'r':
1967 			args.has_remote_ip = 1;
1968 			args.remote_addr_str = optarg;
1969 			break;
1970 		case 'c':
1971 			args.has_local_ip = 1;
1972 			args.client_local_addr_str = optarg;
1973 			break;
1974 		case 'p':
1975 			if (str_to_uint(optarg, 1, 65535, &tmp) != 0) {
1976 				fprintf(stderr, "Invalid port\n");
1977 				return 1;
1978 			}
1979 			args.port = (unsigned short) tmp;
1980 			break;
1981 		case 't':
1982 			if (str_to_uint(optarg, 0, INT_MAX,
1983 					&prog_timeout) != 0) {
1984 				fprintf(stderr, "Invalid timeout\n");
1985 				return 1;
1986 			}
1987 			break;
1988 		case 'D':
1989 			args.type = SOCK_DGRAM;
1990 			break;
1991 		case 'R':
1992 			args.type = SOCK_RAW;
1993 			args.port = 0;
1994 			if (!args.protocol)
1995 				args.protocol = IPPROTO_RAW;
1996 			break;
1997 		case 'P':
1998 			pe = getprotobyname(optarg);
1999 			if (pe) {
2000 				args.protocol = pe->p_proto;
2001 			} else {
2002 				if (str_to_uint(optarg, 0, 0xffff, &tmp) != 0) {
2003 					fprintf(stderr, "Invalid protocol\n");
2004 					return 1;
2005 				}
2006 				args.protocol = tmp;
2007 			}
2008 			break;
2009 		case 'n':
2010 			iter = atoi(optarg);
2011 			break;
2012 		case 'N':
2013 			args.clientns = optarg;
2014 			break;
2015 		case 'O':
2016 			args.serverns = optarg;
2017 			break;
2018 		case 'L':
2019 			msg = random_msg(atoi(optarg));
2020 			break;
2021 		case 'M':
2022 			args.password = optarg;
2023 			break;
2024 		case OPT_FORCE_BIND_KEY_IFINDEX:
2025 			args.bind_key_ifindex = 1;
2026 			break;
2027 		case OPT_NO_BIND_KEY_IFINDEX:
2028 			args.bind_key_ifindex = -1;
2029 			break;
2030 		case 'X':
2031 			args.client_pw = optarg;
2032 			break;
2033 		case 'm':
2034 			args.md5_prefix_str = optarg;
2035 			break;
2036 		case 'S':
2037 			args.use_setsockopt = 1;
2038 			break;
2039 		case 'f':
2040 			args.use_freebind = 1;
2041 			break;
2042 		case 'C':
2043 			args.use_cmsg = 1;
2044 			break;
2045 		case 'd':
2046 			args.dev = optarg;
2047 			break;
2048 		case 'I':
2049 			args.server_dev = optarg;
2050 			break;
2051 		case 'i':
2052 			interactive = 1;
2053 			break;
2054 		case 'g':
2055 			args.has_grp = 1;
2056 			if (convert_addr(&args, optarg, ADDR_TYPE_MCAST) < 0)
2057 				return 1;
2058 			args.type = SOCK_DGRAM;
2059 			break;
2060 		case '6':
2061 			args.version = AF_INET6;
2062 			break;
2063 		case 'b':
2064 			args.bind_test_only = 1;
2065 			break;
2066 		case '0':
2067 			args.has_expected_laddr = 1;
2068 			args.expected_laddr_str = optarg;
2069 			break;
2070 		case '1':
2071 			args.has_expected_raddr = 1;
2072 			args.expected_raddr_str = optarg;
2073 			break;
2074 		case '2':
2075 			args.expected_dev = optarg;
2076 			break;
2077 		case '3':
2078 			args.expected_server_dev = optarg;
2079 			break;
2080 		case 'q':
2081 			quiet = 1;
2082 			break;
2083 		case 'x':
2084 			args.use_xfrm = 1;
2085 			break;
2086 		case 'U':
2087 			args.datagram_connect = 1;
2088 			break;
2089 		default:
2090 			print_usage(argv[0]);
2091 			return 1;
2092 		}
2093 	}
2094 
2095 	if (args.password &&
2096 	    ((!args.has_remote_ip && !args.md5_prefix_str) ||
2097 	      args.type != SOCK_STREAM)) {
2098 		log_error("MD5 passwords apply to TCP only and require a remote ip for the password\n");
2099 		return 1;
2100 	}
2101 
2102 	if (args.md5_prefix_str && !args.password) {
2103 		log_error("Prefix range for MD5 protection specified without a password\n");
2104 		return 1;
2105 	}
2106 
2107 	if (iter == 0) {
2108 		fprintf(stderr, "Invalid number of messages to send\n");
2109 		return 1;
2110 	}
2111 
2112 	if (args.type == SOCK_STREAM && !args.protocol)
2113 		args.protocol = IPPROTO_TCP;
2114 	if (args.type == SOCK_DGRAM && !args.protocol)
2115 		args.protocol = IPPROTO_UDP;
2116 
2117 	if ((args.type == SOCK_STREAM || args.type == SOCK_DGRAM) &&
2118 	     args.port == 0) {
2119 		fprintf(stderr, "Invalid port number\n");
2120 		return 1;
2121 	}
2122 
2123 	if ((both_mode || !server_mode) && !args.has_grp &&
2124 	    !args.has_remote_ip && !args.has_local_ip) {
2125 		fprintf(stderr,
2126 			"Local (server mode) or remote IP (client IP) required\n");
2127 		return 1;
2128 	}
2129 
2130 	if (interactive) {
2131 		prog_timeout = 0;
2132 		msg = NULL;
2133 	}
2134 
2135 	if (both_mode) {
2136 		if (pipe(fd) < 0) {
2137 			perror("pipe");
2138 			exit(1);
2139 		}
2140 
2141 		cpid = fork();
2142 		if (cpid < 0) {
2143 			perror("fork");
2144 			exit(1);
2145 		}
2146 		if (cpid)
2147 			return ipc_parent(cpid, fd[0], &args);
2148 
2149 		return ipc_child(fd[1], &args);
2150 	}
2151 
2152 	if (server_mode) {
2153 		do {
2154 			rc = do_server(&args, -1);
2155 		} while (forever);
2156 
2157 		return rc;
2158 	}
2159 	return do_client(&args);
2160 }
2161