1

In the unix(7) man page for Unix domain sockets, it says that sendmsg can be used with the SCM_RIGHTS flag to send file descriptors over these sockets. Is this supported in Go? Is there any good example code out there showing how it's done?

It appears that there is a Msghdr structure declared in the syscall package. But no functions take it. Maybe I have to use the raw system call interface?

1 Answer 1

6

There's a package that does it here: https://github.com/ftrvxmtrx/fd/blob/master/fd.go. However that's using the Syscall package to achieve it. I'm not sure if there's a way to do this with Go standard library API.

In the syscall package, the things to look at are UnixRights, ParseUnixRights, and ParseSocketControlMessage. These can be used in conjunction with Readmsg and Sendmsg to send file descriptors over AF_UNIX sockets.

The basic structure goes something like this for receiving:

buf := make([]byte, syscall.CmsgSpace(<number of file descriptors expected> * 4))
_, _, _, _, err = syscall.Recvmsg(socket, nil, buf, 0)
if err != nil {
    panic(err)
}
var msgs []syscall.SocketControlMessage
msgs, err = syscall.ParseSocketControlMessage(buf)
var allfds []int
for i := 0, i < len(msgs) && err == null; i++ {
    var msgfds []int
    msgfds, err = syscall.ParseUnixRights(&msgs[i])
    append(allfds, msgfds...)
}

And for sending, it's much simpler (var fds []int):

rights := syscall.UnixRights(fds...)
err := syscall.Sendmsg(socket, nil, rights, nil, 0)
Sign up to request clarification or add additional context in comments.

2 Comments

That's good enough for me. This whole thing I'm working on is extremely Linux specific. I've even had to fight a bit to keep it from being x86_64 specific. This UnixRights thing is just the ticket. It should work on anything that implements the Posix API that allows this sort of thing.
If you don't mind, I'm going to edit the real answer into your answer. Who knows if that code you link to will be there forever?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.