Better logging in recv_fds

This commit is contained in:
topjohnwu 2023-10-31 17:40:59 -07:00
parent 19a4e11645
commit a177846044

View File

@ -73,13 +73,27 @@ static void *recv_fds(int sockfd, char *cmsgbuf, size_t bufsz, int cnt) {
}; };
xrecvmsg(sockfd, &msg, MSG_WAITALL); xrecvmsg(sockfd, &msg, MSG_WAITALL);
cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (msg.msg_controllen != bufsz) {
LOGE("recv_fd: msg_flags = %d, msg_controllen(%zu) != %zu\n",
msg.msg_flags, msg.msg_controllen, bufsz);
return nullptr;
}
if (msg.msg_controllen != bufsz || cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg == nullptr || if (cmsg == nullptr) {
cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt) || LOGE("recv_fd: cmsg == nullptr\n");
cmsg->cmsg_level != SOL_SOCKET || return nullptr;
cmsg->cmsg_type != SCM_RIGHTS) { }
if (cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt)) {
LOGE("recv_fd: cmsg_len(%zu) != %zu\n", cmsg->cmsg_len, CMSG_LEN(sizeof(int) * cnt));
return nullptr;
}
if (cmsg->cmsg_level != SOL_SOCKET) {
LOGE("recv_fd: cmsg_level != SOL_SOCKET\n");
return nullptr;
}
if (cmsg->cmsg_type != SCM_RIGHTS) {
LOGE("recv_fd: cmsg_type != SCM_RIGHTS\n");
return nullptr; return nullptr;
} }
@ -92,8 +106,11 @@ vector<int> recv_fds(int sockfd) {
// Peek fd count to allocate proper buffer // Peek fd count to allocate proper buffer
int cnt; int cnt;
recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK);
if (cnt == 0) if (cnt == 0) {
// Consume data
recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL);
return results; return results;
}
vector<char> cmsgbuf; vector<char> cmsgbuf;
cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt));
@ -109,6 +126,15 @@ vector<int> recv_fds(int sockfd) {
} }
int recv_fd(int sockfd) { int recv_fd(int sockfd) {
// Peek fd count
int cnt;
recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK);
if (cnt == 0) {
// Consume data
recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL);
return -1;
}
char cmsgbuf[CMSG_SPACE(sizeof(int))]; char cmsgbuf[CMSG_SPACE(sizeof(int))];
void *data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1); void *data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1);