xref: /linux/tools/testing/selftests/net/cmsg_sender.c (revision 6785ad21822c67f25647c3a2f609a56dddae5ffb)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 #include <errno.h>
3 #include <error.h>
4 #include <netdb.h>
5 #include <stdbool.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <time.h>
10 #include <unistd.h>
11 #include <linux/errqueue.h>
12 #include <linux/icmp.h>
13 #include <linux/icmpv6.h>
14 #include <linux/net_tstamp.h>
15 #include <linux/types.h>
16 #include <linux/udp.h>
17 #include <sys/socket.h>
18 
19 #include "kselftest.h"
20 
21 enum {
22 	ERN_SUCCESS = 0,
23 	/* Well defined errors, callers may depend on these */
24 	ERN_SEND = 1,
25 	/* Informational, can reorder */
26 	ERN_HELP,
27 	ERN_SEND_SHORT,
28 	ERN_SOCK_CREATE,
29 	ERN_RESOLVE,
30 	ERN_CMSG_WR,
31 	ERN_SOCKOPT,
32 	ERN_GETTIME,
33 	ERN_RECVERR,
34 	ERN_CMSG_RD,
35 	ERN_CMSG_RCV,
36 	ERN_SEND_MORE,
37 	ERN_CONNECT,
38 };
39 
40 struct option_cmsg_u32 {
41 	bool ena;
42 	unsigned int val;
43 };
44 
45 struct options {
46 	bool silent_send;
47 	const char *host;
48 	const char *service;
49 	unsigned int size;
50 	unsigned int num_pkt;
51 	bool msg_more;
52 	bool connected;
53 	struct {
54 		unsigned int mark;
55 		unsigned int dontfrag;
56 		unsigned int tclass;
57 		unsigned int hlimit;
58 		unsigned int priority;
59 	} sockopt;
60 	struct {
61 		unsigned int family;
62 		unsigned int type;
63 		unsigned int proto;
64 	} sock;
65 	struct option_cmsg_u32 mark;
66 	struct option_cmsg_u32 priority;
67 	struct {
68 		bool ena;
69 		unsigned int delay;
70 	} txtime;
71 	struct {
72 		bool ena;
73 	} ts;
74 	struct {
75 		struct option_cmsg_u32 dontfrag;
76 		struct option_cmsg_u32 tclass;
77 		struct option_cmsg_u32 hlimit;
78 		struct option_cmsg_u32 exthdr;
79 	} cmsg;
80 } opt = {
81 	.size = 13,
82 	.num_pkt = 1,
83 	.sock = {
84 		.family	= AF_UNSPEC,
85 		.type	= SOCK_DGRAM,
86 		.proto	= IPPROTO_UDP,
87 	},
88 };
89 
90 static struct timespec time_start_real;
91 static struct timespec time_start_mono;
92 
93 static void __attribute__((noreturn)) cs_usage(const char *bin)
94 {
95 	printf("Usage: %s [opts] <dst host> <dst port / service>\n", bin);
96 	printf("Options:\n"
97 	       "\t\t-s      Silent send() failures\n"
98 	       "\t\t-k      Connect before sending\n"
99 	       "\t\t-S      send() size\n"
100 	       "\t\t-4/-6   Force IPv4 / IPv6 only\n"
101 	       "\t\t-p prot Socket protocol\n"
102 	       "\t\t        (u = UDP (default); i = ICMP; r = RAW;\n"
103 	       "\t\t         U = UDP with MSG_MORE)\n"
104 	       "\n"
105 	       "\t\t-m val  Set SO_MARK with given value\n"
106 	       "\t\t-M val  Set SO_MARK via setsockopt\n"
107 	       "\t\t-P val  Set SO_PRIORITY via setsockopt\n"
108 	       "\t\t-Q val  Set SO_PRIORITY via cmsg\n"
109 	       "\t\t-d val  Set SO_TXTIME with given delay (usec)\n"
110 	       "\t\t-t      Enable time stamp reporting\n"
111 	       "\t\t-f val  Set don't fragment via cmsg\n"
112 	       "\t\t-F val  Set don't fragment via setsockopt\n"
113 	       "\t\t-c val  Set TOS/TCLASS via cmsg\n"
114 	       "\t\t-C val  Set TOS/TCLASS via setsockopt\n"
115 	       "\t\t-l val  Set TTL/HOPLIMIT via cmsg\n"
116 	       "\t\t-L val  Set TTL/HOPLIMIT via setsockopt\n"
117 	       "\t\t-H type Add an IPv6 header option\n"
118 	       "\t\t        (h = HOP; d = DST; r = RTDST)\n"
119 	       "\n");
120 	exit(ERN_HELP);
121 }
122 
123 static void cs_parse_args(int argc, char *argv[])
124 {
125 	int o;
126 
127 	while ((o = getopt(argc, argv,
128 			   "46ksS:p:P:m:M:n:d:tf:F:c:C:l:L:H:Q:")) != -1) {
129 		switch (o) {
130 		case 'k':
131 			opt.connected = true;
132 			break;
133 		case 's':
134 			opt.silent_send = true;
135 			break;
136 		case 'S':
137 			opt.size = atoi(optarg);
138 			break;
139 		case '4':
140 			opt.sock.family = AF_INET;
141 			break;
142 		case '6':
143 			opt.sock.family = AF_INET6;
144 			break;
145 		case 'p':
146 			if (*optarg == 'u') {
147 				opt.sock.proto = IPPROTO_UDP;
148 			} else if (*optarg == 'U') {
149 				opt.sock.proto = IPPROTO_UDP;
150 				opt.msg_more = true;
151 			} else if (*optarg == 'i' || *optarg == 'I') {
152 				opt.sock.proto = IPPROTO_ICMP;
153 			} else if (*optarg == 'r') {
154 				opt.sock.type = SOCK_RAW;
155 			} else {
156 				printf("Error: unknown protocol: %s\n", optarg);
157 				cs_usage(argv[0]);
158 			}
159 			break;
160 		case 'P':
161 			opt.sockopt.priority = atoi(optarg);
162 			break;
163 		case 'm':
164 			opt.mark.ena = true;
165 			opt.mark.val = atoi(optarg);
166 			break;
167 		case 'Q':
168 			opt.priority.ena = true;
169 			opt.priority.val = atoi(optarg);
170 			break;
171 		case 'M':
172 			opt.sockopt.mark = atoi(optarg);
173 			break;
174 		case 'n':
175 			opt.num_pkt = atoi(optarg);
176 			break;
177 		case 'd':
178 			opt.txtime.ena = true;
179 			opt.txtime.delay = atoi(optarg);
180 			break;
181 		case 't':
182 			opt.ts.ena = true;
183 			break;
184 		case 'f':
185 			opt.cmsg.dontfrag.ena = true;
186 			opt.cmsg.dontfrag.val = atoi(optarg);
187 			break;
188 		case 'F':
189 			opt.sockopt.dontfrag = atoi(optarg);
190 			break;
191 		case 'c':
192 			opt.cmsg.tclass.ena = true;
193 			opt.cmsg.tclass.val = atoi(optarg);
194 			break;
195 		case 'C':
196 			opt.sockopt.tclass = atoi(optarg);
197 			break;
198 		case 'l':
199 			opt.cmsg.hlimit.ena = true;
200 			opt.cmsg.hlimit.val = atoi(optarg);
201 			break;
202 		case 'L':
203 			opt.sockopt.hlimit = atoi(optarg);
204 			break;
205 		case 'H':
206 			opt.cmsg.exthdr.ena = true;
207 			switch (optarg[0]) {
208 			case 'h':
209 				opt.cmsg.exthdr.val = IPV6_HOPOPTS;
210 				break;
211 			case 'd':
212 				opt.cmsg.exthdr.val = IPV6_DSTOPTS;
213 				break;
214 			case 'r':
215 				opt.cmsg.exthdr.val = IPV6_RTHDRDSTOPTS;
216 				break;
217 			default:
218 				printf("Error: hdr type: %s\n", optarg);
219 				break;
220 			}
221 			break;
222 		}
223 	}
224 
225 	if (optind != argc - 2)
226 		cs_usage(argv[0]);
227 
228 	opt.host = argv[optind];
229 	opt.service = argv[optind + 1];
230 }
231 
232 static void memrnd(void *s, size_t n)
233 {
234 	int *dword = s;
235 	char *byte;
236 
237 	for (; n >= 4; n -= 4)
238 		*dword++ = rand();
239 	byte = (void *)dword;
240 	while (n--)
241 		*byte++ = rand();
242 }
243 
244 static void
245 ca_write_cmsg_u32(char *cbuf, size_t cbuf_sz, size_t *cmsg_len,
246 		  int level, int optname, struct option_cmsg_u32 *uopt)
247 {
248 	struct cmsghdr *cmsg;
249 
250 	if (!uopt->ena)
251 		return;
252 
253 	cmsg = (struct cmsghdr *)(cbuf + *cmsg_len);
254 	*cmsg_len += CMSG_SPACE(sizeof(__u32));
255 	if (cbuf_sz < *cmsg_len)
256 		error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small");
257 
258 	cmsg->cmsg_level = level;
259 	cmsg->cmsg_type = optname;
260 	cmsg->cmsg_len = CMSG_LEN(sizeof(__u32));
261 	*(__u32 *)CMSG_DATA(cmsg) = uopt->val;
262 }
263 
264 static void
265 cs_write_cmsg(int fd, struct msghdr *msg, char *cbuf, size_t cbuf_sz)
266 {
267 	struct cmsghdr *cmsg;
268 	size_t cmsg_len;
269 
270 	msg->msg_control = cbuf;
271 	cmsg_len = 0;
272 
273 	ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
274 			  SOL_SOCKET, SO_MARK, &opt.mark);
275 	ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
276 			  SOL_SOCKET, SO_PRIORITY, &opt.priority);
277 
278 	if (opt.sock.family == AF_INET) {
279 		ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
280 				  SOL_IP, IP_TOS, &opt.cmsg.tclass);
281 		ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
282 				  SOL_IP, IP_TTL, &opt.cmsg.hlimit);
283 	} else {
284 		ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
285 				  SOL_IPV6, IPV6_DONTFRAG, &opt.cmsg.dontfrag);
286 		ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
287 				  SOL_IPV6, IPV6_TCLASS, &opt.cmsg.tclass);
288 		ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len,
289 				  SOL_IPV6, IPV6_HOPLIMIT, &opt.cmsg.hlimit);
290 	}
291 
292 	if (opt.txtime.ena) {
293 		__u64 txtime;
294 
295 		txtime = time_start_mono.tv_sec * (1000ULL * 1000 * 1000) +
296 			 time_start_mono.tv_nsec +
297 			 opt.txtime.delay * 1000;
298 
299 		cmsg = (struct cmsghdr *)(cbuf + cmsg_len);
300 		cmsg_len += CMSG_SPACE(sizeof(txtime));
301 		if (cbuf_sz < cmsg_len)
302 			error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small");
303 
304 		cmsg->cmsg_level = SOL_SOCKET;
305 		cmsg->cmsg_type = SCM_TXTIME;
306 		cmsg->cmsg_len = CMSG_LEN(sizeof(txtime));
307 		memcpy(CMSG_DATA(cmsg), &txtime, sizeof(txtime));
308 	}
309 	if (opt.ts.ena) {
310 		cmsg = (struct cmsghdr *)(cbuf + cmsg_len);
311 		cmsg_len += CMSG_SPACE(sizeof(__u32));
312 		if (cbuf_sz < cmsg_len)
313 			error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small");
314 
315 		cmsg->cmsg_level = SOL_SOCKET;
316 		cmsg->cmsg_type = SO_TIMESTAMPING;
317 		cmsg->cmsg_len = CMSG_LEN(sizeof(__u32));
318 		*(__u32 *)CMSG_DATA(cmsg) = SOF_TIMESTAMPING_TX_SCHED |
319 					    SOF_TIMESTAMPING_TX_SOFTWARE;
320 	}
321 	if (opt.cmsg.exthdr.ena) {
322 		cmsg = (struct cmsghdr *)(cbuf + cmsg_len);
323 		cmsg_len += CMSG_SPACE(8);
324 		if (cbuf_sz < cmsg_len)
325 			error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small");
326 
327 		cmsg->cmsg_level = SOL_IPV6;
328 		cmsg->cmsg_type = opt.cmsg.exthdr.val;
329 		cmsg->cmsg_len = CMSG_LEN(8);
330 		*(__u64 *)CMSG_DATA(cmsg) = 0;
331 	}
332 
333 	if (cmsg_len)
334 		msg->msg_controllen = cmsg_len;
335 	else
336 		msg->msg_control = NULL;
337 }
338 
339 static const char *cs_ts_info2str(unsigned int info)
340 {
341 	static const char *names[] = {
342 		[SCM_TSTAMP_SND]	= "SND",
343 		[SCM_TSTAMP_SCHED]	= "SCHED",
344 		[SCM_TSTAMP_ACK]	= "ACK",
345 	};
346 
347 	if (info < ARRAY_SIZE(names))
348 		return names[info];
349 	return "unknown";
350 }
351 
352 static unsigned long
353 cs_read_cmsg(int fd, struct msghdr *msg, char *cbuf, size_t cbuf_sz)
354 {
355 	struct sock_extended_err *see;
356 	struct scm_timestamping *ts;
357 	unsigned long ts_seen = 0;
358 	struct cmsghdr *cmsg;
359 	int i, err;
360 
361 	if (!opt.ts.ena)
362 		return 0;
363 	msg->msg_control = cbuf;
364 	msg->msg_controllen = cbuf_sz;
365 
366 	while (true) {
367 		ts = NULL;
368 		see = NULL;
369 		memset(cbuf, 0, cbuf_sz);
370 
371 		err = recvmsg(fd, msg, MSG_ERRQUEUE);
372 		if (err < 0) {
373 			if (errno == EAGAIN)
374 				break;
375 			error(ERN_RECVERR, errno, "recvmsg ERRQ");
376 		}
377 
378 		for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
379 		     cmsg = CMSG_NXTHDR(msg, cmsg)) {
380 			if (cmsg->cmsg_level == SOL_SOCKET &&
381 			    cmsg->cmsg_type == SO_TIMESTAMPING_OLD) {
382 				if (cmsg->cmsg_len < sizeof(*ts))
383 					error(ERN_CMSG_RD, EINVAL, "TS cmsg");
384 
385 				ts = (void *)CMSG_DATA(cmsg);
386 			}
387 			if ((cmsg->cmsg_level == SOL_IP &&
388 			     cmsg->cmsg_type == IP_RECVERR) ||
389 			    (cmsg->cmsg_level == SOL_IPV6 &&
390 			     cmsg->cmsg_type == IPV6_RECVERR)) {
391 				if (cmsg->cmsg_len < sizeof(*see))
392 					error(ERN_CMSG_RD, EINVAL, "sock_err cmsg");
393 
394 				see = (void *)CMSG_DATA(cmsg);
395 			}
396 		}
397 
398 		if (!ts)
399 			error(ERN_CMSG_RCV, ENOENT, "TS cmsg not found");
400 		if (!see)
401 			error(ERN_CMSG_RCV, ENOENT, "sock_err cmsg not found");
402 
403 		for (i = 0; i < 3; i++) {
404 			unsigned long long rel_time;
405 
406 			if (!ts->ts[i].tv_sec && !ts->ts[i].tv_nsec)
407 				continue;
408 
409 			rel_time = (ts->ts[i].tv_sec - time_start_real.tv_sec) *
410 				(1000ULL * 1000) +
411 				(ts->ts[i].tv_nsec - time_start_real.tv_nsec) /
412 				1000;
413 			printf(" %5s ts%d %lluus\n",
414 			       cs_ts_info2str(see->ee_info),
415 			       i, rel_time);
416 			ts_seen |= 1 << see->ee_info;
417 		}
418 	}
419 
420 	return ts_seen;
421 }
422 
423 static void ca_set_sockopts(int fd)
424 {
425 	if (opt.sockopt.mark &&
426 	    setsockopt(fd, SOL_SOCKET, SO_MARK,
427 		       &opt.sockopt.mark, sizeof(opt.sockopt.mark)))
428 		error(ERN_SOCKOPT, errno, "setsockopt SO_MARK");
429 	if (opt.sockopt.priority &&
430 	    setsockopt(fd, SOL_SOCKET, SO_PRIORITY,
431 		       &opt.sockopt.priority, sizeof(opt.sockopt.priority)))
432 		error(ERN_SOCKOPT, errno, "setsockopt SO_PRIORITY");
433 
434 	if (opt.sock.family == AF_INET) {
435 		if (opt.sockopt.tclass &&
436 		    setsockopt(fd, SOL_IP, IP_TOS,
437 			       &opt.sockopt.tclass, sizeof(opt.sockopt.tclass)))
438 			error(ERN_SOCKOPT, errno, "setsockopt IP_TOS");
439 		if (opt.sockopt.hlimit &&
440 		    setsockopt(fd, SOL_IP, IP_TTL,
441 			       &opt.sockopt.hlimit, sizeof(opt.sockopt.hlimit)))
442 			error(ERN_SOCKOPT, errno, "setsockopt IP_TTL");
443 	} else {
444 		if (opt.sockopt.dontfrag &&
445 		    setsockopt(fd, SOL_IPV6, IPV6_DONTFRAG,
446 			       &opt.sockopt.dontfrag, sizeof(opt.sockopt.dontfrag)))
447 			error(ERN_SOCKOPT, errno, "setsockopt IPV6_DONTFRAG");
448 		if (opt.sockopt.tclass &&
449 		    setsockopt(fd, SOL_IPV6, IPV6_TCLASS,
450 			       &opt.sockopt.tclass, sizeof(opt.sockopt.tclass)))
451 			error(ERN_SOCKOPT, errno, "setsockopt IPV6_TCLASS");
452 		if (opt.sockopt.hlimit &&
453 		    setsockopt(fd, SOL_IPV6, IPV6_UNICAST_HOPS,
454 			       &opt.sockopt.hlimit, sizeof(opt.sockopt.hlimit)))
455 			error(ERN_SOCKOPT, errno, "setsockopt IPV6_HOPLIMIT");
456 	}
457 
458 	if (opt.txtime.ena) {
459 		struct sock_txtime so_txtime = {
460 			.clockid = CLOCK_MONOTONIC,
461 		};
462 
463 		if (setsockopt(fd, SOL_SOCKET, SO_TXTIME,
464 			       &so_txtime, sizeof(so_txtime)))
465 			error(ERN_SOCKOPT, errno, "setsockopt TXTIME");
466 	}
467 	if (opt.ts.ena) {
468 		__u32 val = SOF_TIMESTAMPING_SOFTWARE |
469 			SOF_TIMESTAMPING_OPT_TSONLY;
470 
471 		if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING,
472 			       &val, sizeof(val)))
473 			error(ERN_SOCKOPT, errno, "setsockopt TIMESTAMPING");
474 	}
475 }
476 
477 int main(int argc, char *argv[])
478 {
479 	struct addrinfo hints, *ai;
480 	struct iovec iov[1];
481 	unsigned char *buf;
482 	struct msghdr msg;
483 	char cbuf[1024];
484 	int err;
485 	int fd;
486 	int i;
487 
488 	cs_parse_args(argc, argv);
489 
490 	buf = malloc(opt.size);
491 	memrnd(buf, opt.size);
492 
493 	memset(&hints, 0, sizeof(hints));
494 	hints.ai_family = opt.sock.family;
495 
496 	ai = NULL;
497 	err = getaddrinfo(opt.host, opt.service, &hints, &ai);
498 	if (err) {
499 		fprintf(stderr, "Can't resolve address [%s]:%s\n",
500 			opt.host, opt.service);
501 		err = ERN_SOCK_CREATE;
502 		goto err_free_buff;
503 	}
504 
505 	if (ai->ai_family == AF_INET6 && opt.sock.proto == IPPROTO_ICMP)
506 		opt.sock.proto = IPPROTO_ICMPV6;
507 
508 	fd = socket(ai->ai_family, opt.sock.type, opt.sock.proto);
509 	if (fd < 0) {
510 		fprintf(stderr, "Can't open socket: %s\n", strerror(errno));
511 		err = ERN_RESOLVE;
512 		goto err_free_info;
513 	}
514 
515 	if (opt.sock.proto == IPPROTO_ICMP) {
516 		buf[0] = ICMP_ECHO;
517 		buf[1] = 0;
518 	} else if (opt.sock.proto == IPPROTO_ICMPV6) {
519 		buf[0] = ICMPV6_ECHO_REQUEST;
520 		buf[1] = 0;
521 	} else if (opt.sock.type == SOCK_RAW) {
522 		struct udphdr hdr = { 1, 2, htons(opt.size), 0 };
523 		struct sockaddr_in6 *sin6 = (void *)ai->ai_addr;
524 
525 		memcpy(buf, &hdr, sizeof(hdr));
526 		sin6->sin6_port = htons(opt.sock.proto);
527 	}
528 
529 	ca_set_sockopts(fd);
530 
531 	if (opt.connected && connect(fd, ai->ai_addr, ai->ai_addrlen)) {
532 		fprintf(stderr, "Can't connect socket: %s\n", strerror(errno));
533 		err = ERN_CONNECT;
534 		goto err_out;
535 	}
536 
537 	if (clock_gettime(CLOCK_REALTIME, &time_start_real))
538 		error(ERN_GETTIME, errno, "gettime REALTIME");
539 	if (clock_gettime(CLOCK_MONOTONIC, &time_start_mono))
540 		error(ERN_GETTIME, errno, "gettime MONOTONIC");
541 
542 	iov[0].iov_base = buf;
543 	iov[0].iov_len = opt.size;
544 
545 	memset(&msg, 0, sizeof(msg));
546 	if (!opt.connected) {
547 		msg.msg_name = ai->ai_addr;
548 		msg.msg_namelen = ai->ai_addrlen;
549 	}
550 	msg.msg_iov = iov;
551 	msg.msg_iovlen = 1;
552 
553 	cs_write_cmsg(fd, &msg, cbuf, sizeof(cbuf));
554 
555 	for (i = 0; i < opt.num_pkt; i++) {
556 		err = sendmsg(fd, &msg, opt.msg_more ? MSG_MORE : 0);
557 		if (err < 0) {
558 			if (!opt.silent_send)
559 				fprintf(stderr, "send failed: %s\n", strerror(errno));
560 			err = ERN_SEND;
561 			goto err_out;
562 		} else if (err != (int)opt.size) {
563 			fprintf(stderr, "short send\n");
564 			err = ERN_SEND_SHORT;
565 			goto err_out;
566 		}
567 		if (opt.msg_more) {
568 			err = write(fd, NULL, 0);
569 			if (err < 0) {
570 				fprintf(stderr, "send more: %s\n", strerror(errno));
571 				err = ERN_SEND_MORE;
572 				goto err_out;
573 			}
574 		}
575 	}
576 	err = ERN_SUCCESS;
577 
578 	if (opt.ts.ena) {
579 		unsigned long seen;
580 		int i;
581 
582 		/* Make sure all timestamps have time to loop back */
583 		for (i = 0; i < 40; i++) {
584 			seen = cs_read_cmsg(fd, &msg, cbuf, sizeof(cbuf));
585 			if (seen & (1 << SCM_TSTAMP_SND))
586 				break;
587 			usleep(opt.txtime.delay / 20);
588 		}
589 	}
590 
591 err_out:
592 	close(fd);
593 err_free_info:
594 	freeaddrinfo(ai);
595 err_free_buff:
596 	free(buf);
597 	return err;
598 }
599