MCPcopy Create free account
hub / github.com/MhmRdd/NoHello / sendfd

Function sendfd

module/src/main/cpp/utils.cpp:197–247  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

195}
196
197static int sendfd(int sockfd, int fd) {
198 int data;
199 struct iovec iov{};
200 struct msghdr msgh{};
201 struct cmsghdr *cmsgp;
202
203 /* Allocate a char array of suitable size to hold the ancillary data.
204 However, since this buffer is in reality a 'struct cmsghdr', use a
205 union to ensure that it is suitably aligned. */
206 union {
207 char buf[CMSG_SPACE(sizeof(int))];
208 /* Space large enough to hold an 'int' */
209 struct cmsghdr align;
210 } controlMsg{};
211
212 /* The 'msg_name' field can be used to specify the address of the
213 destination socket when sending a datagram. However, we do not
214 need to use this field because 'sockfd' is a connected socket. */
215
216 msgh.msg_name = nullptr;
217 msgh.msg_namelen = 0;
218
219 /* On Linux, we must transmit at least one byte of real data in
220 order to send ancillary data. We transmit an arbitrary integer
221 whose value is ignored by recvfd(). */
222
223 msgh.msg_iov = &iov;
224 msgh.msg_iovlen = 1;
225 iov.iov_base = &data;
226 iov.iov_len = sizeof(int);
227 data = 12345;
228
229 /* Set 'msghdr' fields that describe ancillary data */
230
231 msgh.msg_control = controlMsg.buf;
232 msgh.msg_controllen = sizeof(controlMsg.buf);
233
234 /* Set up ancillary data describing file descriptor to send */
235
236 cmsgp = reinterpret_cast<cmsghdr *>(msgh.msg_control);
237 cmsgp->cmsg_level = SOL_SOCKET;
238 cmsgp->cmsg_type = SCM_RIGHTS;
239 cmsgp->cmsg_len = CMSG_LEN(sizeof(int));
240 memcpy(CMSG_DATA(cmsgp), &fd, sizeof(int));
241
242 /* Send real plus ancillary data */
243
244 if (sendmsg(sockfd, &msgh, 0) == -1) return -1;
245
246 return 0;
247}
248
249static int recvfd(int sockfd) {
250 int data, fd;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected