1
2
3
4
5
6
7
8
9
10 package unix
11
12 import (
13 "unsafe"
14 )
15
16
17
18 func CmsgLen(datalen int) int {
19 return cmsgAlignOf(SizeofCmsghdr) + datalen
20 }
21
22
23
24 func CmsgSpace(datalen int) int {
25 return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf(datalen)
26 }
27
28 func (h *Cmsghdr) data(offset uintptr) unsafe.Pointer {
29 return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr)) + offset)
30 }
31
32
33 type SocketControlMessage struct {
34 Header Cmsghdr
35 Data []byte
36 }
37
38
39
40 func 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
55 func 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
64
65 func 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
79
80 func 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
View as plain text