xref: /freebsd/tests/sys/kern/unix_passfd_test.c (revision c08a86e0c6d989c926c2777c978155dde7d0697a)
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/jail.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/sysctl.h>
34 #include <sys/time.h>
35 #include <sys/resource.h>
36 #include <sys/un.h>
37 #include <sys/wait.h>
38 
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <jail.h>
43 #include <limits.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #include <atf-c.h>
50 
51 #if !defined(TEST_PROTO)
52 #error Need TEST_PROTO defined to SOCK_STREAM or SOCK_DGRAM
53 #endif
54 
55 /*
56  * UNIX domain sockets allow file descriptors to be passed via "ancillary
57  * data", or control messages.  This regression test is intended to exercise
58  * this facility, both performing some basic tests that it operates, and also
59  * causing some kernel edge cases to execute, such as garbage collection when
60  * there are cyclic file descriptor references.  Right now we test only with
61  * stream sockets, but ideally we'd also test with datagram sockets.
62  */
63 
64 static void
65 domainsocketpair(int *fdp)
66 {
67 
68 	ATF_REQUIRE_MSG(socketpair(PF_UNIX, TEST_PROTO, 0, fdp) != -1,
69 	    "socketpair(PF_UNIX, %u) failed: %s", TEST_PROTO, strerror(errno));
70 }
71 
72 static void
73 closesocketpair(int *fdp)
74 {
75 
76 	close(fdp[0]);
77 	close(fdp[1]);
78 }
79 
80 static void
81 devnull(int *fdp)
82 {
83 	int fd;
84 
85 	fd = open("/dev/null", O_RDONLY);
86 	ATF_REQUIRE_MSG(fd != -1, "open failed: %s", strerror(errno));
87 	*fdp = fd;
88 }
89 
90 static void
91 tempfile(int *fdp)
92 {
93 	char path[PATH_MAX];
94 	int fd;
95 
96 	snprintf(path, PATH_MAX, "%s/unix_passfd.XXXXXXXXXXXXXXX",
97 	    getenv("TMPDIR") == NULL ? "/tmp" : getenv("TMPDIR"));
98 	fd = mkstemp(path);
99 	ATF_REQUIRE_MSG(fd != -1, "mkstemp(%s) failed", path);
100 	(void)unlink(path);
101 	*fdp = fd;
102 }
103 
104 static void
105 dofstat(int fd, struct stat *sb)
106 {
107 
108 	ATF_REQUIRE_MSG(fstat(fd, sb) == 0,
109 	    "fstat failed: %s", strerror(errno));
110 }
111 
112 static int
113 getnfds(void)
114 {
115 	size_t len;
116 	int mib[4], n, rc;
117 
118 	len = sizeof(n);
119 	mib[0] = CTL_KERN;
120 	mib[1] = KERN_PROC;
121 	mib[2] = KERN_PROC_NFDS;
122 	mib[3] = 0;
123 
124 	rc = sysctl(mib, 4, &n, &len, NULL, 0);
125 	ATF_REQUIRE_MSG(rc != -1, "sysctl(KERN_PROC_NFDS) failed");
126 	return (n);
127 }
128 
129 static int
130 openfiles(void)
131 {
132 	int files;
133 	size_t len = sizeof(files);
134 
135 	ATF_REQUIRE(sysctlbyname("kern.openfiles", &files, &len, NULL, 0) == 0);
136 
137 	return (files);
138 }
139 
140 static void
141 putfds(char *buf, int fd, int nfds)
142 {
143 	struct cmsghdr *cm;
144 	int *fdp, i;
145 
146 	cm = (struct cmsghdr *)buf;
147 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
148 	cm->cmsg_level = SOL_SOCKET;
149 	cm->cmsg_type = SCM_RIGHTS;
150 	for (fdp = (int *)CMSG_DATA(cm), i = 0; i < nfds; i++)
151 		*fdp++ = fd;
152 }
153 
154 static void
155 samefile(struct stat *sb1, struct stat *sb2)
156 {
157 
158 	ATF_REQUIRE_MSG(sb1->st_dev == sb2->st_dev, "different device");
159 	ATF_REQUIRE_MSG(sb1->st_ino == sb2->st_ino, "different inode");
160 }
161 
162 static ssize_t
163 sendfd_payload(int sockfd, int send_fd, void *payload, size_t paylen)
164 {
165 	struct iovec iovec;
166 	char message[CMSG_SPACE(sizeof(int))];
167 	struct msghdr msghdr;
168 
169 	bzero(&msghdr, sizeof(msghdr));
170 	bzero(&message, sizeof(message));
171 
172 	msghdr.msg_control = message;
173 	msghdr.msg_controllen = sizeof(message);
174 
175 	iovec.iov_base = payload;
176 	iovec.iov_len = paylen;
177 
178 	msghdr.msg_iov = &iovec;
179 	msghdr.msg_iovlen = 1;
180 
181 	putfds(message, send_fd, 1);
182 	return (sendmsg(sockfd, &msghdr, 0));
183 }
184 
185 static void
186 sendfd(int sockfd, int send_fd)
187 {
188 	ssize_t len;
189 	char ch;
190 
191 	ch = 0;
192 	len = sendfd_payload(sockfd, send_fd, &ch, sizeof(ch));
193 	ATF_REQUIRE_MSG(len == sizeof(ch),
194 	    "sendmsg: %zd bytes sent; expected %zu; %s", len, sizeof(ch),
195 	    strerror(errno));
196 }
197 
198 static bool
199 localcreds(int sockfd)
200 {
201 	socklen_t sz;
202 	int rc, val;
203 
204 	sz = sizeof(val);
205 	rc = getsockopt(sockfd, 0, LOCAL_CREDS, &val, &sz);
206 	ATF_REQUIRE_MSG(rc != -1, "getsockopt(LOCAL_CREDS) failed: %s",
207 	    strerror(errno));
208 	return (val != 0);
209 }
210 
211 static bool
212 passrights(int sockfd)
213 {
214 	socklen_t sz;
215 	int rc, val;
216 
217 	sz = sizeof(val);
218 	rc = getsockopt(sockfd, SOL_SOCKET, SO_PASSRIGHTS, &val, &sz);
219 	ATF_REQUIRE_MSG(rc != -1, "getsockopt(SO_PASSRIGHTS) failed: %s",
220 	    strerror(errno));
221 	return (val != 0);
222 }
223 
224 static ssize_t
225 recvfd_payload_cmsg(int sockfd, void *buf, size_t buflen, struct msghdr *msghdr,
226     int recvmsg_flags)
227 {
228 	struct iovec iovec;
229 
230 	iovec.iov_base = buf;
231 	iovec.iov_len = buflen;
232 
233 	msghdr->msg_iov = &iovec;
234 	msghdr->msg_iovlen = 1;
235 
236 	return (recvmsg(sockfd, msghdr, recvmsg_flags));
237 }
238 
239 static ssize_t
240 recvfd_payload(int sockfd, int *recv_fd, void *buf, size_t buflen,
241     size_t cmsgsz, int recvmsg_flags)
242 {
243 	struct cmsghdr *cmsghdr;
244 	struct msghdr msghdr;
245 	char *message;
246 	ssize_t len;
247 	bool foundcreds;
248 
249 	bzero(&msghdr, sizeof(msghdr));
250 	message = malloc(cmsgsz);
251 	ATF_REQUIRE(message != NULL);
252 
253 	msghdr.msg_control = message;
254 	msghdr.msg_controllen = cmsgsz;
255 
256 	len = recvfd_payload_cmsg(sockfd, buf, buflen, &msghdr, recvmsg_flags);
257 	ATF_REQUIRE_MSG(len != -1, "recvmsg failed: %s", strerror(errno));
258 
259 	cmsghdr = CMSG_FIRSTHDR(&msghdr);
260 	ATF_REQUIRE_MSG(cmsghdr != NULL,
261 	    "recvmsg: did not receive control message");
262 	foundcreds = false;
263 	*recv_fd = -1;
264 	for (; cmsghdr != NULL; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) {
265 		if (cmsghdr->cmsg_level == SOL_SOCKET &&
266 		    cmsghdr->cmsg_type == SCM_RIGHTS &&
267 		    cmsghdr->cmsg_len == CMSG_LEN(sizeof(int))) {
268 			memcpy(recv_fd, CMSG_DATA(cmsghdr), sizeof(int));
269 			ATF_REQUIRE(*recv_fd != -1);
270 		} else if (cmsghdr->cmsg_level == SOL_SOCKET &&
271 		    cmsghdr->cmsg_type == SCM_CREDS)
272 			foundcreds = true;
273 	}
274 	ATF_REQUIRE_MSG(*recv_fd != -1,
275 	    "recvmsg: did not receive single-fd message");
276 	ATF_REQUIRE_MSG(!localcreds(sockfd) || foundcreds,
277 	    "recvmsg: expected credentials were not received");
278 	ATF_REQUIRE_MSG((msghdr.msg_flags & MSG_TRUNC) == 0,
279 	    "recvmsg: MSG_TRUNC is set while buffer is sufficient");
280 
281 	return (len);
282 }
283 
284 static void
285 recvfd(int sockfd, int *recv_fd, int flags)
286 {
287 	ssize_t len;
288 	char ch = 0;
289 
290 	len = recvfd_payload(sockfd, recv_fd, &ch, sizeof(ch),
291 	    CMSG_SPACE(sizeof(int)), flags);
292 	ATF_REQUIRE_MSG((size_t)len == sizeof(ch),
293 	    "recvmsg: %zd bytes received; expected %zd", len, sizeof(ch));
294 }
295 
296 #if TEST_PROTO == SOCK_STREAM
297 #define	LOCAL_SENDSPACE_SYSCTL	"net.local.stream.sendspace"
298 #define	LOCAL_RECVSPACE_SYSCTL	"net.local.stream.recvspace"
299 #elif TEST_PROTO == SOCK_DGRAM
300 #define	LOCAL_SENDSPACE_SYSCTL	"net.local.dgram.maxdgram"
301 #define	LOCAL_RECVSPACE_SYSCTL	"net.local.dgram.recvspace"
302 #endif
303 
304 static u_long
305 getsendspace(void)
306 {
307 	u_long sendspace;
308 
309 	ATF_REQUIRE_MSG(sysctlbyname(LOCAL_SENDSPACE_SYSCTL, &sendspace,
310             &(size_t){sizeof(u_long)}, NULL, 0) != -1,
311 	    "sysctl %s failed: %s", LOCAL_SENDSPACE_SYSCTL, strerror(errno));
312 
313 	return (sendspace);
314 }
315 
316 static u_long
317 getrecvspace(void)
318 {
319 	u_long recvspace;
320 
321 	ATF_REQUIRE_MSG(sysctlbyname(LOCAL_RECVSPACE_SYSCTL, &recvspace,
322             &(size_t){sizeof(u_long)}, NULL, 0) != -1,
323 	    "sysctl %s failed: %s", LOCAL_RECVSPACE_SYSCTL, strerror(errno));
324 
325 	return (recvspace);
326 }
327 
328 /*
329  * Fill socket to a state when next max sized send would fail with EAGAIN.
330  */
331 static void
332 fill(int fd)
333 {
334 	u_long sendspace;
335 	void *buf;
336 
337 	sendspace = getsendspace();
338 	ATF_REQUIRE((buf = malloc(sendspace)) != NULL);
339 
340 	ATF_REQUIRE_MSG(fcntl(fd, F_SETFL, O_NONBLOCK) != -1,
341 	    "fcntl(O_NONBLOCK) failed: %s", strerror(errno));
342 
343 #if TEST_PROTO == SOCK_STREAM
344 	do {} while (send(fd, buf, sendspace, 0) == (ssize_t)sendspace);
345 #elif TEST_PROTO == SOCK_DGRAM
346 	u_long recvspace = getrecvspace();
347 
348 	for (ssize_t sent = 0;
349 	    sent + sendspace + sizeof(struct sockaddr) < recvspace;
350 	    sent += sendspace + sizeof(struct sockaddr))
351 		ATF_REQUIRE(send(fd, buf, sendspace, 0) == (ssize_t)sendspace);
352 #endif
353 	free(buf);
354 }
355 
356 /*
357  * Put a temporary file into a UNIX domain socket, then take it out and make
358  * sure it's the same file.  First time around, don't close the reference
359  * after sending.
360  */
361 ATF_TC_WITHOUT_HEAD(simple_send_fd);
362 ATF_TC_BODY(simple_send_fd, tc)
363 {
364 	struct stat getfd_stat, putfd_stat;
365 	int fd[2], getfd, putfd;
366 
367 	domainsocketpair(fd);
368 	tempfile(&putfd);
369 	dofstat(putfd, &putfd_stat);
370 	sendfd(fd[0], putfd);
371 	recvfd(fd[1], &getfd, 0);
372 	dofstat(getfd, &getfd_stat);
373 	samefile(&putfd_stat, &getfd_stat);
374 	close(putfd);
375 	close(getfd);
376 	closesocketpair(fd);
377 }
378 
379 /*
380  * Like simple_send_fd but also sets MSG_CMSG_CLOEXEC and checks that the
381  * received file descriptor has the FD_CLOEXEC flag set.
382  */
383 ATF_TC_WITHOUT_HEAD(simple_send_fd_msg_cmsg_cloexec);
384 ATF_TC_BODY(simple_send_fd_msg_cmsg_cloexec, tc)
385 {
386 	struct stat getfd_stat, putfd_stat;
387 	int fd[2], getfd, putfd;
388 
389 	domainsocketpair(fd);
390 	tempfile(&putfd);
391 	dofstat(putfd, &putfd_stat);
392 	sendfd(fd[0], putfd);
393 	recvfd(fd[1], &getfd, MSG_CMSG_CLOEXEC);
394 	dofstat(getfd, &getfd_stat);
395 	samefile(&putfd_stat, &getfd_stat);
396 	ATF_REQUIRE_EQ_MSG(fcntl(getfd, F_GETFD) & FD_CLOEXEC, FD_CLOEXEC,
397 	    "FD_CLOEXEC not set on the received file descriptor");
398 	close(putfd);
399 	close(getfd);
400 	closesocketpair(fd);
401 }
402 
403 /*
404  * Like simple_send_fd but also sets MSG_CMSG_CLOFORK and checks that the
405  * received file descriptor has the FD_CLOFORK flag set.
406  */
407 ATF_TC_WITHOUT_HEAD(simple_send_fd_msg_cmsg_clofork);
408 ATF_TC_BODY(simple_send_fd_msg_cmsg_clofork, tc)
409 {
410 	struct stat getfd_stat, putfd_stat;
411 	int fd[2], getfd, putfd;
412 
413 	domainsocketpair(fd);
414 	tempfile(&putfd);
415 	dofstat(putfd, &putfd_stat);
416 	sendfd(fd[0], putfd);
417 	recvfd(fd[1], &getfd, MSG_CMSG_CLOFORK);
418 	dofstat(getfd, &getfd_stat);
419 	samefile(&putfd_stat, &getfd_stat);
420 	ATF_REQUIRE_EQ_MSG(fcntl(getfd, F_GETFD) & FD_CLOFORK, FD_CLOFORK,
421 	    "FD_CLOFORK not set on the received file descriptor");
422 	close(putfd);
423 	close(getfd);
424 	closesocketpair(fd);
425 }
426 
427 /*
428  * Same as simple_send_fd, only close the file reference after sending, so that
429  * the only reference is the descriptor in the UNIX domain socket buffer.
430  */
431 ATF_TC_WITHOUT_HEAD(send_and_close);
432 ATF_TC_BODY(send_and_close, tc)
433 {
434 	struct stat getfd_stat, putfd_stat;
435 	int fd[2], getfd, putfd;
436 
437 	domainsocketpair(fd);
438 	tempfile(&putfd);
439 	dofstat(putfd, &putfd_stat);
440 	sendfd(fd[0], putfd);
441 	close(putfd);
442 	recvfd(fd[1], &getfd, 0);
443 	dofstat(getfd, &getfd_stat);
444 	samefile(&putfd_stat, &getfd_stat);
445 	close(getfd);
446 	closesocketpair(fd);
447 }
448 
449 /*
450  * Put a temporary file into a UNIX domain socket, then close both endpoints
451  * causing garbage collection to kick off.
452  */
453 ATF_TC_WITHOUT_HEAD(send_and_cancel);
454 ATF_TC_BODY(send_and_cancel, tc)
455 {
456 	int fd[2], putfd;
457 
458 	domainsocketpair(fd);
459 	tempfile(&putfd);
460 	sendfd(fd[0], putfd);
461 	close(putfd);
462 	closesocketpair(fd);
463 }
464 
465 /*
466  * Send file then shutdown receive side to exercise unp_dispose() call
467  * via soshutdown().  Check that shutdown(SHUT_RD) would gc the file
468  * reference sitting in the receive buffer.  There is no good way of
469  * checking that except using global open file count.
470  */
471 ATF_TC_WITHOUT_HEAD(send_and_shutdown);
472 ATF_TC_BODY(send_and_shutdown, tc)
473 {
474 	int fd[2], putfd, nfiles;
475 
476 	domainsocketpair(fd);
477 	tempfile(&putfd);
478 	sendfd(fd[0], putfd);
479 	nfiles = openfiles();
480 	close(putfd);
481 	ATF_REQUIRE(openfiles() == nfiles);
482 	shutdown(fd[1], SHUT_RD);
483 	ATF_REQUIRE(openfiles() == nfiles - 1);
484 	closesocketpair(fd);
485 }
486 
487 /*
488  * Send maximum possible SCM_RIGHTS message.
489  * Internally the file descriptors are converted from integers to pointers
490  * and stored in a single mbuf cluster.  Check that we can not send too much
491  * and that we can successfully send maximum possible amount.  Check that we
492  * can not exploit getrlimit(3).
493  */
494 #define	MAXFDS	((MCLBYTES - _ALIGN(sizeof(struct cmsghdr)))/sizeof(void *))
495 ATF_TC_WITHOUT_HEAD(send_a_lot);
496 ATF_TC_BODY(send_a_lot, tc)
497 {
498 	struct msghdr msghdr;
499 	struct iovec iov;
500 	struct rlimit rlim;
501 	int fd[2], nfds;
502 	char *cmsg, ch;
503 
504 	domainsocketpair(fd);
505 	cmsg = malloc(CMSG_SPACE((MAXFDS + 1) * sizeof(int)));
506 	ATF_REQUIRE(cmsg != NULL);
507 	iov.iov_base = &ch;
508 	iov.iov_len = sizeof(ch);
509 	msghdr = (struct msghdr ){
510 		.msg_control = cmsg,
511 		.msg_controllen = CMSG_LEN((MAXFDS + 1) * sizeof(int)),
512 		.msg_iov = &iov,
513 		.msg_iovlen = 1,
514 	};
515 
516 	/* Sending too much fails. */
517 	putfds(cmsg, fd[0], MAXFDS + 1);
518 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == -1);
519 	ATF_REQUIRE(errno == EMSGSIZE);
520 
521 	/* Sending just the right amount works and everything is received. */
522 	putfds(cmsg, fd[0], MAXFDS);
523 	msghdr.msg_controllen = CMSG_LEN(MAXFDS * sizeof(int));
524 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == 1);
525 	nfds = getnfds();
526 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == 1);
527 	ATF_REQUIRE(getnfds() == (int)(nfds + MAXFDS));
528 
529 	/* Limit our process open files... */
530 	ATF_REQUIRE(getrlimit(RLIMIT_NOFILE, &rlim) == 0);
531 	nfds = rlim.rlim_cur = getnfds();
532 	ATF_REQUIRE(setrlimit(RLIMIT_NOFILE, &rlim) == 0);
533 
534 	/* ... and try to receive a single descriptor. */
535 	putfds(cmsg, fd[0], 1);
536 	msghdr.msg_controllen = CMSG_LEN(sizeof(int));
537 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == 1);
538 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == -1);
539 	/* Such attempt shall fail with EMFILE. */
540 	ATF_REQUIRE(errno == EMFILE);
541 	ATF_REQUIRE(getnfds() == nfds);
542 #if TEST_PROTO == SOCK_STREAM
543 	/*
544 	 * For the SOCK_STREAM the above attempt shall free the control in
545 	 * the kernel, so that socket isn't left in a stuck state.  Next read
546 	 * shall bring us the normal data only.  The stream data shall not
547 	 * miss a byte.
548 	 */
549 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == 1);
550 	ATF_REQUIRE(msghdr.msg_controllen == 0);
551 #elif TEST_PROTO == SOCK_DGRAM
552 	/*
553 	 * For SOCK_DGRAM there are two options for the previously failed
554 	 * syscall: strip the control leaving datagram in the socket or
555 	 * drop the whole datagram.  Our implementation drops the whole
556 	 * datagram.
557 	 */
558 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, MSG_DONTWAIT) == -1);
559 	ATF_REQUIRE(errno == EAGAIN);
560 #endif
561 }
562 
563 /*
564  * Exersize condition when SCM_RIGHTS is successfully internalized, but
565  * message delivery fails due to receive buffer overflow.  Check that no
566  * file descriptors are leaked.
567  */
568 ATF_TC_WITHOUT_HEAD(send_overflow);
569 ATF_TC_BODY(send_overflow, tc)
570 {
571 	void *buf;
572 	ssize_t len;
573 	int fd[2], putfd, nfiles;
574 	int sendspace;
575 
576 	sendspace = (int)getsendspace();
577 	ATF_REQUIRE((buf = malloc(sendspace)) != NULL);
578 
579 	domainsocketpair(fd);
580 	fill(fd[0]);
581 	nfiles = openfiles();
582 	tempfile(&putfd);
583 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
584 #if TEST_PROTO == SOCK_STREAM
585 	ATF_REQUIRE_MSG(len == -1 && errno == EAGAIN,
586 	    "sendmsg: %zd bytes sent, errno %d", len, errno);
587 #elif TEST_PROTO == SOCK_DGRAM
588 	ATF_REQUIRE_MSG(len == -1 && errno == ENOBUFS,
589 	    "sendmsg: %zd bytes sent, errno %d", len, errno);
590 #endif
591 	close(putfd);
592 	ATF_REQUIRE(nfiles == openfiles());
593 	closesocketpair(fd);
594 }
595 
596 ATF_TC_WITHOUT_HEAD(send_rejected);
597 ATF_TC_BODY(send_rejected, tc)
598 {
599 	ssize_t len;
600 	int fd[2], optval, putfd, rc;
601 	char ch;
602 
603 	domainsocketpair(fd);
604 	ATF_REQUIRE_MSG(passrights(fd[0]),
605 	    "socketpair socket not initialized with SO_PASSRIGHTS");
606 	ATF_REQUIRE_MSG(passrights(fd[1]),
607 	    "socketpair socket not initialized with SO_PASSRIGHTS");
608 
609 	tempfile(&putfd);
610 
611 	/* Toggle SO_PASSRIGHTS off on the receiver side. */
612 	optval = 0;
613 	rc = setsockopt(fd[1], SOL_SOCKET, SO_PASSRIGHTS, &optval,
614 	    sizeof(optval));
615 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(SO_PASSRIGHTS) failed: %s",
616 	    strerror(errno));
617 	/* Confirm that the sender-side didn't reflect that... */
618 	ATF_REQUIRE_MSG(passrights(fd[0]),
619 	    "setsockopt(SO_PASSRIGHTS) switched the sender");
620 	/* ... and that the receiver-side did. */
621 	ATF_REQUIRE_MSG(!passrights(fd[1]),
622 	    "setsockopt(SO_PASSRIGHTS) did not switch the receiver");
623 
624 	ch = 0;
625 	len = sendfd_payload(fd[0], putfd, &ch, sizeof(ch));
626 	ATF_REQUIRE_MSG(len == -1,
627 	    "sending SCM_RIGHTS with SO_PASSRIGHTS disabled on peer did not fail");
628 	ATF_REQUIRE_MSG(errno == EPERM,
629 	    "bad SCM_RIGHTS failure: %s", strerror(errno));
630 	closesocketpair(fd);
631 }
632 
633 ATF_TC_WITHOUT_HEAD(send_rejected_late);
634 ATF_TC_BODY(send_rejected_late, tc)
635 {
636 	struct cmsghdr *cmsghdr;
637 	struct msghdr msghdr;
638 	ssize_t len;
639 	char cmsgbuf[CMSG_SPACE(sizeof(int))];
640 	int fd[2], nfds, optval, putfd, rc;
641 	char ch;
642 #define	MAGIC_VAL	42
643 
644 	domainsocketpair(fd);
645 	tempfile(&putfd);
646 
647 	nfds = getnfds();
648 
649 	ch = MAGIC_VAL;
650 	len = sendfd_payload(fd[0], putfd, &ch, sizeof(ch));
651 	ATF_REQUIRE_MSG(len == sizeof(ch),
652 	    "valid send of SCM_RIGHTS failed: %s", strerror(errno));
653 
654 	/*
655 	 * Toggle SO_PASSRIGHTS off on the receiver side.  The subsequent recv
656 	 * should actually succeed, we just won't have an fd installed.
657 	 */
658 	optval = 0;
659 	rc = setsockopt(fd[1], SOL_SOCKET, SO_PASSRIGHTS, &optval,
660 	    sizeof(optval));
661 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(SO_PASSRIGHTS) failed: %s",
662 	    strerror(errno));
663 
664 	bzero(&msghdr, sizeof(msghdr));
665 	msghdr.msg_control = &cmsgbuf[0];
666 	msghdr.msg_controllen = sizeof(cmsgbuf);
667 
668 	ch = 0;
669 	len = recvfd_payload_cmsg(fd[1], &ch, sizeof(ch), &msghdr, 0);
670 	/* We want to confirm that we still received the sent byte... */
671 	ATF_REQUIRE_MSG(len == sizeof(ch), "recvmsg should have returned data");
672 	ATF_REQUIRE_MSG(ch == MAGIC_VAL, "recvmsg returned garbage? %d", ch);
673 
674 	/* ... and make sure we did not receive any descriptors! */
675 	cmsghdr = CMSG_FIRSTHDR(&msghdr);
676 	ATF_REQUIRE_MSG(cmsghdr == NULL || cmsghdr->cmsg_type != SCM_RIGHTS,
677 	    "recvmsg unexpectedly received a descriptor");
678 	ATF_REQUIRE(getnfds() == nfds);
679 	closesocketpair(fd);
680 }
681 
682 ATF_TC_WITHOUT_HEAD(send_rejected_noinherit);
683 ATF_TC_BODY(send_rejected_noinherit, tc)
684 {
685 	struct sockaddr_un sun;
686 	int clsock, connsock, ls, optval, rc;
687 
688 	ls = socket(AF_UNIX, SOCK_STREAM, 0);
689 	ATF_REQUIRE(ls != -1);
690 
691 	optval = 0;
692 	rc = setsockopt(ls, SOL_SOCKET, SO_PASSRIGHTS, &optval,
693 	    sizeof(optval));
694 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(SO_PASSRIGHTS) failed: %s",
695 	    strerror(errno));
696 
697 	memset(&sun, 0, sizeof(sun));
698 	sun.sun_len = sizeof(sun);
699 	sun.sun_family = AF_UNIX;
700 	snprintf(sun.sun_path, sizeof(sun.sun_path), "listen.sock");
701 	rc = bind(ls, (struct sockaddr *)&sun, sizeof(sun));
702 	ATF_REQUIRE_MSG(rc == 0, "bind failed: %s", strerror(errno));
703 	rc = listen(ls, 0);
704 	ATF_REQUIRE_MSG(rc == 0, "listen failed: %s", strerror(errno));
705 
706 	ATF_REQUIRE_MSG(!passrights(ls),
707 	    "listening socket lost its SO_PASSRIGHTS setting");
708 
709 	connsock = socket(AF_UNIX, SOCK_STREAM, 0);
710 	ATF_REQUIRE_MSG(connsock != -1, "connect failed: %s", strerror(errno));
711 
712 	rc = connect(connsock, (const struct sockaddr *)&sun,
713 	    sizeof(sun));
714 	ATF_REQUIRE_MSG(rc == 0, "connect failed: %s", strerror(errno));
715 
716 	/*
717 	 * Finally, accept(4) and confirm that the new socket has
718 	 * SO_PASSRIGHTS set.
719 	 */
720 	clsock = accept(ls, NULL, NULL);
721 	ATF_REQUIRE_MSG(clsock >= 0, "accept failed: %s", strerror(errno));
722 
723 	ATF_REQUIRE_MSG(passrights(clsock),
724 	    "inherited socket should enable SO_PASSRIGHTS");
725 	close(clsock);
726 	close(connsock);
727 	close(ls);
728 }
729 
730 /*
731  * Make sure that we do not receive descriptors with MSG_PEEK.
732  */
733 ATF_TC_WITHOUT_HEAD(peek);
734 ATF_TC_BODY(peek, tc)
735 {
736 	int fd[2], getfd, putfd, nfds;
737 
738 	domainsocketpair(fd);
739 	tempfile(&putfd);
740 	nfds = getnfds();
741 	sendfd(fd[0], putfd);
742 	ATF_REQUIRE(getnfds() == nfds);
743 
744 	/* First make MSG_PEEK recvmsg(2)... */
745 	char cbuf[CMSG_SPACE(sizeof(int))];
746 	char buf[1];
747 	struct iovec iov = {
748 		.iov_base = buf,
749 		.iov_len = sizeof(buf)
750 	};
751 	struct msghdr msghdr = {
752 		.msg_iov = &iov,
753 		.msg_iovlen = 1,
754 		.msg_control = cbuf,
755 		.msg_controllen = sizeof(cbuf),
756 	};
757 	ATF_REQUIRE(1 == recvmsg(fd[1], &msghdr, MSG_PEEK));
758 	for (struct cmsghdr *cmsghdr = CMSG_FIRSTHDR(&msghdr);
759 	     cmsghdr != NULL; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) {
760 		/* Usually this is some garbage. */
761 		printf("level %d type %d len %u\n",
762 		    cmsghdr->cmsg_level, cmsghdr->cmsg_type, cmsghdr->cmsg_len);
763 	}
764 
765 	/* ... and make sure we did not receive any descriptors! */
766 	ATF_REQUIRE(getnfds() == nfds);
767 
768 	/* Now really receive a descriptor. */
769 	recvfd(fd[1], &getfd, 0);
770 	ATF_REQUIRE(getnfds() == nfds + 1);
771 	close(putfd);
772 	close(getfd);
773 	closesocketpair(fd);
774 }
775 
776 /*
777  * Send two files.  Then receive them.  Make sure they are returned in the
778  * right order, and both get there.
779  */
780 ATF_TC_WITHOUT_HEAD(two_files);
781 ATF_TC_BODY(two_files, tc)
782 {
783 	struct stat getfd_1_stat, getfd_2_stat, putfd_1_stat, putfd_2_stat;
784 	int fd[2], getfd_1, getfd_2, putfd_1, putfd_2;
785 
786 	domainsocketpair(fd);
787 	tempfile(&putfd_1);
788 	tempfile(&putfd_2);
789 	dofstat(putfd_1, &putfd_1_stat);
790 	dofstat(putfd_2, &putfd_2_stat);
791 	sendfd(fd[0], putfd_1);
792 	sendfd(fd[0], putfd_2);
793 	close(putfd_1);
794 	close(putfd_2);
795 	recvfd(fd[1], &getfd_1, 0);
796 	recvfd(fd[1], &getfd_2, 0);
797 	dofstat(getfd_1, &getfd_1_stat);
798 	dofstat(getfd_2, &getfd_2_stat);
799 	samefile(&putfd_1_stat, &getfd_1_stat);
800 	samefile(&putfd_2_stat, &getfd_2_stat);
801 	close(getfd_1);
802 	close(getfd_2);
803 	closesocketpair(fd);
804 }
805 
806 /*
807  * Big bundling test.  Send an endpoint of the UNIX domain socket over itself,
808  * closing the door behind it.
809  */
810 ATF_TC_WITHOUT_HEAD(bundle);
811 ATF_TC_BODY(bundle, tc)
812 {
813 	int fd[2], getfd;
814 
815 	domainsocketpair(fd);
816 
817 	sendfd(fd[0], fd[0]);
818 	close(fd[0]);
819 	recvfd(fd[1], &getfd, 0);
820 	close(getfd);
821 	close(fd[1]);
822 }
823 
824 /*
825  * Big bundling test part two: Send an endpoint of the UNIX domain socket over
826  * itself, close the door behind it, and never remove it from the other end.
827  */
828 ATF_TC_WITHOUT_HEAD(bundle_cancel);
829 ATF_TC_BODY(bundle_cancel, tc)
830 {
831 	int fd[2];
832 
833 	domainsocketpair(fd);
834 	sendfd(fd[0], fd[0]);
835 	sendfd(fd[1], fd[0]);
836 	closesocketpair(fd);
837 }
838 
839 /*
840  * Test for PR 151758: Send an character device over the UNIX domain socket
841  * and then close both sockets to orphan the device.
842  */
843 ATF_TC_WITHOUT_HEAD(devfs_orphan);
844 ATF_TC_BODY(devfs_orphan, tc)
845 {
846 	int fd[2], putfd;
847 
848 	domainsocketpair(fd);
849 	devnull(&putfd);
850 	sendfd(fd[0], putfd);
851 	close(putfd);
852 	closesocketpair(fd);
853 }
854 
855 /*
856  * Test for PR 181741. Receiver sets LOCAL_CREDS, and kernel prepends a
857  * control message to the data. Sender sends large payload using a non-blocking
858  * socket. Payload + SCM_RIGHTS + LOCAL_CREDS hit socket buffer limit, and
859  * receiver receives truncated data.
860  */
861 ATF_TC_WITHOUT_HEAD(rights_creds_payload);
862 ATF_TC_BODY(rights_creds_payload, tc)
863 {
864 	const int on = 1;
865 	u_long sendspace;
866 	ssize_t len, rlen;
867 	void *buf;
868 	int fd[2], getfd, putfd, rc;
869 
870 	sendspace = getsendspace();
871 	buf = calloc(1, sendspace);
872 	ATF_REQUIRE(buf != NULL);
873 
874 	domainsocketpair(fd);
875 	tempfile(&putfd);
876 
877 	rc = fcntl(fd[0], F_SETFL, O_NONBLOCK);
878 	ATF_REQUIRE_MSG(rc != -1, "fcntl(O_NONBLOCK) failed: %s",
879 	    strerror(errno));
880 	rc = setsockopt(fd[1], 0, LOCAL_CREDS, &on, sizeof(on));
881 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(LOCAL_CREDS) failed: %s",
882 	    strerror(errno));
883 
884 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
885 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
886 #if TEST_PROTO == SOCK_STREAM
887 	ATF_REQUIRE_MSG((size_t)len < sendspace,
888 	    "sendmsg: %zd bytes sent, expected < %lu", len, sendspace);
889 #endif
890 #if TEST_PROTO == SOCK_DGRAM
891 	/*
892 	 * sendmsg(2) can't truncate datagrams, only recvmsg(2) can.  There are
893 	 * two options for the kernel here: either accept the datagram with
894 	 * slight overcommit of the socket buffer space or return ENOBUFS for a
895 	 * datagram that is smaller or equal to the socket buffer space.  Our
896 	 * implementation does overcommit.  Explanation is simple: from our
897 	 * side we see space available, we have no idea that remote side has
898 	 * LOCAL_CREDS set.  From our side we expect sendmsg(2) to succeed.
899 	 */
900 	ATF_REQUIRE_MSG((size_t)len == sendspace,
901 	    "sendmsg: %zd bytes sent, expected %lu", len, sendspace);
902 #endif
903 	rlen = recvfd_payload(fd[1], &getfd, buf, len,
904 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
905 	ATF_REQUIRE_MSG(rlen == len,
906 	    "recvmsg: %zd bytes received; expected %zd", rlen, len);
907 
908 	close(putfd);
909 	close(getfd);
910 	closesocketpair(fd);
911 }
912 
913 static void
914 send_cmsg(int sockfd, void *cmsg, size_t cmsgsz)
915 {
916 	struct iovec iov;
917 	struct msghdr msghdr;
918 	ssize_t len;
919 	char ch;
920 
921 	ch = 0;
922 	bzero(&msghdr, sizeof(msghdr));
923 
924 	iov.iov_base = &ch;
925 	iov.iov_len = sizeof(ch);
926 	msghdr.msg_control = cmsg;
927 	msghdr.msg_controllen = cmsgsz;
928 	msghdr.msg_iov = &iov;
929 	msghdr.msg_iovlen = 1;
930 
931 	len = sendmsg(sockfd, &msghdr, 0);
932 	ATF_REQUIRE_MSG(len != -1,
933 	    "sendmsg failed: %s", strerror(errno));
934 	ATF_REQUIRE_MSG(len == sizeof(ch),
935 	    "sendmsg: %zd bytes sent; expected %zu", len, sizeof(ch));
936 }
937 
938 static void
939 recv_cmsg(int sockfd, char *cmsg, size_t cmsgsz, int flags)
940 {
941 	struct iovec iov;
942 	struct msghdr msghdr;
943 	ssize_t len;
944 	char ch;
945 
946 	ch = 0;
947 	bzero(&msghdr, sizeof(msghdr));
948 
949 	iov.iov_base = &ch;
950 	iov.iov_len = sizeof(ch);
951 	msghdr.msg_control = cmsg;
952 	msghdr.msg_controllen = cmsgsz;
953 	msghdr.msg_iov = &iov;
954 	msghdr.msg_iovlen = 1;
955 
956 	len = recvmsg(sockfd, &msghdr, 0);
957 	ATF_REQUIRE_MSG(len != -1,
958 	    "recvmsg failed: %s", strerror(errno));
959 	ATF_REQUIRE_MSG(len == sizeof(ch),
960 	    "recvmsg: %zd bytes received; expected %zu", len, sizeof(ch));
961 	ATF_REQUIRE_MSG((msghdr.msg_flags & flags) == flags,
962 	    "recvmsg: got flags %#x; expected %#x", msghdr.msg_flags, flags);
963 }
964 
965 /*
966  * Test for PR 131876.  Receiver uses a control message buffer that is too
967  * small for the incoming SCM_RIGHTS message, so the message is truncated.
968  * The kernel must not leak the copied right into the receiver's namespace.
969  */
970 ATF_TC_WITHOUT_HEAD(truncated_rights);
971 ATF_TC_BODY(truncated_rights, tc)
972 {
973 	char *message;
974 	int fd[2], nfds, putfd, rc;
975 
976 	domainsocketpair(fd);
977 	devnull(&putfd);
978 	nfds = getnfds();
979 
980 	/*
981 	 * Case 1: Send a single descriptor and truncate the message.
982 	 */
983 	message = malloc(CMSG_SPACE(sizeof(int)));
984 	ATF_REQUIRE(message != NULL);
985 	putfds(message, putfd, 1);
986 	send_cmsg(fd[0], message, CMSG_LEN(sizeof(int)));
987 	recv_cmsg(fd[1], message, CMSG_LEN(0), MSG_CTRUNC);
988 	ATF_REQUIRE(getnfds() == nfds);
989 	free(message);
990 
991 	/*
992 	 * Case 2a: Send two descriptors in separate messages, and truncate at
993 	 *          the boundary between the two messages.  We should still
994 	 *          receive the first message.
995 	 */
996 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
997 	ATF_REQUIRE(message != NULL);
998 	putfds(message, putfd, 1);
999 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
1000 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
1001 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
1002 	rc = close(*(int *)CMSG_DATA(message));
1003 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
1004 	ATF_REQUIRE(getnfds() == nfds);
1005 	free(message);
1006 
1007 	/*
1008 	 * Case 2b: Send two descriptors in separate messages, and truncate
1009 	 *          before the end of the first message.
1010 	 */
1011 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
1012 	ATF_REQUIRE(message != NULL);
1013 	putfds(message, putfd, 1);
1014 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
1015 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
1016 	recv_cmsg(fd[1], message, CMSG_SPACE(0), MSG_CTRUNC);
1017 	ATF_REQUIRE(getnfds() == nfds);
1018 	free(message);
1019 
1020 	/*
1021 	 * Case 2c: Send two descriptors in separate messages, and truncate
1022 	 *          after the end of the first message.  We should still
1023 	 *          receive the first message.
1024 	 */
1025 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
1026 	ATF_REQUIRE(message != NULL);
1027 	putfds(message, putfd, 1);
1028 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
1029 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
1030 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)) + CMSG_SPACE(0),
1031 	    MSG_CTRUNC);
1032 	rc = close(*(int *)CMSG_DATA(message));
1033 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
1034 	ATF_REQUIRE(getnfds() == nfds);
1035 	free(message);
1036 
1037 	/*
1038 	 * Case 3: Send three descriptors in the same message, and leave space
1039 	 *         only for the first when receiving the message.
1040 	 */
1041 	message = malloc(CMSG_SPACE(sizeof(int) * 3));
1042 	ATF_REQUIRE(message != NULL);
1043 	putfds(message, putfd, 3);
1044 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int) * 3));
1045 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
1046 	ATF_REQUIRE(getnfds() == nfds);
1047 	free(message);
1048 
1049 	close(putfd);
1050 	closesocketpair(fd);
1051 }
1052 
1053 /*
1054  * Ensure that an attempt to copy a SCM_RIGHTS message to the recipient
1055  * fails.  In this case the kernel must dispose of the externalized rights
1056  * rather than leaking them into the recipient's file descriptor table.
1057  */
1058 ATF_TC_WITHOUT_HEAD(copyout_rights_error);
1059 ATF_TC_BODY(copyout_rights_error, tc)
1060 {
1061 	struct iovec iovec;
1062 	struct msghdr msghdr;
1063 	char buf[16];
1064 	ssize_t len;
1065 	int fd[2], error, nfds, putfd;
1066 
1067 	memset(buf, 0, sizeof(buf));
1068 	domainsocketpair(fd);
1069 	devnull(&putfd);
1070 	nfds = getnfds();
1071 
1072 	len = sendfd_payload(fd[0], putfd, buf, sizeof(buf));
1073 	ATF_REQUIRE_MSG(len != -1, "sendmsg failed: %s", strerror(errno));
1074 
1075 	bzero(&msghdr, sizeof(msghdr));
1076 
1077 	iovec.iov_base = buf;
1078 	iovec.iov_len = sizeof(buf);
1079 	msghdr.msg_control = (char *)-1; /* trigger EFAULT */
1080 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
1081 	msghdr.msg_iov = &iovec;
1082 	msghdr.msg_iovlen = 1;
1083 
1084 	len = recvmsg(fd[1], &msghdr, 0);
1085 	error = errno;
1086 	ATF_REQUIRE_MSG(len == -1, "recvmsg succeeded: %zd", len);
1087 	ATF_REQUIRE_MSG(errno == EFAULT, "expected EFAULT, got %d (%s)",
1088 	    error, strerror(errno));
1089 
1090 	/* Verify that no FDs were leaked. */
1091 	ATF_REQUIRE(getnfds() == nfds);
1092 
1093 	close(putfd);
1094 	closesocketpair(fd);
1095 }
1096 
1097 /*
1098  * Verify that we can handle empty rights messages.
1099  */
1100 ATF_TC_WITHOUT_HEAD(empty_rights_message);
1101 ATF_TC_BODY(empty_rights_message, tc)
1102 {
1103 	struct iovec iov;
1104 	struct msghdr msghdr;
1105 	struct cmsghdr cmsg;
1106 	char *cm, message[CMSG_SPACE(0) + CMSG_SPACE(sizeof(int))];
1107 	ssize_t len;
1108 	int error, fd[2], putfd;
1109 
1110 	domainsocketpair(fd);
1111 	devnull(&putfd);
1112 
1113 	memset(&msghdr, 0, sizeof(msghdr));
1114 	iov.iov_base = NULL;
1115 	iov.iov_len = 0;
1116 	msghdr.msg_iov = &iov;
1117 	msghdr.msg_iovlen = 1;
1118 
1119 	/*
1120 	 * Try sending incorrect empty message.  On 64-bit platforms, where
1121 	 * CMSG_SPACE(0) > sizeof(struct cmsghdr), this will exercise
1122 	 * an edge case.
1123 	 */
1124 	cmsg = (struct cmsghdr ){
1125 	    .cmsg_len = sizeof(struct cmsghdr),	/* not CMSG_LEN(0)! */
1126 	    .cmsg_level = SOL_SOCKET,
1127 	    .cmsg_type = SCM_RIGHTS,
1128 	};
1129 	msghdr.msg_control = &cmsg;
1130 	msghdr.msg_controllen = CMSG_SPACE(0);
1131 
1132 	len = sendmsg(fd[0], &msghdr, 0);
1133 	if (CMSG_LEN(0) != sizeof(struct cmsghdr))
1134 		ATF_REQUIRE(len == -1 && errno == EINVAL);
1135 	else
1136 		ATF_REQUIRE(len == 0);
1137 
1138 	/*
1139 	 * Try sending an empty message followed by a non-empty message.
1140 	 */
1141 	cm = message;
1142 	putfds(cm, -1, 0);
1143 	cm += CMSG_SPACE(0);
1144 	putfds(cm, putfd, 1);
1145 	msghdr.msg_control = message;
1146 	msghdr.msg_controllen = sizeof(message);
1147 
1148 	len = sendmsg(fd[0], &msghdr, 0);
1149 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
1150 
1151 	/* Only the non-empty message should be received. */
1152 	len = recvmsg(fd[1], &msghdr, 0);
1153 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
1154 	ATF_REQUIRE(msghdr.msg_controllen == CMSG_SPACE(sizeof(int)));
1155 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
1156 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
1157 
1158 	/*
1159 	 * Now try sending with the non-empty message before the empty message.
1160 	 */
1161 	cm = message;
1162 	putfds(cm, putfd, 1);
1163 	cm += CMSG_SPACE(sizeof(int));
1164 	putfds(cm, -1, 0);
1165 
1166 	memset(&msghdr, 0, sizeof(msghdr));
1167 	iov.iov_base = NULL;
1168 	iov.iov_len = 0;
1169 	msghdr.msg_control = message;
1170 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
1171 	msghdr.msg_iov = &iov;
1172 	msghdr.msg_iovlen = 1;
1173 
1174 	len = sendmsg(fd[0], &msghdr, 0);
1175 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
1176 
1177 	/* Only the non-empty message should be received. */
1178 	len = recvmsg(fd[1], &msghdr, 0);
1179 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
1180 	ATF_REQUIRE(msghdr.msg_controllen == CMSG_SPACE(sizeof(int)));
1181 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
1182 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
1183 
1184 	(void)close(putfd);
1185 }
1186 
1187 /*
1188  * Check that sending control creates records in a stream socket, making it
1189  * behave like a seqpacket socket.  If we stack several control+data writes
1190  * on a stream socket, we won't be able to read them all at once, even if we
1191  * provide a buffer large enough to receive all at once.
1192  *
1193  * XXXGL: adding MSG_WAITALL to the recvmsg() flags will make this test stuck.
1194  */
1195 ATF_TC_WITHOUT_HEAD(control_creates_records);
1196 ATF_TC_BODY(control_creates_records, tc)
1197 {
1198 	int fd[2], putfd, getfd;
1199 	char buf[2];
1200 	ssize_t rlen;
1201 
1202 	domainsocketpair(fd);
1203 	tempfile(&putfd);
1204 
1205 	for (int i = 1; i <= 2; i++)
1206 		ATF_REQUIRE(sendfd_payload(fd[0], putfd, buf, 1) == 1);
1207 	ATF_REQUIRE(close(putfd) == 0);
1208 	for (int i = 1; i <= 2; i++) {
1209 		rlen = recvfd_payload(fd[1], &getfd, buf, 2,
1210 		    CMSG_SPACE(sizeof(int)) * 2, 0);
1211 		ATF_REQUIRE_MSG(rlen == 1,
1212 		    "recvmsg: %zd bytes received; expected 1", rlen);
1213 		ATF_REQUIRE(close(getfd) == 0);
1214 	}
1215 	closesocketpair(fd);
1216 }
1217 
1218 ATF_TC_WITH_CLEANUP(cross_jail_dirfd);
1219 ATF_TC_HEAD(cross_jail_dirfd, tc)
1220 {
1221 	atf_tc_set_md_var(tc, "require.user", "root");
1222 }
1223 ATF_TC_BODY(cross_jail_dirfd, tc)
1224 {
1225 	int error, sock[2], jid1, jid2, status;
1226 	pid_t pid1, pid2;
1227 
1228 	domainsocketpair(sock);
1229 
1230 	error = mkdir("./a", 0755);
1231 	ATF_REQUIRE(error == 0);
1232 	error = mkdir("./b", 0755);
1233 	ATF_REQUIRE(error == 0);
1234 	error = mkdir("./c", 0755);
1235 	ATF_REQUIRE(error == 0);
1236 	error = mkdir("./a/c", 0755);
1237 	ATF_REQUIRE(error == 0);
1238 
1239 	jid1 = jail_setv(JAIL_CREATE,
1240 	    "name", "passfd_test_cross_jail_dirfd1",
1241 	    "path", "./a",
1242 	    "persist", NULL,
1243 	    NULL);
1244 	ATF_REQUIRE_MSG(jid1 >= 0, "jail_setv: %s", jail_errmsg);
1245 
1246 	jid2 = jail_setv(JAIL_CREATE,
1247 	    "name", "passfd_test_cross_jail_dirfd2",
1248 	    "path", "./b",
1249 	    "persist", NULL,
1250 	    NULL);
1251 	ATF_REQUIRE_MSG(jid2 >= 0, "jail_setv: %s", jail_errmsg);
1252 
1253 	pid1 = fork();
1254 	ATF_REQUIRE(pid1 >= 0);
1255 	if (pid1 == 0) {
1256 		ssize_t len;
1257 		int dfd, error;
1258 		char ch;
1259 
1260 		error = jail_attach(jid1);
1261 		if (error != 0)
1262 			err(1, "jail_attach");
1263 
1264 		dfd = open(".", O_RDONLY | O_DIRECTORY);
1265 		if (dfd < 0)
1266 			err(1, "open(\".\") in jail %d", jid1);
1267 
1268 		ch = 0;
1269 		len = sendfd_payload(sock[0], dfd, &ch, sizeof(ch));
1270 		if (len == -1)
1271 			err(1, "sendmsg");
1272 
1273 		_exit(0);
1274 	}
1275 
1276 	pid2 = fork();
1277 	ATF_REQUIRE(pid2 >= 0);
1278 	if (pid2 == 0) {
1279 		ssize_t len;
1280 		int dfd, dfd2, error, fd;
1281 		char ch;
1282 
1283 		error = jail_attach(jid2);
1284 		if (error != 0)
1285 			err(1, "jail_attach");
1286 
1287 		/* Get a directory from outside the jail root. */
1288 		len = recvfd_payload(sock[1], &dfd, &ch, sizeof(ch),
1289 		    CMSG_SPACE(sizeof(int)), 0);
1290 		if (len == -1)
1291 			err(1, "recvmsg");
1292 
1293 		if ((fcntl(dfd, F_GETFD) & FD_RESOLVE_BENEATH) == 0)
1294 			errx(1, "dfd does not have FD_RESOLVE_BENEATH set");
1295 
1296 		/* Make sure we can't chdir. */
1297 		error = fchdir(dfd);
1298 		if (error == 0)
1299 			errx(1, "fchdir succeeded");
1300 		if (errno != ENOTCAPABLE)
1301 			err(1, "fchdir");
1302 
1303 		/* Make sure a dotdot access fails. */
1304 		fd = openat(dfd, "../c", O_RDONLY | O_DIRECTORY);
1305 		if (fd >= 0)
1306 			errx(1, "openat(\"../c\") succeeded");
1307 		if (errno != ENOTCAPABLE)
1308 			err(1, "openat");
1309 
1310 		/* Accesses within the sender's jail root are ok. */
1311 		fd = openat(dfd, "c", O_RDONLY | O_DIRECTORY);
1312 		if (fd < 0)
1313 			err(1, "openat(\"c\")");
1314 
1315 		dfd2 = openat(dfd, "", O_EMPTY_PATH | O_RDONLY | O_DIRECTORY);
1316 		if (dfd2 < 0)
1317 			err(1, "openat(\"\")");
1318 		if ((fcntl(dfd2, F_GETFD) & FD_RESOLVE_BENEATH) == 0)
1319 			errx(1, "dfd2 does not have FD_RESOLVE_BENEATH set");
1320 
1321 		_exit(0);
1322 	}
1323 
1324 	error = waitpid(pid1, &status, 0);
1325 	ATF_REQUIRE(error != -1);
1326 	ATF_REQUIRE(WIFEXITED(status));
1327 	ATF_REQUIRE(WEXITSTATUS(status) == 0);
1328 	error = waitpid(pid2, &status, 0);
1329 	ATF_REQUIRE(error != -1);
1330 	ATF_REQUIRE(WIFEXITED(status));
1331 	ATF_REQUIRE(WEXITSTATUS(status) == 0);
1332 
1333 	closesocketpair(sock);
1334 }
1335 ATF_TC_CLEANUP(cross_jail_dirfd, tc)
1336 {
1337 	int jid;
1338 
1339 	jid = jail_getid("passfd_test_cross_jail_dirfd1");
1340 	if (jid >= 0 && jail_remove(jid) != 0)
1341 		err(1, "jail_remove");
1342 	jid = jail_getid("passfd_test_cross_jail_dirfd2");
1343 	if (jid >= 0 && jail_remove(jid) != 0)
1344 		err(1, "jail_remove");
1345 }
1346 
1347 ATF_TC_WITHOUT_HEAD(listening_socket);
1348 ATF_TC_BODY(listening_socket, tc)
1349 {
1350 	struct sockaddr_un sun;
1351 	int error, ls, s[2];
1352 
1353 	ls = socket(AF_UNIX, SOCK_STREAM, 0);
1354 	ATF_REQUIRE(ls != -1);
1355 
1356 	memset(&sun, 0, sizeof(sun));
1357 	sun.sun_len = sizeof(sun);
1358 	sun.sun_family = AF_UNIX;
1359 	snprintf(sun.sun_path, sizeof(sun.sun_path), "listen.sock");
1360 	error = bind(ls, (struct sockaddr *)&sun, sizeof(sun));
1361 	ATF_REQUIRE_MSG(error == 0, "bind failed: %s", strerror(errno));
1362 	error = listen(ls, 0);
1363 
1364 	error = socketpair(AF_UNIX, SOCK_STREAM, 0, s);
1365 	ATF_REQUIRE_MSG(error == 0, "socketpair failed: %s", strerror(errno));
1366 
1367 	sendfd(s[0], ls);
1368 	sendfd(s[0], s[0]);
1369 	sendfd(s[0], s[1]);
1370 	close(ls);
1371 	close(s[0]);
1372 	close(s[1]);
1373 }
1374 
1375 ATF_TP_ADD_TCS(tp)
1376 {
1377 
1378 	ATF_TP_ADD_TC(tp, simple_send_fd);
1379 	ATF_TP_ADD_TC(tp, simple_send_fd_msg_cmsg_cloexec);
1380 	ATF_TP_ADD_TC(tp, simple_send_fd_msg_cmsg_clofork);
1381 	ATF_TP_ADD_TC(tp, send_and_close);
1382 	ATF_TP_ADD_TC(tp, send_and_cancel);
1383 	ATF_TP_ADD_TC(tp, send_and_shutdown);
1384 	ATF_TP_ADD_TC(tp, send_a_lot);
1385 	ATF_TP_ADD_TC(tp, send_overflow);
1386 	ATF_TP_ADD_TC(tp, send_rejected);
1387 	ATF_TP_ADD_TC(tp, send_rejected_late);
1388 	ATF_TP_ADD_TC(tp, send_rejected_noinherit);
1389 	ATF_TP_ADD_TC(tp, peek);
1390 	ATF_TP_ADD_TC(tp, two_files);
1391 	ATF_TP_ADD_TC(tp, bundle);
1392 	ATF_TP_ADD_TC(tp, bundle_cancel);
1393 	ATF_TP_ADD_TC(tp, devfs_orphan);
1394 	ATF_TP_ADD_TC(tp, rights_creds_payload);
1395 	ATF_TP_ADD_TC(tp, truncated_rights);
1396 	ATF_TP_ADD_TC(tp, copyout_rights_error);
1397 	ATF_TP_ADD_TC(tp, empty_rights_message);
1398 	ATF_TP_ADD_TC(tp, control_creates_records);
1399 	ATF_TP_ADD_TC(tp, cross_jail_dirfd);
1400 	ATF_TP_ADD_TC(tp, listening_socket);
1401 
1402 	return (atf_no_error());
1403 }
1404