1 /* Smoke test for MSG_CMSG_CLOEXEC.
2 Copyright (C) 2021-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
19 #include <support/xunistd.h>
20 #include <support/check.h>
21 #include <sys/socket.h>
27 send_fd (int sockfd
, int fd
)
29 char data
[] = "hello";
30 struct iovec iov
= { .iov_base
= data
, .iov_len
= sizeof (data
) };
34 struct cmsghdr header
;
35 char bytes
[CMSG_SPACE (sizeof (fd
))];
42 .msg_control
= cmsg_storage
.bytes
,
43 .msg_controllen
= sizeof (cmsg_storage
)
46 memset (&cmsg_storage
, 0, sizeof (cmsg_storage
));
48 struct cmsghdr
*cmsg
= CMSG_FIRSTHDR (&msg
);
49 cmsg
->cmsg_level
= SOL_SOCKET
;
50 cmsg
->cmsg_type
= SCM_RIGHTS
;
51 cmsg
->cmsg_len
= CMSG_LEN (sizeof (fd
));
52 memcpy (CMSG_DATA (cmsg
), &fd
, sizeof (fd
));
54 ssize_t nsent
= sendmsg (sockfd
, &msg
, 0);
56 FAIL_EXIT1 ("sendmsg (%d): %m", sockfd
);
57 TEST_COMPARE (nsent
, sizeof (data
));
61 recv_fd (int sockfd
, int flags
)
64 struct iovec iov
= { .iov_base
= buffer
, .iov_len
= sizeof (buffer
) };
68 struct cmsghdr header
;
76 .msg_control
= cmsg_storage
.bytes
,
77 .msg_controllen
= sizeof (cmsg_storage
)
80 ssize_t nrecv
= recvmsg (sockfd
, &msg
, flags
);
82 FAIL_EXIT1 ("recvmsg (%d): %m", sockfd
);
84 TEST_COMPARE (msg
.msg_controllen
, CMSG_SPACE (sizeof (int)));
85 struct cmsghdr
*cmsg
= CMSG_FIRSTHDR (&msg
);
86 TEST_COMPARE (cmsg
->cmsg_level
, SOL_SOCKET
);
87 TEST_COMPARE (cmsg
->cmsg_type
, SCM_RIGHTS
);
88 TEST_COMPARE (cmsg
->cmsg_len
, CMSG_LEN (sizeof (int)));
91 memcpy (&fd
, CMSG_DATA (cmsg
), sizeof (fd
));
101 int rc
= socketpair (AF_UNIX
, SOCK_DGRAM
| SOCK_CLOEXEC
, 0, sockfd
);
103 FAIL_EXIT1 ("socketpair: %m");
105 send_fd (sockfd
[1], STDIN_FILENO
);
106 newfd
= recv_fd (sockfd
[0], 0);
107 TEST_VERIFY_EXIT (newfd
> 0);
108 flags
= fcntl (newfd
, F_GETFD
, 0);
109 TEST_VERIFY_EXIT (flags
!= -1);
110 TEST_VERIFY (!(flags
& FD_CLOEXEC
));
113 send_fd (sockfd
[1], STDIN_FILENO
);
114 newfd
= recv_fd (sockfd
[0], MSG_CMSG_CLOEXEC
);
115 TEST_VERIFY_EXIT (newfd
> 0);
116 flags
= fcntl (newfd
, F_GETFD
, 0);
117 TEST_VERIFY_EXIT (flags
!= -1);
118 TEST_VERIFY (flags
& FD_CLOEXEC
);
126 #include <support/test-driver.c>