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