xref: /freebsd/tests/sys/kern/unix_passfd_test.c (revision 3e5d0784b9b5296bda801add034b057ad68237f7)
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 #if TEST_PROTO == SOCK_STREAM
536 	ATF_REQUIRE_MSG(len == -1 && errno == EAGAIN,
537 	    "sendmsg: %zu bytes sent, errno %d", len, errno);
538 #elif TEST_PROTO == SOCK_DGRAM
539 	ATF_REQUIRE_MSG(len == -1 && errno == ENOBUFS,
540 	    "sendmsg: %zu bytes sent, errno %d", len, errno);
541 #endif
542 	close(putfd);
543 	ATF_REQUIRE(nfiles == openfiles());
544 	closesocketpair(fd);
545 }
546 
547 
548 /*
549  * Send two files.  Then receive them.  Make sure they are returned in the
550  * right order, and both get there.
551  */
552 ATF_TC_WITHOUT_HEAD(two_files);
553 ATF_TC_BODY(two_files, tc)
554 {
555 	struct stat getfd_1_stat, getfd_2_stat, putfd_1_stat, putfd_2_stat;
556 	int fd[2], getfd_1, getfd_2, putfd_1, putfd_2;
557 
558 	domainsocketpair(fd);
559 	tempfile(&putfd_1);
560 	tempfile(&putfd_2);
561 	dofstat(putfd_1, &putfd_1_stat);
562 	dofstat(putfd_2, &putfd_2_stat);
563 	sendfd(fd[0], putfd_1);
564 	sendfd(fd[0], putfd_2);
565 	close(putfd_1);
566 	close(putfd_2);
567 	recvfd(fd[1], &getfd_1, 0);
568 	recvfd(fd[1], &getfd_2, 0);
569 	dofstat(getfd_1, &getfd_1_stat);
570 	dofstat(getfd_2, &getfd_2_stat);
571 	samefile(&putfd_1_stat, &getfd_1_stat);
572 	samefile(&putfd_2_stat, &getfd_2_stat);
573 	close(getfd_1);
574 	close(getfd_2);
575 	closesocketpair(fd);
576 }
577 
578 /*
579  * Big bundling test.  Send an endpoint of the UNIX domain socket over itself,
580  * closing the door behind it.
581  */
582 ATF_TC_WITHOUT_HEAD(bundle);
583 ATF_TC_BODY(bundle, tc)
584 {
585 	int fd[2], getfd;
586 
587 	domainsocketpair(fd);
588 
589 	sendfd(fd[0], fd[0]);
590 	close(fd[0]);
591 	recvfd(fd[1], &getfd, 0);
592 	close(getfd);
593 	close(fd[1]);
594 }
595 
596 /*
597  * Big bundling test part two: Send an endpoint of the UNIX domain socket over
598  * itself, close the door behind it, and never remove it from the other end.
599  */
600 ATF_TC_WITHOUT_HEAD(bundle_cancel);
601 ATF_TC_BODY(bundle_cancel, tc)
602 {
603 	int fd[2];
604 
605 	domainsocketpair(fd);
606 	sendfd(fd[0], fd[0]);
607 	sendfd(fd[1], fd[0]);
608 	closesocketpair(fd);
609 }
610 
611 /*
612  * Test for PR 151758: Send an character device over the UNIX domain socket
613  * and then close both sockets to orphan the device.
614  */
615 ATF_TC_WITHOUT_HEAD(devfs_orphan);
616 ATF_TC_BODY(devfs_orphan, tc)
617 {
618 	int fd[2], putfd;
619 
620 	domainsocketpair(fd);
621 	devnull(&putfd);
622 	sendfd(fd[0], putfd);
623 	close(putfd);
624 	closesocketpair(fd);
625 }
626 
627 /*
628  * Test for PR 181741. Receiver sets LOCAL_CREDS, and kernel prepends a
629  * control message to the data. Sender sends large payload using a non-blocking
630  * socket. Payload + SCM_RIGHTS + LOCAL_CREDS hit socket buffer limit, and
631  * receiver receives truncated data.
632  */
633 ATF_TC_WITHOUT_HEAD(rights_creds_payload);
634 ATF_TC_BODY(rights_creds_payload, tc)
635 {
636 	const int on = 1;
637 	u_long sendspace;
638 	ssize_t len;
639 	void *buf;
640 	int fd[2], getfd, putfd, rc;
641 
642 	sendspace = getsendspace();
643 	buf = calloc(1, sendspace);
644 	ATF_REQUIRE(buf != NULL);
645 
646 	domainsocketpair(fd);
647 	tempfile(&putfd);
648 
649 	rc = fcntl(fd[0], F_SETFL, O_NONBLOCK);
650 	ATF_REQUIRE_MSG(rc != -1, "fcntl(O_NONBLOCK) failed: %s",
651 	    strerror(errno));
652 	rc = setsockopt(fd[1], 0, LOCAL_CREDS, &on, sizeof(on));
653 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(LOCAL_CREDS) failed: %s",
654 	    strerror(errno));
655 
656 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
657 #if TEST_PROTO == SOCK_STREAM
658 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
659 	ATF_REQUIRE_MSG((size_t)len < sendspace,
660 	    "sendmsg: %zu bytes sent", len);
661 	recvfd_payload(fd[1], &getfd, buf, len,
662 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
663 #endif
664 #if TEST_PROTO == SOCK_DGRAM
665 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
666 	ATF_REQUIRE_MSG((size_t)len == sendspace,
667 	    "sendmsg: %zu bytes sent", len);
668 	recvfd_payload(fd[1], &getfd, buf, len,
669 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
670 #endif
671 
672 	close(putfd);
673 	close(getfd);
674 	closesocketpair(fd);
675 }
676 
677 static void
678 send_cmsg(int sockfd, void *cmsg, size_t cmsgsz)
679 {
680 	struct iovec iov;
681 	struct msghdr msghdr;
682 	ssize_t len;
683 	char ch;
684 
685 	ch = 0;
686 	bzero(&msghdr, sizeof(msghdr));
687 
688 	iov.iov_base = &ch;
689 	iov.iov_len = sizeof(ch);
690 	msghdr.msg_control = cmsg;
691 	msghdr.msg_controllen = cmsgsz;
692 	msghdr.msg_iov = &iov;
693 	msghdr.msg_iovlen = 1;
694 
695 	len = sendmsg(sockfd, &msghdr, 0);
696 	ATF_REQUIRE_MSG(len != -1,
697 	    "sendmsg failed: %s", strerror(errno));
698 	ATF_REQUIRE_MSG(len == sizeof(ch),
699 	    "sendmsg: %zd bytes sent; expected %zu", len, sizeof(ch));
700 }
701 
702 static void
703 recv_cmsg(int sockfd, char *cmsg, size_t cmsgsz, int flags)
704 {
705 	struct iovec iov;
706 	struct msghdr msghdr;
707 	ssize_t len;
708 	char ch;
709 
710 	ch = 0;
711 	bzero(&msghdr, sizeof(msghdr));
712 
713 	iov.iov_base = &ch;
714 	iov.iov_len = sizeof(ch);
715 	msghdr.msg_control = cmsg;
716 	msghdr.msg_controllen = cmsgsz;
717 	msghdr.msg_iov = &iov;
718 	msghdr.msg_iovlen = 1;
719 
720 	len = recvmsg(sockfd, &msghdr, 0);
721 	ATF_REQUIRE_MSG(len != -1,
722 	    "recvmsg failed: %s", strerror(errno));
723 	ATF_REQUIRE_MSG(len == sizeof(ch),
724 	    "recvmsg: %zd bytes received; expected %zu", len, sizeof(ch));
725 	ATF_REQUIRE_MSG((msghdr.msg_flags & flags) == flags,
726 	    "recvmsg: got flags %#x; expected %#x", msghdr.msg_flags, flags);
727 }
728 
729 /*
730  * Test for PR 131876.  Receiver uses a control message buffer that is too
731  * small for the incoming SCM_RIGHTS message, so the message is truncated.
732  * The kernel must not leak the copied right into the receiver's namespace.
733  */
734 ATF_TC_WITHOUT_HEAD(truncated_rights);
735 ATF_TC_BODY(truncated_rights, tc)
736 {
737 	char *message;
738 	int fd[2], nfds, putfd, rc;
739 
740 	domainsocketpair(fd);
741 	devnull(&putfd);
742 	nfds = getnfds();
743 
744 	/*
745 	 * Case 1: Send a single descriptor and truncate the message.
746 	 */
747 	message = malloc(CMSG_SPACE(sizeof(int)));
748 	ATF_REQUIRE(message != NULL);
749 	putfds(message, putfd, 1);
750 	send_cmsg(fd[0], message, CMSG_LEN(sizeof(int)));
751 	recv_cmsg(fd[1], message, CMSG_LEN(0), MSG_CTRUNC);
752 	ATF_REQUIRE(getnfds() == nfds);
753 	free(message);
754 
755 	/*
756 	 * Case 2a: Send two descriptors in separate messages, and truncate at
757 	 *          the boundary between the two messages.  We should still
758 	 *          receive the first message.
759 	 */
760 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
761 	ATF_REQUIRE(message != NULL);
762 	putfds(message, putfd, 1);
763 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
764 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
765 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
766 	rc = close(*(int *)CMSG_DATA(message));
767 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
768 	ATF_REQUIRE(getnfds() == nfds);
769 	free(message);
770 
771 	/*
772 	 * Case 2b: Send two descriptors in separate messages, and truncate
773 	 *          before the end of the first message.
774 	 */
775 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
776 	ATF_REQUIRE(message != NULL);
777 	putfds(message, putfd, 1);
778 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
779 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
780 	recv_cmsg(fd[1], message, CMSG_SPACE(0), MSG_CTRUNC);
781 	ATF_REQUIRE(getnfds() == nfds);
782 	free(message);
783 
784 	/*
785 	 * Case 2c: Send two descriptors in separate messages, and truncate
786 	 *          after the end of the first message.  We should still
787 	 *          receive the first message.
788 	 */
789 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
790 	ATF_REQUIRE(message != NULL);
791 	putfds(message, putfd, 1);
792 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
793 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
794 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)) + CMSG_SPACE(0),
795 	    MSG_CTRUNC);
796 	rc = close(*(int *)CMSG_DATA(message));
797 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
798 	ATF_REQUIRE(getnfds() == nfds);
799 	free(message);
800 
801 	/*
802 	 * Case 3: Send three descriptors in the same message, and leave space
803 	 *         only for the first when receiving the message.
804 	 */
805 	message = malloc(CMSG_SPACE(sizeof(int) * 3));
806 	ATF_REQUIRE(message != NULL);
807 	putfds(message, putfd, 3);
808 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int) * 3));
809 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
810 	ATF_REQUIRE(getnfds() == nfds);
811 	free(message);
812 
813 	close(putfd);
814 	closesocketpair(fd);
815 }
816 
817 /*
818  * Ensure that an attempt to copy a SCM_RIGHTS message to the recipient
819  * fails.  In this case the kernel must dispose of the externalized rights
820  * rather than leaking them into the recipient's file descriptor table.
821  */
822 ATF_TC_WITHOUT_HEAD(copyout_rights_error);
823 ATF_TC_BODY(copyout_rights_error, tc)
824 {
825 	struct iovec iovec;
826 	struct msghdr msghdr;
827 	char buf[16];
828 	ssize_t len;
829 	int fd[2], error, nfds, putfd;
830 
831 	memset(buf, 0, sizeof(buf));
832 	domainsocketpair(fd);
833 	devnull(&putfd);
834 	nfds = getnfds();
835 
836 	len = sendfd_payload(fd[0], putfd, buf, sizeof(buf));
837 	ATF_REQUIRE_MSG(len != -1, "sendmsg failed: %s", strerror(errno));
838 
839 	bzero(&msghdr, sizeof(msghdr));
840 
841 	iovec.iov_base = buf;
842 	iovec.iov_len = sizeof(buf);
843 	msghdr.msg_control = (char *)-1; /* trigger EFAULT */
844 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
845 	msghdr.msg_iov = &iovec;
846 	msghdr.msg_iovlen = 1;
847 
848 	len = recvmsg(fd[1], &msghdr, 0);
849 	error = errno;
850 	ATF_REQUIRE_MSG(len == -1, "recvmsg succeeded: %zd", len);
851 	ATF_REQUIRE_MSG(errno == EFAULT, "expected EFAULT, got %d (%s)",
852 	    error, strerror(errno));
853 
854 	/* Verify that no FDs were leaked. */
855 	ATF_REQUIRE(getnfds() == nfds);
856 
857 	close(putfd);
858 	closesocketpair(fd);
859 }
860 
861 /*
862  * Verify that we can handle empty rights messages.
863  */
864 ATF_TC_WITHOUT_HEAD(empty_rights_message);
865 ATF_TC_BODY(empty_rights_message, tc)
866 {
867 	struct iovec iov;
868 	struct msghdr msghdr;
869 	struct cmsghdr cmsg;
870 	char *cm, message[CMSG_SPACE(0) + CMSG_SPACE(sizeof(int))];
871 	ssize_t len;
872 	int error, fd[2], putfd;
873 
874 	domainsocketpair(fd);
875 	devnull(&putfd);
876 
877 	memset(&msghdr, 0, sizeof(msghdr));
878 	iov.iov_base = NULL;
879 	iov.iov_len = 0;
880 	msghdr.msg_iov = &iov;
881 	msghdr.msg_iovlen = 1;
882 
883 	/*
884 	 * Try sending incorrect empty message.  On 64-bit platforms, where
885 	 * CMSG_SPACE(0) > sizeof(struct cmsghdr), this will exercise
886 	 * an edge case.
887 	 */
888 	cmsg = (struct cmsghdr ){
889 	    .cmsg_len = sizeof(struct cmsghdr),	/* not CMSG_LEN(0)! */
890 	    .cmsg_level = SOL_SOCKET,
891 	    .cmsg_type = SCM_RIGHTS,
892 	};
893 	msghdr.msg_control = &cmsg;
894 	msghdr.msg_controllen = CMSG_SPACE(0);
895 
896 	len = sendmsg(fd[0], &msghdr, 0);
897 	if (CMSG_LEN(0) != sizeof(struct cmsghdr))
898 		ATF_REQUIRE(len == -1 && errno == EINVAL);
899 	else
900 		ATF_REQUIRE(len == 0);
901 
902 	/*
903 	 * Try sending an empty message followed by a non-empty message.
904 	 */
905 	cm = message;
906 	putfds(cm, -1, 0);
907 	cm += CMSG_SPACE(0);
908 	putfds(cm, putfd, 1);
909 	msghdr.msg_control = message;
910 	msghdr.msg_controllen = sizeof(message);
911 
912 	len = sendmsg(fd[0], &msghdr, 0);
913 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
914 
915 	/* Only the non-empty message should be received. */
916 	len = recvmsg(fd[1], &msghdr, 0);
917 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
918 	ATF_REQUIRE(msghdr.msg_controllen = CMSG_SPACE(sizeof(int)));
919 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
920 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
921 
922 	/*
923 	 * Now try sending with the non-empty message before the empty message.
924 	 */
925 	cm = message;
926 	putfds(cm, putfd, 1);
927 	cm += CMSG_SPACE(sizeof(int));
928 	putfds(cm, -1, 0);
929 
930 	memset(&msghdr, 0, sizeof(msghdr));
931 	iov.iov_base = NULL;
932 	iov.iov_len = 0;
933 	msghdr.msg_control = message;
934 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
935 	msghdr.msg_iov = &iov;
936 	msghdr.msg_iovlen = 1;
937 
938 	len = sendmsg(fd[0], &msghdr, 0);
939 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
940 
941 	/* Only the non-empty message should be received. */
942 	len = recvmsg(fd[1], &msghdr, 0);
943 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
944 	ATF_REQUIRE(msghdr.msg_controllen = CMSG_SPACE(sizeof(int)));
945 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
946 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
947 
948 	(void)close(putfd);
949 }
950 
951 ATF_TP_ADD_TCS(tp)
952 {
953 
954 	ATF_TP_ADD_TC(tp, simple_send_fd);
955 	ATF_TP_ADD_TC(tp, simple_send_fd_msg_cmsg_cloexec);
956 	ATF_TP_ADD_TC(tp, send_and_close);
957 	ATF_TP_ADD_TC(tp, send_and_cancel);
958 	ATF_TP_ADD_TC(tp, send_and_shutdown);
959 	ATF_TP_ADD_TC(tp, send_a_lot);
960 	ATF_TP_ADD_TC(tp, send_overflow);
961 	ATF_TP_ADD_TC(tp, two_files);
962 	ATF_TP_ADD_TC(tp, bundle);
963 	ATF_TP_ADD_TC(tp, bundle_cancel);
964 	ATF_TP_ADD_TC(tp, devfs_orphan);
965 	ATF_TP_ADD_TC(tp, rights_creds_payload);
966 	ATF_TP_ADD_TC(tp, truncated_rights);
967 	ATF_TP_ADD_TC(tp, copyout_rights_error);
968 	ATF_TP_ADD_TC(tp, empty_rights_message);
969 
970 	return (atf_no_error());
971 }
972