xref: /freebsd/tests/sys/kern/unix_passfd_test.c (revision 5f757f3f)
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 ssize_t
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 
234 	cmsghdr = CMSG_FIRSTHDR(&msghdr);
235 	ATF_REQUIRE_MSG(cmsghdr != NULL,
236 	    "recvmsg: did not receive control message");
237 	foundcreds = false;
238 	*recv_fd = -1;
239 	for (; cmsghdr != NULL; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) {
240 		if (cmsghdr->cmsg_level == SOL_SOCKET &&
241 		    cmsghdr->cmsg_type == SCM_RIGHTS &&
242 		    cmsghdr->cmsg_len == CMSG_LEN(sizeof(int))) {
243 			memcpy(recv_fd, CMSG_DATA(cmsghdr), sizeof(int));
244 			ATF_REQUIRE(*recv_fd != -1);
245 		} else if (cmsghdr->cmsg_level == SOL_SOCKET &&
246 		    cmsghdr->cmsg_type == SCM_CREDS)
247 			foundcreds = true;
248 	}
249 	ATF_REQUIRE_MSG(*recv_fd != -1,
250 	    "recvmsg: did not receive single-fd message");
251 	ATF_REQUIRE_MSG(!localcreds(sockfd) || foundcreds,
252 	    "recvmsg: expected credentials were not received");
253 	ATF_REQUIRE_MSG((msghdr.msg_flags & MSG_TRUNC) == 0,
254 	    "recvmsg: MSG_TRUNC is set while buffer is sufficient");
255 
256 	return (len);
257 }
258 
259 static void
260 recvfd(int sockfd, int *recv_fd, int flags)
261 {
262 	ssize_t len;
263 	char ch = 0;
264 
265 	len = recvfd_payload(sockfd, recv_fd, &ch, sizeof(ch),
266 	    CMSG_SPACE(sizeof(int)), flags);
267 	ATF_REQUIRE_MSG((size_t)len == sizeof(ch),
268 	    "recvmsg: %zd bytes received; expected %zd", len, sizeof(ch));
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: %zd bytes sent, errno %d", len, errno);
538 #elif TEST_PROTO == SOCK_DGRAM
539 	ATF_REQUIRE_MSG(len == -1 && errno == ENOBUFS,
540 	    "sendmsg: %zd 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, rlen;
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 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
658 #if TEST_PROTO == SOCK_STREAM
659 	ATF_REQUIRE_MSG((size_t)len < sendspace,
660 	    "sendmsg: %zd bytes sent, expected < %lu", len, sendspace);
661 #endif
662 #if TEST_PROTO == SOCK_DGRAM
663 	/*
664 	 * sendmsg(2) can't truncate datagrams, only recvmsg(2) can.  There are
665 	 * two options for the kernel here: either accept the datagram with
666 	 * slight overcommit of the socket buffer space or return ENOBUFS for a
667 	 * datagram that is smaller or equal to the socket buffer space.  Our
668 	 * implementation does overcommit.  Explanation is simple: from our
669 	 * side we see space available, we have no idea that remote side has
670 	 * LOCAL_CREDS set.  From our side we expect sendmsg(2) to succeed.
671 	 */
672 	ATF_REQUIRE_MSG((size_t)len == sendspace,
673 	    "sendmsg: %zd bytes sent, expected %lu", len, sendspace);
674 #endif
675 	rlen = recvfd_payload(fd[1], &getfd, buf, len,
676 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
677 	ATF_REQUIRE_MSG(rlen == len,
678 	    "recvmsg: %zd bytes received; expected %zd", rlen, len);
679 
680 	close(putfd);
681 	close(getfd);
682 	closesocketpair(fd);
683 }
684 
685 static void
686 send_cmsg(int sockfd, void *cmsg, size_t cmsgsz)
687 {
688 	struct iovec iov;
689 	struct msghdr msghdr;
690 	ssize_t len;
691 	char ch;
692 
693 	ch = 0;
694 	bzero(&msghdr, sizeof(msghdr));
695 
696 	iov.iov_base = &ch;
697 	iov.iov_len = sizeof(ch);
698 	msghdr.msg_control = cmsg;
699 	msghdr.msg_controllen = cmsgsz;
700 	msghdr.msg_iov = &iov;
701 	msghdr.msg_iovlen = 1;
702 
703 	len = sendmsg(sockfd, &msghdr, 0);
704 	ATF_REQUIRE_MSG(len != -1,
705 	    "sendmsg failed: %s", strerror(errno));
706 	ATF_REQUIRE_MSG(len == sizeof(ch),
707 	    "sendmsg: %zd bytes sent; expected %zu", len, sizeof(ch));
708 }
709 
710 static void
711 recv_cmsg(int sockfd, char *cmsg, size_t cmsgsz, int flags)
712 {
713 	struct iovec iov;
714 	struct msghdr msghdr;
715 	ssize_t len;
716 	char ch;
717 
718 	ch = 0;
719 	bzero(&msghdr, sizeof(msghdr));
720 
721 	iov.iov_base = &ch;
722 	iov.iov_len = sizeof(ch);
723 	msghdr.msg_control = cmsg;
724 	msghdr.msg_controllen = cmsgsz;
725 	msghdr.msg_iov = &iov;
726 	msghdr.msg_iovlen = 1;
727 
728 	len = recvmsg(sockfd, &msghdr, 0);
729 	ATF_REQUIRE_MSG(len != -1,
730 	    "recvmsg failed: %s", strerror(errno));
731 	ATF_REQUIRE_MSG(len == sizeof(ch),
732 	    "recvmsg: %zd bytes received; expected %zu", len, sizeof(ch));
733 	ATF_REQUIRE_MSG((msghdr.msg_flags & flags) == flags,
734 	    "recvmsg: got flags %#x; expected %#x", msghdr.msg_flags, flags);
735 }
736 
737 /*
738  * Test for PR 131876.  Receiver uses a control message buffer that is too
739  * small for the incoming SCM_RIGHTS message, so the message is truncated.
740  * The kernel must not leak the copied right into the receiver's namespace.
741  */
742 ATF_TC_WITHOUT_HEAD(truncated_rights);
743 ATF_TC_BODY(truncated_rights, tc)
744 {
745 	char *message;
746 	int fd[2], nfds, putfd, rc;
747 
748 	domainsocketpair(fd);
749 	devnull(&putfd);
750 	nfds = getnfds();
751 
752 	/*
753 	 * Case 1: Send a single descriptor and truncate the message.
754 	 */
755 	message = malloc(CMSG_SPACE(sizeof(int)));
756 	ATF_REQUIRE(message != NULL);
757 	putfds(message, putfd, 1);
758 	send_cmsg(fd[0], message, CMSG_LEN(sizeof(int)));
759 	recv_cmsg(fd[1], message, CMSG_LEN(0), MSG_CTRUNC);
760 	ATF_REQUIRE(getnfds() == nfds);
761 	free(message);
762 
763 	/*
764 	 * Case 2a: Send two descriptors in separate messages, and truncate at
765 	 *          the boundary between the two messages.  We should still
766 	 *          receive the first message.
767 	 */
768 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
769 	ATF_REQUIRE(message != NULL);
770 	putfds(message, putfd, 1);
771 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
772 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
773 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
774 	rc = close(*(int *)CMSG_DATA(message));
775 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
776 	ATF_REQUIRE(getnfds() == nfds);
777 	free(message);
778 
779 	/*
780 	 * Case 2b: Send two descriptors in separate messages, and truncate
781 	 *          before the end of the first message.
782 	 */
783 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
784 	ATF_REQUIRE(message != NULL);
785 	putfds(message, putfd, 1);
786 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
787 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
788 	recv_cmsg(fd[1], message, CMSG_SPACE(0), MSG_CTRUNC);
789 	ATF_REQUIRE(getnfds() == nfds);
790 	free(message);
791 
792 	/*
793 	 * Case 2c: Send two descriptors in separate messages, and truncate
794 	 *          after the end of the first message.  We should still
795 	 *          receive the first message.
796 	 */
797 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
798 	ATF_REQUIRE(message != NULL);
799 	putfds(message, putfd, 1);
800 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
801 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
802 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)) + CMSG_SPACE(0),
803 	    MSG_CTRUNC);
804 	rc = close(*(int *)CMSG_DATA(message));
805 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
806 	ATF_REQUIRE(getnfds() == nfds);
807 	free(message);
808 
809 	/*
810 	 * Case 3: Send three descriptors in the same message, and leave space
811 	 *         only for the first when receiving the message.
812 	 */
813 	message = malloc(CMSG_SPACE(sizeof(int) * 3));
814 	ATF_REQUIRE(message != NULL);
815 	putfds(message, putfd, 3);
816 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int) * 3));
817 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
818 	ATF_REQUIRE(getnfds() == nfds);
819 	free(message);
820 
821 	close(putfd);
822 	closesocketpair(fd);
823 }
824 
825 /*
826  * Ensure that an attempt to copy a SCM_RIGHTS message to the recipient
827  * fails.  In this case the kernel must dispose of the externalized rights
828  * rather than leaking them into the recipient's file descriptor table.
829  */
830 ATF_TC_WITHOUT_HEAD(copyout_rights_error);
831 ATF_TC_BODY(copyout_rights_error, tc)
832 {
833 	struct iovec iovec;
834 	struct msghdr msghdr;
835 	char buf[16];
836 	ssize_t len;
837 	int fd[2], error, nfds, putfd;
838 
839 	memset(buf, 0, sizeof(buf));
840 	domainsocketpair(fd);
841 	devnull(&putfd);
842 	nfds = getnfds();
843 
844 	len = sendfd_payload(fd[0], putfd, buf, sizeof(buf));
845 	ATF_REQUIRE_MSG(len != -1, "sendmsg failed: %s", strerror(errno));
846 
847 	bzero(&msghdr, sizeof(msghdr));
848 
849 	iovec.iov_base = buf;
850 	iovec.iov_len = sizeof(buf);
851 	msghdr.msg_control = (char *)-1; /* trigger EFAULT */
852 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
853 	msghdr.msg_iov = &iovec;
854 	msghdr.msg_iovlen = 1;
855 
856 	len = recvmsg(fd[1], &msghdr, 0);
857 	error = errno;
858 	ATF_REQUIRE_MSG(len == -1, "recvmsg succeeded: %zd", len);
859 	ATF_REQUIRE_MSG(errno == EFAULT, "expected EFAULT, got %d (%s)",
860 	    error, strerror(errno));
861 
862 	/* Verify that no FDs were leaked. */
863 	ATF_REQUIRE(getnfds() == nfds);
864 
865 	close(putfd);
866 	closesocketpair(fd);
867 }
868 
869 /*
870  * Verify that we can handle empty rights messages.
871  */
872 ATF_TC_WITHOUT_HEAD(empty_rights_message);
873 ATF_TC_BODY(empty_rights_message, tc)
874 {
875 	struct iovec iov;
876 	struct msghdr msghdr;
877 	struct cmsghdr cmsg;
878 	char *cm, message[CMSG_SPACE(0) + CMSG_SPACE(sizeof(int))];
879 	ssize_t len;
880 	int error, fd[2], putfd;
881 
882 	domainsocketpair(fd);
883 	devnull(&putfd);
884 
885 	memset(&msghdr, 0, sizeof(msghdr));
886 	iov.iov_base = NULL;
887 	iov.iov_len = 0;
888 	msghdr.msg_iov = &iov;
889 	msghdr.msg_iovlen = 1;
890 
891 	/*
892 	 * Try sending incorrect empty message.  On 64-bit platforms, where
893 	 * CMSG_SPACE(0) > sizeof(struct cmsghdr), this will exercise
894 	 * an edge case.
895 	 */
896 	cmsg = (struct cmsghdr ){
897 	    .cmsg_len = sizeof(struct cmsghdr),	/* not CMSG_LEN(0)! */
898 	    .cmsg_level = SOL_SOCKET,
899 	    .cmsg_type = SCM_RIGHTS,
900 	};
901 	msghdr.msg_control = &cmsg;
902 	msghdr.msg_controllen = CMSG_SPACE(0);
903 
904 	len = sendmsg(fd[0], &msghdr, 0);
905 	if (CMSG_LEN(0) != sizeof(struct cmsghdr))
906 		ATF_REQUIRE(len == -1 && errno == EINVAL);
907 	else
908 		ATF_REQUIRE(len == 0);
909 
910 	/*
911 	 * Try sending an empty message followed by a non-empty message.
912 	 */
913 	cm = message;
914 	putfds(cm, -1, 0);
915 	cm += CMSG_SPACE(0);
916 	putfds(cm, putfd, 1);
917 	msghdr.msg_control = message;
918 	msghdr.msg_controllen = sizeof(message);
919 
920 	len = sendmsg(fd[0], &msghdr, 0);
921 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
922 
923 	/* Only the non-empty message should be received. */
924 	len = recvmsg(fd[1], &msghdr, 0);
925 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
926 	ATF_REQUIRE(msghdr.msg_controllen == CMSG_SPACE(sizeof(int)));
927 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
928 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
929 
930 	/*
931 	 * Now try sending with the non-empty message before the empty message.
932 	 */
933 	cm = message;
934 	putfds(cm, putfd, 1);
935 	cm += CMSG_SPACE(sizeof(int));
936 	putfds(cm, -1, 0);
937 
938 	memset(&msghdr, 0, sizeof(msghdr));
939 	iov.iov_base = NULL;
940 	iov.iov_len = 0;
941 	msghdr.msg_control = message;
942 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
943 	msghdr.msg_iov = &iov;
944 	msghdr.msg_iovlen = 1;
945 
946 	len = sendmsg(fd[0], &msghdr, 0);
947 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
948 
949 	/* Only the non-empty message should be received. */
950 	len = recvmsg(fd[1], &msghdr, 0);
951 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
952 	ATF_REQUIRE(msghdr.msg_controllen == CMSG_SPACE(sizeof(int)));
953 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
954 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
955 
956 	(void)close(putfd);
957 }
958 
959 /*
960  * Check that sending control creates records in a stream socket, making it
961  * behave like a seqpacket socket.  If we stack several control+data writes
962  * on a stream socket, we won't be able to read them all at once, even if we
963  * provide a buffer large enough to receive all at once.
964  *
965  * XXXGL: adding MSG_WAITALL to the recvmsg() flags will make this test stuck.
966  */
967 ATF_TC_WITHOUT_HEAD(control_creates_records);
968 ATF_TC_BODY(control_creates_records, tc)
969 {
970 	int fd[2], putfd, getfd;
971 	char buf[2];
972 	ssize_t rlen;
973 
974 	domainsocketpair(fd);
975 	tempfile(&putfd);
976 
977 	for (int i = 1; i <= 2; i++)
978 		ATF_REQUIRE(sendfd_payload(fd[0], putfd, buf, 1) == 1);
979 	ATF_REQUIRE(close(putfd) == 0);
980 	for (int i = 1; i <= 2; i++) {
981 		rlen = recvfd_payload(fd[1], &getfd, buf, 2,
982 		    CMSG_SPACE(sizeof(int)) * 2, 0);
983 		ATF_REQUIRE_MSG(rlen == 1,
984 		    "recvmsg: %zd bytes received; expected 1", rlen);
985 		ATF_REQUIRE(close(getfd) == 0);
986 	}
987 	closesocketpair(fd);
988 }
989 
990 ATF_TP_ADD_TCS(tp)
991 {
992 
993 	ATF_TP_ADD_TC(tp, simple_send_fd);
994 	ATF_TP_ADD_TC(tp, simple_send_fd_msg_cmsg_cloexec);
995 	ATF_TP_ADD_TC(tp, send_and_close);
996 	ATF_TP_ADD_TC(tp, send_and_cancel);
997 	ATF_TP_ADD_TC(tp, send_and_shutdown);
998 	ATF_TP_ADD_TC(tp, send_a_lot);
999 	ATF_TP_ADD_TC(tp, send_overflow);
1000 	ATF_TP_ADD_TC(tp, two_files);
1001 	ATF_TP_ADD_TC(tp, bundle);
1002 	ATF_TP_ADD_TC(tp, bundle_cancel);
1003 	ATF_TP_ADD_TC(tp, devfs_orphan);
1004 	ATF_TP_ADD_TC(tp, rights_creds_payload);
1005 	ATF_TP_ADD_TC(tp, truncated_rights);
1006 	ATF_TP_ADD_TC(tp, copyout_rights_error);
1007 	ATF_TP_ADD_TC(tp, empty_rights_message);
1008 	ATF_TP_ADD_TC(tp, control_creates_records);
1009 
1010 	return (atf_no_error());
1011 }
1012