Skip to content

Commit

Permalink
Merge pull request #662 from smcv/cmsg
Browse files Browse the repository at this point in the history
Ensure correct alignment when dealing with control messages
  • Loading branch information
smcv authored Oct 18, 2024
2 parents 759517f + 1fd7c38 commit 0545e72
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -759,9 +759,9 @@ send_pid_on_socket (int sockfd)
struct msghdr msg = {};
struct iovec iov = { buf, sizeof (buf) };
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 ucred *cred;
struct ucred cred;

msg.msg_iov = &iov;
msg.msg_iovlen = 1;
Expand All @@ -772,11 +772,11 @@ send_pid_on_socket (int sockfd)
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
cred = (struct ucred *)CMSG_DATA(cmsg);

cred->pid = getpid ();
cred->uid = geteuid ();
cred->gid = getegid ();
cred.pid = getpid ();
cred.uid = geteuid ();
cred.gid = getegid ();
memcpy (CMSG_DATA (cmsg), &cred, sizeof (cred));

if (TEMP_FAILURE_RETRY (sendmsg (sockfd, &msg, 0)) < 0)
die_with_error ("Can't send pid");
Expand All @@ -801,7 +801,7 @@ read_pid_from_socket (int sockfd)
struct msghdr msg = {};
struct iovec iov = { recv_buf, sizeof (recv_buf) };
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;

msg.msg_iov = &iov;
Expand All @@ -822,8 +822,10 @@ read_pid_from_socket (int sockfd)
cmsg->cmsg_type == SCM_CREDENTIALS &&
payload_len == sizeof(struct ucred))
{
struct ucred *cred = (struct ucred *)CMSG_DATA(cmsg);
return cred->pid;
struct ucred cred;

memcpy (&cred, CMSG_DATA (cmsg), sizeof (cred));
return cred.pid;
}
}
die ("No pid returned on socket");
Expand Down

0 comments on commit 0545e72

Please sign in to comment.