| 1 |
/* |
| 2 |
* Utility to send fds via Unix domain socket |
| 3 |
* |
| 4 |
* Copyright 2011, 2018 Yuya Nishihara <[email protected]> |
| 5 |
* |
| 6 |
* This software may be used and distributed according to the terms of the |
| 7 |
* GNU General Public License version 2 or any later version. |
| 8 |
*/ |
| 9 |
|
| 10 |
#include <errno.h> |
| 11 |
#include <stdlib.h> |
| 12 |
#include <string.h> |
| 13 |
#include <sys/socket.h> |
| 14 |
#include <sys/types.h> |
| 15 |
|
| 16 |
#define MAX_FD_LEN 10 |
| 17 |
|
| 18 |
/* |
| 19 |
* Sends the given fds with 1-byte dummy payload. |
| 20 |
* |
| 21 |
* Returns the number of bytes sent on success, -1 on error and errno is set |
| 22 |
* appropriately. |
| 23 |
*/ |
| 24 |
ssize_t sendfds(int sockfd, const int *fds, size_t fdlen) |
| 25 |
{ |
| 26 |
char dummy[1] = {0}; |
| 27 |
struct iovec iov = {dummy, sizeof(dummy)}; |
| 28 |
char fdbuf[CMSG_SPACE(sizeof(fds[0]) * MAX_FD_LEN)]; |
| 29 |
struct msghdr msgh; |
| 30 |
struct cmsghdr *cmsg; |
| 31 |
|
| 32 |
/* just use a fixed-size buffer since we'll never send tons of fds */ |
| 33 |
if (fdlen > MAX_FD_LEN) { |
| 34 |
errno = EINVAL; |
| 35 |
return -1; |
| 36 |
} |
| 37 |
|
| 38 |
memset(&msgh, 0, sizeof(msgh)); |
| 39 |
msgh.msg_iov = &iov; |
| 40 |
msgh.msg_iovlen = 1; |
| 41 |
msgh.msg_control = fdbuf; |
| 42 |
msgh.msg_controllen = CMSG_SPACE(sizeof(fds[0]) * fdlen); |
| 43 |
|
| 44 |
cmsg = CMSG_FIRSTHDR(&msgh); |
| 45 |
cmsg->cmsg_level = SOL_SOCKET; |
| 46 |
cmsg->cmsg_type = SCM_RIGHTS; |
| 47 |
cmsg->cmsg_len = CMSG_LEN(sizeof(fds[0]) * fdlen); |
| 48 |
memcpy(CMSG_DATA(cmsg), fds, sizeof(fds[0]) * fdlen); |
| 49 |
msgh.msg_controllen = cmsg->cmsg_len; |
| 50 |
return sendmsg(sockfd, &msgh, 0); |
| 51 |
} |