/*
 * sendmsg SCM_RIGHTS: trigger net/sendfd path
 */

#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void)
{
	int sv[2];
	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0)
		return 1;

	int fd = open("/dev/null", O_RDONLY);
	if (fd < 0) {
		close(sv[0]);
		close(sv[1]);
		return 1;
	}

	/* Send fd over socket via SCM_RIGHTS */
	struct msghdr msg = {0};
	char buf[1] = {'x'};
	struct iovec iov = { .iov_base = buf, .iov_len = 1 };
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;

	char cmsg_buf[CMSG_SPACE(sizeof(int))];
	msg.msg_control = cmsg_buf;
	msg.msg_controllen = sizeof(cmsg_buf);
	struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
	cmsg->cmsg_level = SOL_SOCKET;
	cmsg->cmsg_type = SCM_RIGHTS;
	cmsg->cmsg_len = CMSG_LEN(sizeof(int));
	memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));

	sendmsg(sv[0], &msg, 0);

	close(fd);
	close(sv[0]);
	close(sv[1]);
	return 0;
}
