xref: /freebsd/tests/sys/kern/unix_passfd_test.c (revision 058ac3e8063366dafa634d9107642e12b038bf09)
1 /*-
2  * Copyright (c) 2005 Robert N. M. Watson
3  * Copyright (c) 2015 Mark Johnston
4  * Copyright (c) 2022 Gleb Smirnoff <glebius@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/sysctl.h>
36 #include <sys/time.h>
37 #include <sys/resource.h>
38 #include <sys/un.h>
39 
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <limits.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 
48 #include <atf-c.h>
49 
50 #if !defined(TEST_PROTO)
51 #error Need TEST_PROTO defined to SOCK_STREAM or SOCK_DGRAM
52 #endif
53 
54 /*
55  * UNIX domain sockets allow file descriptors to be passed via "ancillary
56  * data", or control messages.  This regression test is intended to exercise
57  * this facility, both performing some basic tests that it operates, and also
58  * causing some kernel edge cases to execute, such as garbage collection when
59  * there are cyclic file descriptor references.  Right now we test only with
60  * stream sockets, but ideally we'd also test with datagram sockets.
61  */
62 
63 static void
64 domainsocketpair(int *fdp)
65 {
66 
67 	ATF_REQUIRE_MSG(socketpair(PF_UNIX, TEST_PROTO, 0, fdp) != -1,
68 	    "socketpair(PF_UNIX, %u) failed: %s", TEST_PROTO, strerror(errno));
69 }
70 
71 static void
72 closesocketpair(int *fdp)
73 {
74 
75 	close(fdp[0]);
76 	close(fdp[1]);
77 }
78 
79 static void
80 devnull(int *fdp)
81 {
82 	int fd;
83 
84 	fd = open("/dev/null", O_RDONLY);
85 	ATF_REQUIRE_MSG(fd != -1, "open failed: %s", strerror(errno));
86 	*fdp = fd;
87 }
88 
89 static void
90 tempfile(int *fdp)
91 {
92 	char path[PATH_MAX];
93 	int fd;
94 
95 	snprintf(path, PATH_MAX, "%s/unix_passfd.XXXXXXXXXXXXXXX",
96 	    getenv("TMPDIR") == NULL ? "/tmp" : getenv("TMPDIR"));
97 	fd = mkstemp(path);
98 	ATF_REQUIRE_MSG(fd != -1, "mkstemp(%s) failed", path);
99 	(void)unlink(path);
100 	*fdp = fd;
101 }
102 
103 static void
104 dofstat(int fd, struct stat *sb)
105 {
106 
107 	ATF_REQUIRE_MSG(fstat(fd, sb) == 0,
108 	    "fstat failed: %s", strerror(errno));
109 }
110 
111 static int
112 getnfds(void)
113 {
114 	size_t len;
115 	int mib[4], n, rc;
116 
117 	len = sizeof(n);
118 	mib[0] = CTL_KERN;
119 	mib[1] = KERN_PROC;
120 	mib[2] = KERN_PROC_NFDS;
121 	mib[3] = 0;
122 
123 	rc = sysctl(mib, 4, &n, &len, NULL, 0);
124 	ATF_REQUIRE_MSG(rc != -1, "sysctl(KERN_PROC_NFDS) failed");
125 	return (n);
126 }
127 
128 static int
129 openfiles(void)
130 {
131 	int files;
132 	size_t len = sizeof(files);
133 
134 	ATF_REQUIRE(sysctlbyname("kern.openfiles", &files, &len, NULL, 0) == 0);
135 
136 	return (files);
137 }
138 
139 static void
140 putfds(char *buf, int fd, int nfds)
141 {
142 	struct cmsghdr *cm;
143 	int *fdp, i;
144 
145 	cm = (struct cmsghdr *)buf;
146 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
147 	cm->cmsg_level = SOL_SOCKET;
148 	cm->cmsg_type = SCM_RIGHTS;
149 	for (fdp = (int *)CMSG_DATA(cm), i = 0; i < nfds; i++)
150 		*fdp++ = fd;
151 }
152 
153 static void
154 samefile(struct stat *sb1, struct stat *sb2)
155 {
156 
157 	ATF_REQUIRE_MSG(sb1->st_dev == sb2->st_dev, "different device");
158 	ATF_REQUIRE_MSG(sb1->st_ino == sb2->st_ino, "different inode");
159 }
160 
161 static ssize_t
162 sendfd_payload(int sockfd, int send_fd, void *payload, size_t paylen)
163 {
164 	struct iovec iovec;
165 	char message[CMSG_SPACE(sizeof(int))];
166 	struct msghdr msghdr;
167 
168 	bzero(&msghdr, sizeof(msghdr));
169 	bzero(&message, sizeof(message));
170 
171 	msghdr.msg_control = message;
172 	msghdr.msg_controllen = sizeof(message);
173 
174 	iovec.iov_base = payload;
175 	iovec.iov_len = paylen;
176 
177 	msghdr.msg_iov = &iovec;
178 	msghdr.msg_iovlen = 1;
179 
180 	putfds(message, send_fd, 1);
181 	return (sendmsg(sockfd, &msghdr, 0));
182 }
183 
184 static void
185 sendfd(int sockfd, int send_fd)
186 {
187 	size_t len;
188 	char ch;
189 
190 	ch = 0;
191 	len = sendfd_payload(sockfd, send_fd, &ch, sizeof(ch));
192 	ATF_REQUIRE_MSG(len == sizeof(ch),
193 	    "sendmsg: %zu bytes sent; expected %zu; %s", len, sizeof(ch),
194 	    strerror(errno));
195 }
196 
197 static bool
198 localcreds(int sockfd)
199 {
200 	socklen_t sz;
201 	int rc, val;
202 
203 	sz = sizeof(val);
204 	rc = getsockopt(sockfd, 0, LOCAL_CREDS, &val, &sz);
205 	ATF_REQUIRE_MSG(rc != -1, "getsockopt(LOCAL_CREDS) failed: %s",
206 	    strerror(errno));
207 	return (val != 0);
208 }
209 
210 static void
211 recvfd_payload(int sockfd, int *recv_fd, void *buf, size_t buflen,
212     size_t cmsgsz, int recvmsg_flags)
213 {
214 	struct cmsghdr *cmsghdr;
215 	struct msghdr msghdr;
216 	struct iovec iovec;
217 	char *message;
218 	ssize_t len;
219 	bool foundcreds;
220 
221 	bzero(&msghdr, sizeof(msghdr));
222 	message = malloc(cmsgsz);
223 	ATF_REQUIRE(message != NULL);
224 
225 	msghdr.msg_control = message;
226 	msghdr.msg_controllen = cmsgsz;
227 
228 	iovec.iov_base = buf;
229 	iovec.iov_len = buflen;
230 
231 	msghdr.msg_iov = &iovec;
232 	msghdr.msg_iovlen = 1;
233 
234 	len = recvmsg(sockfd, &msghdr, recvmsg_flags);
235 	ATF_REQUIRE_MSG(len != -1, "recvmsg failed: %s", strerror(errno));
236 	ATF_REQUIRE_MSG((size_t)len == buflen,
237 	    "recvmsg: %zd bytes received; expected %zd", len, buflen);
238 
239 	cmsghdr = CMSG_FIRSTHDR(&msghdr);
240 	ATF_REQUIRE_MSG(cmsghdr != NULL,
241 	    "recvmsg: did not receive control message");
242 	foundcreds = false;
243 	*recv_fd = -1;
244 	for (; cmsghdr != NULL; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) {
245 		if (cmsghdr->cmsg_level == SOL_SOCKET &&
246 		    cmsghdr->cmsg_type == SCM_RIGHTS &&
247 		    cmsghdr->cmsg_len == CMSG_LEN(sizeof(int))) {
248 			memcpy(recv_fd, CMSG_DATA(cmsghdr), sizeof(int));
249 			ATF_REQUIRE(*recv_fd != -1);
250 		} else if (cmsghdr->cmsg_level == SOL_SOCKET &&
251 		    cmsghdr->cmsg_type == SCM_CREDS)
252 			foundcreds = true;
253 	}
254 	ATF_REQUIRE_MSG(*recv_fd != -1,
255 	    "recvmsg: did not receive single-fd message");
256 	ATF_REQUIRE_MSG(!localcreds(sockfd) || foundcreds,
257 	    "recvmsg: expected credentials were not received");
258 	ATF_REQUIRE_MSG((msghdr.msg_flags & MSG_TRUNC) == 0,
259 	    "recvmsg: MSG_TRUNC is set while buffer is sufficient");
260 }
261 
262 static void
263 recvfd(int sockfd, int *recv_fd, int flags)
264 {
265 	char ch = 0;
266 
267 	recvfd_payload(sockfd, recv_fd, &ch, sizeof(ch),
268 	    CMSG_SPACE(sizeof(int)), flags);
269 }
270 
271 #if TEST_PROTO == SOCK_STREAM
272 #define	LOCAL_SENDSPACE_SYSCTL	"net.local.stream.sendspace"
273 #define	LOCAL_RECVSPACE_SYSCTL	"net.local.stream.recvspace"
274 #elif TEST_PROTO == SOCK_DGRAM
275 #define	LOCAL_SENDSPACE_SYSCTL	"net.local.dgram.maxdgram"
276 #define	LOCAL_RECVSPACE_SYSCTL	"net.local.dgram.recvspace"
277 #endif
278 
279 static u_long
280 getsendspace(void)
281 {
282 	u_long sendspace;
283 
284 	ATF_REQUIRE_MSG(sysctlbyname(LOCAL_SENDSPACE_SYSCTL, &sendspace,
285             &(size_t){sizeof(u_long)}, NULL, 0) != -1,
286 	    "sysctl %s failed: %s", LOCAL_SENDSPACE_SYSCTL, strerror(errno));
287 
288 	return (sendspace);
289 }
290 
291 static u_long
292 getrecvspace(void)
293 {
294 	u_long recvspace;
295 
296 	ATF_REQUIRE_MSG(sysctlbyname(LOCAL_RECVSPACE_SYSCTL, &recvspace,
297             &(size_t){sizeof(u_long)}, NULL, 0) != -1,
298 	    "sysctl %s failed: %s", LOCAL_RECVSPACE_SYSCTL, strerror(errno));
299 
300 	return (recvspace);
301 }
302 
303 /*
304  * Fill socket to a state when next max sized send would fail with EAGAIN.
305  */
306 static void
307 fill(int fd)
308 {
309 	u_long sendspace;
310 	void *buf;
311 
312 	sendspace = getsendspace();
313 	ATF_REQUIRE((buf = malloc(sendspace)) != NULL);
314 
315 	ATF_REQUIRE_MSG(fcntl(fd, F_SETFL, O_NONBLOCK) != -1,
316 	    "fcntl(O_NONBLOCK) failed: %s", strerror(errno));
317 
318 #if TEST_PROTO == SOCK_STREAM
319 	do {} while (send(fd, buf, sendspace, 0) == (ssize_t)sendspace);
320 #elif TEST_PROTO == SOCK_DGRAM
321 	u_long recvspace = getrecvspace();
322 
323 	for (ssize_t sent = 0;
324 	    sent + sendspace + sizeof(struct sockaddr) < recvspace;
325 	    sent += sendspace + sizeof(struct sockaddr))
326 		ATF_REQUIRE(send(fd, buf, sendspace, 0) == (ssize_t)sendspace);
327 #endif
328 	free(buf);
329 }
330 
331 /*
332  * Put a temporary file into a UNIX domain socket, then take it out and make
333  * sure it's the same file.  First time around, don't close the reference
334  * after sending.
335  */
336 ATF_TC_WITHOUT_HEAD(simple_send_fd);
337 ATF_TC_BODY(simple_send_fd, tc)
338 {
339 	struct stat getfd_stat, putfd_stat;
340 	int fd[2], getfd, putfd;
341 
342 	domainsocketpair(fd);
343 	tempfile(&putfd);
344 	dofstat(putfd, &putfd_stat);
345 	sendfd(fd[0], putfd);
346 	recvfd(fd[1], &getfd, 0);
347 	dofstat(getfd, &getfd_stat);
348 	samefile(&putfd_stat, &getfd_stat);
349 	close(putfd);
350 	close(getfd);
351 	closesocketpair(fd);
352 }
353 
354 /*
355  * Like simple_send_fd but also sets MSG_CMSG_CLOEXEC and checks that the
356  * received file descriptor has the FD_CLOEXEC flag set.
357  */
358 ATF_TC_WITHOUT_HEAD(simple_send_fd_msg_cmsg_cloexec);
359 ATF_TC_BODY(simple_send_fd_msg_cmsg_cloexec, tc)
360 {
361 	struct stat getfd_stat, putfd_stat;
362 	int fd[2], getfd, putfd;
363 
364 	domainsocketpair(fd);
365 	tempfile(&putfd);
366 	dofstat(putfd, &putfd_stat);
367 	sendfd(fd[0], putfd);
368 	recvfd(fd[1], &getfd, MSG_CMSG_CLOEXEC);
369 	dofstat(getfd, &getfd_stat);
370 	samefile(&putfd_stat, &getfd_stat);
371 	ATF_REQUIRE_EQ_MSG(fcntl(getfd, F_GETFD) & FD_CLOEXEC, FD_CLOEXEC,
372 	    "FD_CLOEXEC not set on the received file descriptor");
373 	close(putfd);
374 	close(getfd);
375 	closesocketpair(fd);
376 }
377 
378 /*
379  * Same as simple_send_fd, only close the file reference after sending, so that
380  * the only reference is the descriptor in the UNIX domain socket buffer.
381  */
382 ATF_TC_WITHOUT_HEAD(send_and_close);
383 ATF_TC_BODY(send_and_close, tc)
384 {
385 	struct stat getfd_stat, putfd_stat;
386 	int fd[2], getfd, putfd;
387 
388 	domainsocketpair(fd);
389 	tempfile(&putfd);
390 	dofstat(putfd, &putfd_stat);
391 	sendfd(fd[0], putfd);
392 	close(putfd);
393 	recvfd(fd[1], &getfd, 0);
394 	dofstat(getfd, &getfd_stat);
395 	samefile(&putfd_stat, &getfd_stat);
396 	close(getfd);
397 	closesocketpair(fd);
398 }
399 
400 /*
401  * Put a temporary file into a UNIX domain socket, then close both endpoints
402  * causing garbage collection to kick off.
403  */
404 ATF_TC_WITHOUT_HEAD(send_and_cancel);
405 ATF_TC_BODY(send_and_cancel, tc)
406 {
407 	int fd[2], putfd;
408 
409 	domainsocketpair(fd);
410 	tempfile(&putfd);
411 	sendfd(fd[0], putfd);
412 	close(putfd);
413 	closesocketpair(fd);
414 }
415 
416 /*
417  * Send file then shutdown receive side to exercise unp_dispose() call
418  * via soshutdown().  Check that shutdown(SHUT_RD) would gc the file
419  * reference sitting in the receive buffer.  There is no good way of
420  * checking that except using global open file count.
421  */
422 ATF_TC_WITHOUT_HEAD(send_and_shutdown);
423 ATF_TC_BODY(send_and_shutdown, tc)
424 {
425 	int fd[2], putfd, nfiles;
426 
427 	domainsocketpair(fd);
428 	tempfile(&putfd);
429 	sendfd(fd[0], putfd);
430 	nfiles = openfiles();
431 	close(putfd);
432 	ATF_REQUIRE(openfiles() == nfiles);
433 	shutdown(fd[1], SHUT_RD);
434 	ATF_REQUIRE(openfiles() == nfiles - 1);
435 	closesocketpair(fd);
436 }
437 
438 /*
439  * Send maximum possible SCM_RIGHTS message.
440  * Internally the file descriptors are converted from integers to pointers
441  * and stored in a single mbuf cluster.  Check that we can not send too much
442  * and that we can successfully send maximum possible amount.  Check that we
443  * can not exploit getrlimit(3).
444  */
445 #define	MAXFDS	((MCLBYTES - _ALIGN(sizeof(struct cmsghdr)))/sizeof(void *))
446 ATF_TC_WITHOUT_HEAD(send_a_lot);
447 ATF_TC_BODY(send_a_lot, tc)
448 {
449 	struct msghdr msghdr;
450 	struct iovec iov;
451 	struct rlimit rlim;
452 	int fd[2], nfds;
453 	char *cmsg, ch;
454 
455 	domainsocketpair(fd);
456 	cmsg = malloc(CMSG_SPACE((MAXFDS + 1) * sizeof(int)));
457 	ATF_REQUIRE(cmsg != NULL);
458 	iov.iov_base = &ch;
459 	iov.iov_len = sizeof(ch);
460 	msghdr = (struct msghdr ){
461 		.msg_control = cmsg,
462 		.msg_controllen = CMSG_LEN((MAXFDS + 1) * sizeof(int)),
463 		.msg_iov = &iov,
464 		.msg_iovlen = 1,
465 	};
466 
467 	/* Sending too much fails. */
468 	putfds(cmsg, fd[0], MAXFDS + 1);
469 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == -1);
470 	ATF_REQUIRE(errno == EMSGSIZE);
471 
472 	/* Sending just the right amount works and everything is received. */
473 	putfds(cmsg, fd[0], MAXFDS);
474 	msghdr.msg_controllen = CMSG_LEN(MAXFDS * sizeof(int));
475 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == 1);
476 	nfds = getnfds();
477 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == 1);
478 	ATF_REQUIRE(getnfds() == (int)(nfds + MAXFDS));
479 
480 	/* Limit our process open files... */
481 	ATF_REQUIRE(getrlimit(RLIMIT_NOFILE, &rlim) == 0);
482 	nfds = rlim.rlim_cur = getnfds();
483 	ATF_REQUIRE(setrlimit(RLIMIT_NOFILE, &rlim) == 0);
484 
485 	/* ... and try to receive a single descriptor. */
486 	putfds(cmsg, fd[0], 1);
487 	msghdr.msg_controllen = CMSG_LEN(sizeof(int));
488 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == 1);
489 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == -1);
490 	/* Such attempt shall fail with EMFILE. */
491 	ATF_REQUIRE(errno == EMFILE);
492 	ATF_REQUIRE(getnfds() == nfds);
493 #if TEST_PROTO == SOCK_STREAM
494 	/*
495 	 * For the SOCK_STREAM the above attempt shall free the control in
496 	 * the kernel, so that socket isn't left in a stuck state.  Next read
497 	 * shall bring us the normal data only.  The stream data shall not
498 	 * miss a byte.
499 	 */
500 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == 1);
501 	ATF_REQUIRE(msghdr.msg_controllen == 0);
502 #elif TEST_PROTO == SOCK_DGRAM
503 	/*
504 	 * For SOCK_DGRAM there are two options for the previously failed
505 	 * syscall: strip the control leaving datagram in the socket or
506 	 * drop the whole datagram.  Our implementation drops the whole
507 	 * datagram.
508 	 */
509 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, MSG_DONTWAIT) == -1);
510 	ATF_REQUIRE(errno == EAGAIN);
511 #endif
512 }
513 
514 /*
515  * Exersize condition when SCM_RIGHTS is successfully internalized, but
516  * message delivery fails due to receive buffer overflow.  Check that no
517  * file descriptors are leaked.
518  */
519 ATF_TC_WITHOUT_HEAD(send_overflow);
520 ATF_TC_BODY(send_overflow, tc)
521 {
522 	void *buf;
523 	ssize_t len;
524 	int fd[2], putfd, nfiles;
525 	int sendspace;
526 
527 	sendspace = (int)getsendspace();
528 	ATF_REQUIRE((buf = malloc(sendspace)) != NULL);
529 
530 	domainsocketpair(fd);
531 	fill(fd[0]);
532 	nfiles = openfiles();
533 	tempfile(&putfd);
534 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
535 	ATF_REQUIRE_MSG(len == -1 && errno == EAGAIN,
536 	    "sendmsg: %zu bytes sent, errno %d", len, errno);
537 	close(putfd);
538 	ATF_REQUIRE(nfiles == openfiles());
539 	closesocketpair(fd);
540 }
541 
542 
543 /*
544  * Send two files.  Then receive them.  Make sure they are returned in the
545  * right order, and both get there.
546  */
547 ATF_TC_WITHOUT_HEAD(two_files);
548 ATF_TC_BODY(two_files, tc)
549 {
550 	struct stat getfd_1_stat, getfd_2_stat, putfd_1_stat, putfd_2_stat;
551 	int fd[2], getfd_1, getfd_2, putfd_1, putfd_2;
552 
553 	domainsocketpair(fd);
554 	tempfile(&putfd_1);
555 	tempfile(&putfd_2);
556 	dofstat(putfd_1, &putfd_1_stat);
557 	dofstat(putfd_2, &putfd_2_stat);
558 	sendfd(fd[0], putfd_1);
559 	sendfd(fd[0], putfd_2);
560 	close(putfd_1);
561 	close(putfd_2);
562 	recvfd(fd[1], &getfd_1, 0);
563 	recvfd(fd[1], &getfd_2, 0);
564 	dofstat(getfd_1, &getfd_1_stat);
565 	dofstat(getfd_2, &getfd_2_stat);
566 	samefile(&putfd_1_stat, &getfd_1_stat);
567 	samefile(&putfd_2_stat, &getfd_2_stat);
568 	close(getfd_1);
569 	close(getfd_2);
570 	closesocketpair(fd);
571 }
572 
573 /*
574  * Big bundling test.  Send an endpoint of the UNIX domain socket over itself,
575  * closing the door behind it.
576  */
577 ATF_TC_WITHOUT_HEAD(bundle);
578 ATF_TC_BODY(bundle, tc)
579 {
580 	int fd[2], getfd;
581 
582 	domainsocketpair(fd);
583 
584 	sendfd(fd[0], fd[0]);
585 	close(fd[0]);
586 	recvfd(fd[1], &getfd, 0);
587 	close(getfd);
588 	close(fd[1]);
589 }
590 
591 /*
592  * Big bundling test part two: Send an endpoint of the UNIX domain socket over
593  * itself, close the door behind it, and never remove it from the other end.
594  */
595 ATF_TC_WITHOUT_HEAD(bundle_cancel);
596 ATF_TC_BODY(bundle_cancel, tc)
597 {
598 	int fd[2];
599 
600 	domainsocketpair(fd);
601 	sendfd(fd[0], fd[0]);
602 	sendfd(fd[1], fd[0]);
603 	closesocketpair(fd);
604 }
605 
606 /*
607  * Test for PR 151758: Send an character device over the UNIX domain socket
608  * and then close both sockets to orphan the device.
609  */
610 ATF_TC_WITHOUT_HEAD(devfs_orphan);
611 ATF_TC_BODY(devfs_orphan, tc)
612 {
613 	int fd[2], putfd;
614 
615 	domainsocketpair(fd);
616 	devnull(&putfd);
617 	sendfd(fd[0], putfd);
618 	close(putfd);
619 	closesocketpair(fd);
620 }
621 
622 /*
623  * Test for PR 181741. Receiver sets LOCAL_CREDS, and kernel prepends a
624  * control message to the data. Sender sends large payload using a non-blocking
625  * socket. Payload + SCM_RIGHTS + LOCAL_CREDS hit socket buffer limit, and
626  * receiver receives truncated data.
627  */
628 ATF_TC_WITHOUT_HEAD(rights_creds_payload);
629 ATF_TC_BODY(rights_creds_payload, tc)
630 {
631 	const int on = 1;
632 	u_long sendspace;
633 	ssize_t len;
634 	void *buf;
635 	int fd[2], getfd, putfd, rc;
636 
637 	sendspace = getsendspace();
638 	buf = calloc(1, sendspace);
639 	ATF_REQUIRE(buf != NULL);
640 
641 	domainsocketpair(fd);
642 	tempfile(&putfd);
643 
644 	rc = fcntl(fd[0], F_SETFL, O_NONBLOCK);
645 	ATF_REQUIRE_MSG(rc != -1, "fcntl(O_NONBLOCK) failed: %s",
646 	    strerror(errno));
647 	rc = setsockopt(fd[1], 0, LOCAL_CREDS, &on, sizeof(on));
648 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(LOCAL_CREDS) failed: %s",
649 	    strerror(errno));
650 
651 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
652 #if TEST_PROTO == SOCK_STREAM
653 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
654 	ATF_REQUIRE_MSG((size_t)len < sendspace,
655 	    "sendmsg: %zu bytes sent", len);
656 	recvfd_payload(fd[1], &getfd, buf, len,
657 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
658 #endif
659 #if TEST_PROTO == SOCK_DGRAM
660 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
661 	ATF_REQUIRE_MSG((size_t)len == sendspace,
662 	    "sendmsg: %zu bytes sent", len);
663 	recvfd_payload(fd[1], &getfd, buf, len,
664 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
665 #endif
666 
667 	close(putfd);
668 	close(getfd);
669 	closesocketpair(fd);
670 }
671 
672 static void
673 send_cmsg(int sockfd, void *cmsg, size_t cmsgsz)
674 {
675 	struct iovec iov;
676 	struct msghdr msghdr;
677 	ssize_t len;
678 	char ch;
679 
680 	ch = 0;
681 	bzero(&msghdr, sizeof(msghdr));
682 
683 	iov.iov_base = &ch;
684 	iov.iov_len = sizeof(ch);
685 	msghdr.msg_control = cmsg;
686 	msghdr.msg_controllen = cmsgsz;
687 	msghdr.msg_iov = &iov;
688 	msghdr.msg_iovlen = 1;
689 
690 	len = sendmsg(sockfd, &msghdr, 0);
691 	ATF_REQUIRE_MSG(len != -1,
692 	    "sendmsg failed: %s", strerror(errno));
693 	ATF_REQUIRE_MSG(len == sizeof(ch),
694 	    "sendmsg: %zd bytes sent; expected %zu", len, sizeof(ch));
695 }
696 
697 static void
698 recv_cmsg(int sockfd, char *cmsg, size_t cmsgsz, int flags)
699 {
700 	struct iovec iov;
701 	struct msghdr msghdr;
702 	ssize_t len;
703 	char ch;
704 
705 	ch = 0;
706 	bzero(&msghdr, sizeof(msghdr));
707 
708 	iov.iov_base = &ch;
709 	iov.iov_len = sizeof(ch);
710 	msghdr.msg_control = cmsg;
711 	msghdr.msg_controllen = cmsgsz;
712 	msghdr.msg_iov = &iov;
713 	msghdr.msg_iovlen = 1;
714 
715 	len = recvmsg(sockfd, &msghdr, 0);
716 	ATF_REQUIRE_MSG(len != -1,
717 	    "recvmsg failed: %s", strerror(errno));
718 	ATF_REQUIRE_MSG(len == sizeof(ch),
719 	    "recvmsg: %zd bytes received; expected %zu", len, sizeof(ch));
720 	ATF_REQUIRE_MSG((msghdr.msg_flags & flags) == flags,
721 	    "recvmsg: got flags %#x; expected %#x", msghdr.msg_flags, flags);
722 }
723 
724 /*
725  * Test for PR 131876.  Receiver uses a control message buffer that is too
726  * small for the incoming SCM_RIGHTS message, so the message is truncated.
727  * The kernel must not leak the copied right into the receiver's namespace.
728  */
729 ATF_TC_WITHOUT_HEAD(truncated_rights);
730 ATF_TC_BODY(truncated_rights, tc)
731 {
732 	char *message;
733 	int fd[2], nfds, putfd, rc;
734 
735 	domainsocketpair(fd);
736 	devnull(&putfd);
737 	nfds = getnfds();
738 
739 	/*
740 	 * Case 1: Send a single descriptor and truncate the message.
741 	 */
742 	message = malloc(CMSG_SPACE(sizeof(int)));
743 	ATF_REQUIRE(message != NULL);
744 	putfds(message, putfd, 1);
745 	send_cmsg(fd[0], message, CMSG_LEN(sizeof(int)));
746 	recv_cmsg(fd[1], message, CMSG_LEN(0), MSG_CTRUNC);
747 	ATF_REQUIRE(getnfds() == nfds);
748 	free(message);
749 
750 	/*
751 	 * Case 2a: Send two descriptors in separate messages, and truncate at
752 	 *          the boundary between the two messages.  We should still
753 	 *          receive the first message.
754 	 */
755 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
756 	ATF_REQUIRE(message != NULL);
757 	putfds(message, putfd, 1);
758 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
759 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
760 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
761 	rc = close(*(int *)CMSG_DATA(message));
762 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
763 	ATF_REQUIRE(getnfds() == nfds);
764 	free(message);
765 
766 	/*
767 	 * Case 2b: Send two descriptors in separate messages, and truncate
768 	 *          before the end of the first message.
769 	 */
770 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
771 	ATF_REQUIRE(message != NULL);
772 	putfds(message, putfd, 1);
773 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
774 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
775 	recv_cmsg(fd[1], message, CMSG_SPACE(0), MSG_CTRUNC);
776 	ATF_REQUIRE(getnfds() == nfds);
777 	free(message);
778 
779 	/*
780 	 * Case 2c: Send two descriptors in separate messages, and truncate
781 	 *          after the end of the first message.  We should still
782 	 *          receive the first message.
783 	 */
784 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
785 	ATF_REQUIRE(message != NULL);
786 	putfds(message, putfd, 1);
787 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
788 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
789 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)) + CMSG_SPACE(0),
790 	    MSG_CTRUNC);
791 	rc = close(*(int *)CMSG_DATA(message));
792 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
793 	ATF_REQUIRE(getnfds() == nfds);
794 	free(message);
795 
796 	/*
797 	 * Case 3: Send three descriptors in the same message, and leave space
798 	 *         only for the first when receiving the message.
799 	 */
800 	message = malloc(CMSG_SPACE(sizeof(int) * 3));
801 	ATF_REQUIRE(message != NULL);
802 	putfds(message, putfd, 3);
803 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int) * 3));
804 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
805 	ATF_REQUIRE(getnfds() == nfds);
806 	free(message);
807 
808 	close(putfd);
809 	closesocketpair(fd);
810 }
811 
812 /*
813  * Ensure that an attempt to copy a SCM_RIGHTS message to the recipient
814  * fails.  In this case the kernel must dispose of the externalized rights
815  * rather than leaking them into the recipient's file descriptor table.
816  */
817 ATF_TC_WITHOUT_HEAD(copyout_rights_error);
818 ATF_TC_BODY(copyout_rights_error, tc)
819 {
820 	struct iovec iovec;
821 	struct msghdr msghdr;
822 	char buf[16];
823 	ssize_t len;
824 	int fd[2], error, nfds, putfd;
825 
826 	memset(buf, 0, sizeof(buf));
827 	domainsocketpair(fd);
828 	devnull(&putfd);
829 	nfds = getnfds();
830 
831 	len = sendfd_payload(fd[0], putfd, buf, sizeof(buf));
832 	ATF_REQUIRE_MSG(len != -1, "sendmsg failed: %s", strerror(errno));
833 
834 	bzero(&msghdr, sizeof(msghdr));
835 
836 	iovec.iov_base = buf;
837 	iovec.iov_len = sizeof(buf);
838 	msghdr.msg_control = (char *)-1; /* trigger EFAULT */
839 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
840 	msghdr.msg_iov = &iovec;
841 	msghdr.msg_iovlen = 1;
842 
843 	len = recvmsg(fd[1], &msghdr, 0);
844 	error = errno;
845 	ATF_REQUIRE_MSG(len == -1, "recvmsg succeeded: %zd", len);
846 	ATF_REQUIRE_MSG(errno == EFAULT, "expected EFAULT, got %d (%s)",
847 	    error, strerror(errno));
848 
849 	/* Verify that no FDs were leaked. */
850 	ATF_REQUIRE(getnfds() == nfds);
851 
852 	close(putfd);
853 	closesocketpair(fd);
854 }
855 
856 /*
857  * Verify that we can handle empty rights messages.
858  */
859 ATF_TC_WITHOUT_HEAD(empty_rights_message);
860 ATF_TC_BODY(empty_rights_message, tc)
861 {
862 	struct iovec iov;
863 	struct msghdr msghdr;
864 	struct cmsghdr cmsg;
865 	char *cm, message[CMSG_SPACE(0) + CMSG_SPACE(sizeof(int))];
866 	ssize_t len;
867 	int error, fd[2], putfd;
868 
869 	domainsocketpair(fd);
870 	devnull(&putfd);
871 
872 	memset(&msghdr, 0, sizeof(msghdr));
873 	iov.iov_base = NULL;
874 	iov.iov_len = 0;
875 	msghdr.msg_iov = &iov;
876 	msghdr.msg_iovlen = 1;
877 
878 	/*
879 	 * Try sending incorrect empty message.  On 64-bit platforms, where
880 	 * CMSG_SPACE(0) > sizeof(struct cmsghdr), this will exercise
881 	 * an edge case.
882 	 */
883 	cmsg = (struct cmsghdr ){
884 	    .cmsg_len = sizeof(struct cmsghdr),	/* not CMSG_LEN(0)! */
885 	    .cmsg_level = SOL_SOCKET,
886 	    .cmsg_type = SCM_RIGHTS,
887 	};
888 	msghdr.msg_control = &cmsg;
889 	msghdr.msg_controllen = CMSG_SPACE(0);
890 
891 	len = sendmsg(fd[0], &msghdr, 0);
892 	if (CMSG_LEN(0) != sizeof(struct cmsghdr))
893 		ATF_REQUIRE(len == -1 && errno == EINVAL);
894 	else
895 		ATF_REQUIRE(len == 0);
896 
897 	/*
898 	 * Try sending an empty message followed by a non-empty message.
899 	 */
900 	cm = message;
901 	putfds(cm, -1, 0);
902 	cm += CMSG_SPACE(0);
903 	putfds(cm, putfd, 1);
904 	msghdr.msg_control = message;
905 	msghdr.msg_controllen = sizeof(message);
906 
907 	len = sendmsg(fd[0], &msghdr, 0);
908 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
909 
910 	/* Only the non-empty message should be received. */
911 	len = recvmsg(fd[1], &msghdr, 0);
912 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
913 	ATF_REQUIRE(msghdr.msg_controllen = CMSG_SPACE(sizeof(int)));
914 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
915 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
916 
917 	/*
918 	 * Now try sending with the non-empty message before the empty message.
919 	 */
920 	cm = message;
921 	putfds(cm, putfd, 1);
922 	cm += CMSG_SPACE(sizeof(int));
923 	putfds(cm, -1, 0);
924 
925 	memset(&msghdr, 0, sizeof(msghdr));
926 	iov.iov_base = NULL;
927 	iov.iov_len = 0;
928 	msghdr.msg_control = message;
929 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
930 	msghdr.msg_iov = &iov;
931 	msghdr.msg_iovlen = 1;
932 
933 	len = sendmsg(fd[0], &msghdr, 0);
934 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
935 
936 	/* Only the non-empty message should be received. */
937 	len = recvmsg(fd[1], &msghdr, 0);
938 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
939 	ATF_REQUIRE(msghdr.msg_controllen = CMSG_SPACE(sizeof(int)));
940 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
941 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
942 
943 	(void)close(putfd);
944 }
945 
946 ATF_TP_ADD_TCS(tp)
947 {
948 
949 	ATF_TP_ADD_TC(tp, simple_send_fd);
950 	ATF_TP_ADD_TC(tp, simple_send_fd_msg_cmsg_cloexec);
951 	ATF_TP_ADD_TC(tp, send_and_close);
952 	ATF_TP_ADD_TC(tp, send_and_cancel);
953 	ATF_TP_ADD_TC(tp, send_and_shutdown);
954 	ATF_TP_ADD_TC(tp, send_a_lot);
955 	ATF_TP_ADD_TC(tp, send_overflow);
956 	ATF_TP_ADD_TC(tp, two_files);
957 	ATF_TP_ADD_TC(tp, bundle);
958 	ATF_TP_ADD_TC(tp, bundle_cancel);
959 	ATF_TP_ADD_TC(tp, devfs_orphan);
960 	ATF_TP_ADD_TC(tp, rights_creds_payload);
961 	ATF_TP_ADD_TC(tp, truncated_rights);
962 	ATF_TP_ADD_TC(tp, copyout_rights_error);
963 	ATF_TP_ADD_TC(tp, empty_rights_message);
964 
965 	return (atf_no_error());
966 }
967