1// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
6// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos
7
8// Socket control messages
9
10package unix
11
12import (
13	"unsafe"
14)
15
16// CmsgLen returns the value to store in the Len field of the Cmsghdr
17// structure, taking into account any necessary alignment.
18func CmsgLen(datalen int) int {
19	return cmsgAlignOf(SizeofCmsghdr) + datalen
20}
21
22// CmsgSpace returns the number of bytes an ancillary element with
23// payload of the passed data length occupies.
24func CmsgSpace(datalen int) int {
25	return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf(datalen)
26}
27
28func (h *Cmsghdr) data(offset uintptr) unsafe.Pointer {
29	return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr)) + offset)
30}
31
32// SocketControlMessage represents a socket control message.
33type SocketControlMessage struct {
34	Header Cmsghdr
35	Data   []byte
36}
37
38// ParseSocketControlMessage parses b as an array of socket control
39// messages.
40func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error) {
41	var msgs []SocketControlMessage
42	i := 0
43	for i+CmsgLen(0) <= len(b) {
44		h, dbuf, err := socketControlMessageHeaderAndData(b[i:])
45		if err != nil {
46			return nil, err
47		}
48		m := SocketControlMessage{Header: *h, Data: dbuf}
49		msgs = append(msgs, m)
50		i += cmsgAlignOf(int(h.Len))
51	}
52	return msgs, nil
53}
54
55func socketControlMessageHeaderAndData(b []byte) (*Cmsghdr, []byte, error) {
56	h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
57	if h.Len < SizeofCmsghdr || uint64(h.Len) > uint64(len(b)) {
58		return nil, nil, EINVAL
59	}
60	return h, b[cmsgAlignOf(SizeofCmsghdr):h.Len], nil
61}
62
63// UnixRights encodes a set of open file descriptors into a socket
64// control message for sending to another process.
65func UnixRights(fds ...int) []byte {
66	datalen := len(fds) * 4
67	b := make([]byte, CmsgSpace(datalen))
68	h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
69	h.Level = SOL_SOCKET
70	h.Type = SCM_RIGHTS
71	h.SetLen(CmsgLen(datalen))
72	for i, fd := range fds {
73		*(*int32)(h.data(4 * uintptr(i))) = int32(fd)
74	}
75	return b
76}
77
78// ParseUnixRights decodes a socket control message that contains an
79// integer array of open file descriptors from another process.
80func ParseUnixRights(m *SocketControlMessage) ([]int, error) {
81	if m.Header.Level != SOL_SOCKET {
82		return nil, EINVAL
83	}
84	if m.Header.Type != SCM_RIGHTS {
85		return nil, EINVAL
86	}
87	fds := make([]int, len(m.Data)>>2)
88	for i, j := 0, 0; i < len(m.Data); i += 4 {
89		fds[j] = int(*(*int32)(unsafe.Pointer(&m.Data[i])))
90		j++
91	}
92	return fds, nil
93}
94