From: David Goulet Date: Tue, 4 Oct 2011 21:49:27 +0000 (-0400) Subject: Add recv fds function to lttng-comm API X-Git-Tag: v2.0-pre15~194 X-Git-Url: https://git.lttng.org./?a=commitdiff_plain;h=09de5c68e74f5af62744ead1516d95bb823038db;p=lttng-tools.git Add recv fds function to lttng-comm API Signed-off-by: David Goulet --- diff --git a/include/lttng-sessiond-comm.h b/include/lttng-sessiond-comm.h index f8308505c..fcdc5a2cf 100644 --- a/include/lttng-sessiond-comm.h +++ b/include/lttng-sessiond-comm.h @@ -248,6 +248,9 @@ extern int lttcomm_close_unix_sock(int sock); /* Send fd(s) over a unix socket. */ extern ssize_t lttcomm_send_fds_unix_sock(int sock, void *buf, int *fds, size_t nb_fd, size_t len); +/* Recv fd(s) over a unix socket */ +extern ssize_t lttcomm_recv_fds_unix_sock(int sock, void *buf, int *fds, + size_t nb_fd, size_t len); extern ssize_t lttcomm_recv_unix_sock(int sock, void *buf, size_t len); extern ssize_t lttcomm_send_unix_sock(int sock, void *buf, size_t len); extern const char *lttcomm_get_readable_code(enum lttcomm_return_code code); diff --git a/liblttng-sessiond-comm/lttng-sessiond-comm.c b/liblttng-sessiond-comm/lttng-sessiond-comm.c index 3c066cd3b..ff78891aa 100644 --- a/liblttng-sessiond-comm/lttng-sessiond-comm.c +++ b/liblttng-sessiond-comm/lttng-sessiond-comm.c @@ -343,3 +343,65 @@ ssize_t lttcomm_send_fds_unix_sock(int sock, void *buf, int *fds, size_t nb_fd, return ret; } + +/* + * Receives a single fd from socket. + * + * Returns the size of received data + */ +ssize_t lttcomm_recv_fds_unix_sock(int sock, void *buf, int *fds, + size_t nb_fd, size_t len) +{ + struct iovec iov[1]; + int data_fd, i, ret = 0; + struct cmsghdr *cmsg; + char recv_fd[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = { 0 }; + union { + unsigned char vc[4]; + int vi; + } tmp; + + /* Prepare to receive the structures */ + iov[0].iov_base = &data_fd; + iov[0].iov_len = sizeof(data_fd); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = recv_fd; + msg.msg_controllen = sizeof(recv_fd); + + ret = recvmsg(sock, &msg, 0); + if (ret < 0) { + perror("recvmsg fds"); + goto end; + } + + if (ret != sizeof(data_fd)) { + fprintf(stderr, "Error: Received %d bytes, expected %ld", + ret, sizeof(data_fd)); + goto end; + } + + cmsg = CMSG_FIRSTHDR(&msg); + if (!cmsg) { + fprintf(stderr, "Error: Invalid control message header"); + ret = -1; + goto end; + } + + if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { + fprintf(stderr, "Didn't received any fd"); + ret = -1; + goto end; + } + + /* this is our fd */ + for (i = 0; i < sizeof(int); i++) { + tmp.vc[i] = CMSG_DATA(cmsg)[i]; + } + + ret = tmp.vi; + +end: + return ret; +}