/* DF-2715: kernel-internal MSG_FNONBLOCKING (0x00020000, sys/socket.h:399)
 * leaks into the user-visible msg_flags word of recvmsg(2) when the socket
 * is non-blocking.  kern_recvmsg ORs the force-flag into its local `flags`
 * (uipc_syscalls.c:996-1001) and sys_recvmsg later copyout()s that local
 * over the user msghdr.msg_flags (uipc_syscalls.c:1190) with nothing
 * stripping the kernel-only bits.  POSIX reserves msg_flags for
 * MSG_TRUNC/MSG_CTRUNC/... output status. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MSG_FNONBLOCKING 0x00020000

int main(void)
{
	struct sockaddr_in sin;
	struct msghdr msg;
	struct iovec iov;
	char buf[64];
	int s, r;

	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0) { perror("socket"); return 1; }
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(31339);
	sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	if (bind(s, (struct sockaddr*)&sin, sizeof(sin)) != 0) { perror("bind"); return 1; }
	if (fcntl(s, F_SETFL, O_NONBLOCK) != 0) { perror("fcntl"); return 1; }

	if (sendto(s, "df2715", 6, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
		perror("sendto"); return 1;
	}
	sleep(1);

	memset(&msg, 0, sizeof(msg));
	iov.iov_base = buf; iov.iov_len = sizeof(buf);
	msg.msg_iov = &iov; msg.msg_iovlen = 1;

	r = recvmsg(s, &msg, 0);
	printf("[*] recvmsg on O_NONBLOCK socket with data queued: r=%d errno=%d\n",
	    r, r < 0 ? errno : 0);
	printf("[*] msg_flags = 0x%08x\n", msg.msg_flags);
	printf("[%c] MSG_FNONBLOCKING (0x20000) %s user-visible msg_flags\n",
	    (msg.msg_flags & MSG_FNONBLOCKING) ? '+' : '-',
	    (msg.msg_flags & MSG_FNONBLOCKING) ? "LEAKED into" : "absent from");
	return (msg.msg_flags & MSG_FNONBLOCKING) ? 0 : 1;
}
