Merge pull request #662 from smcv/cmsg

Ensure correct alignment when dealing with control messages
This commit is contained in:
Simon McVittie
2024-10-18 13:35:42 +01:00
committed by GitHub

20
utils.c
View File

@@ -759,9 +759,9 @@ send_pid_on_socket (int sockfd)
struct msghdr msg = {}; struct msghdr msg = {};
struct iovec iov = { buf, sizeof (buf) }; struct iovec iov = { buf, sizeof (buf) };
const ssize_t control_len_snd = CMSG_SPACE(sizeof(struct ucred)); const ssize_t control_len_snd = CMSG_SPACE(sizeof(struct ucred));
char control_buf_snd[control_len_snd]; _Alignas(struct cmsghdr) char control_buf_snd[control_len_snd];
struct cmsghdr *cmsg; struct cmsghdr *cmsg;
struct ucred *cred; struct ucred cred;
msg.msg_iov = &iov; msg.msg_iov = &iov;
msg.msg_iovlen = 1; msg.msg_iovlen = 1;
@@ -772,11 +772,11 @@ send_pid_on_socket (int sockfd)
cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS; cmsg->cmsg_type = SCM_CREDENTIALS;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred)); cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
cred = (struct ucred *)CMSG_DATA(cmsg);
cred->pid = getpid (); cred.pid = getpid ();
cred->uid = geteuid (); cred.uid = geteuid ();
cred->gid = getegid (); cred.gid = getegid ();
memcpy (CMSG_DATA (cmsg), &cred, sizeof (cred));
if (TEMP_FAILURE_RETRY (sendmsg (sockfd, &msg, 0)) < 0) if (TEMP_FAILURE_RETRY (sendmsg (sockfd, &msg, 0)) < 0)
die_with_error ("Can't send pid"); die_with_error ("Can't send pid");
@@ -801,7 +801,7 @@ read_pid_from_socket (int sockfd)
struct msghdr msg = {}; struct msghdr msg = {};
struct iovec iov = { recv_buf, sizeof (recv_buf) }; struct iovec iov = { recv_buf, sizeof (recv_buf) };
const ssize_t control_len_rcv = CMSG_SPACE(sizeof(struct ucred)); const ssize_t control_len_rcv = CMSG_SPACE(sizeof(struct ucred));
char control_buf_rcv[control_len_rcv]; _Alignas(struct cmsghdr) char control_buf_rcv[control_len_rcv];
struct cmsghdr* cmsg; struct cmsghdr* cmsg;
msg.msg_iov = &iov; msg.msg_iov = &iov;
@@ -822,8 +822,10 @@ read_pid_from_socket (int sockfd)
cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_type == SCM_CREDENTIALS &&
payload_len == sizeof(struct ucred)) payload_len == sizeof(struct ucred))
{ {
struct ucred *cred = (struct ucred *)CMSG_DATA(cmsg); struct ucred cred;
return cred->pid;
memcpy (&cred, CMSG_DATA (cmsg), sizeof (cred));
return cred.pid;
} }
} }
die ("No pid returned on socket"); die ("No pid returned on socket");