-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.go
72 lines (59 loc) · 1.2 KB
/
sender.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package transsocket
import (
"errors"
"net"
"syscall"
)
var (
errMismatchLen = errors.New("length of write data is mismatched")
errMismatchOOBLen = errors.New("length of oob data is mismatched")
errTooLargeData = errors.New("too large data")
)
type Sender struct {
conn *net.UnixConn
}
func NewSender() Sender {
return Sender{}
}
func (s *Sender) Connect() error {
c, err := net.Dial("unix", sockAddr)
if err != nil {
return err
}
s.conn = c.(*net.UnixConn)
return nil
}
func (s *Sender) Disconnect() error {
if s.conn == nil {
return nil
}
return s.conn.Close()
}
func (s *Sender) SendTCPFileDescriptor(c net.Conn) error {
return s.send(nil, c)
}
func (s *Sender) SendTCPFileDescriptorWithData(data []byte, c net.Conn) error {
if len(data) > dataLimit {
return errTooLargeData
}
return s.send(data, c)
}
func (s *Sender) send(d []byte, c net.Conn) error {
f, err := c.(*net.TCPConn).File()
if err != nil {
return err
}
rights := syscall.UnixRights(int(f.Fd()))
n, oobn, err := s.conn.WriteMsgUnix(d, rights, nil)
if err != nil {
return err
}
if n != len(d) {
return errMismatchLen
}
if oobn != len(rights) {
return errMismatchOOBLen
}
_ = f.Close()
return nil
}