(5) unix socket sendmsg message returns permission error (EPERM)

Unix socket sendmsg message returns permission error

Author:onceday date:August 16, 2023

Resolve an error scenario with unix socket sendmsg on linux devices .

1. Question

There is a UDP-like transport for unix sockets, the datagram service. This socket can have a peer set or not. as follows:

  • socket(), creates a socket, which is the basis of all socket operations.
  • bind(), for unix sockets, this binds a string address.
  • connect(), for unix datagram sockets, the peer can also be bound.

Generally, for datagram sockets, only the first two steps are required, because datagrams are stateless connections, each message is independent, and there is no additional state maintenance process .

If we use sendmsg to send a message at this time, but the return permission is not allowed error (1), and the message received is correct, that is, the peer can send a message to this socket, but we cannot reply to the message, then there is It is very likely that the peer socket has performed a connect operation.

The following is part of the code in the function af_unix.cin the source code unix_dgram_sendmsg, that is, the actual calling function at the bottom of the sendmsg function :

err = -EPERM;
if (!unix_may_send(sk, other))
    goto out_unlock;

There is a judgment here. If it is not satisfied, exit directly. Obviously, the return permission error is related to this judgment.

static inline int unix_our_peer(struct sock *sk, struct sock *osk)
{
	return unix_peer(osk) == sk;
}

static inline int unix_may_send(struct sock *sk, struct sock *osk)
{
	return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
}

As above, it can be seen from this function that it determines whether the destination socket sent has a peer, and whether the peer of the destination socket is the local socket. Verification can pass only if the destination socket has no peer address (no connectoperation) orconnect the object is the local end , otherwise a permission error will be returned.

2. Conclusion

EPERMThe above analysis shows that if the unix datagram socket wants to achieve many-to-many free sending, it must give up the connect operation, otherwise it will encounter errors when sending .

Guess you like

Origin blog.csdn.net/Once_day/article/details/132330977