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