1
2
3
4
5 package ipv4
6
7 import (
8 "net"
9
10 "golang.org/x/net/internal/socket"
11 )
12
13
14
15
16
17 type packetHandler struct {
18 *net.IPConn
19 *socket.Conn
20 rawOpt
21 }
22
23 func (c *packetHandler) ok() bool { return c != nil && c.IPConn != nil && c.Conn != nil }
24
25
26
27
28 func (c *packetHandler) ReadFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) {
29 if !c.ok() {
30 return nil, nil, nil, errInvalidConn
31 }
32 c.rawOpt.RLock()
33 m := socket.Message{
34 Buffers: [][]byte{b},
35 OOB: NewControlMessage(c.rawOpt.cflags),
36 }
37 c.rawOpt.RUnlock()
38 if err := c.RecvMsg(&m, 0); err != nil {
39 return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err}
40 }
41 var hs []byte
42 if hs, p, err = slicePacket(b[:m.N]); err != nil {
43 return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err}
44 }
45 if h, err = ParseHeader(hs); err != nil {
46 return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err}
47 }
48 if m.NN > 0 {
49 if compatFreeBSD32 {
50 adjustFreeBSD32(&m)
51 }
52 cm = new(ControlMessage)
53 if err := cm.Parse(m.OOB[:m.NN]); err != nil {
54 return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err}
55 }
56 }
57 if src, ok := m.Addr.(*net.IPAddr); ok && cm != nil {
58 cm.Src = src.IP
59 }
60 return
61 }
62
63 func slicePacket(b []byte) (h, p []byte, err error) {
64 if len(b) < HeaderLen {
65 return nil, nil, errHeaderTooShort
66 }
67 hdrlen := int(b[0]&0x0f) << 2
68 return b[:hdrlen], b[hdrlen:], nil
69 }
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 func (c *packetHandler) WriteTo(h *Header, p []byte, cm *ControlMessage) error {
92 if !c.ok() {
93 return errInvalidConn
94 }
95 m := socket.Message{
96 OOB: cm.Marshal(),
97 }
98 wh, err := h.Marshal()
99 if err != nil {
100 return err
101 }
102 m.Buffers = [][]byte{wh, p}
103 dst := new(net.IPAddr)
104 if cm != nil {
105 if ip := cm.Dst.To4(); ip != nil {
106 dst.IP = ip
107 }
108 }
109 if dst.IP == nil {
110 dst.IP = h.Dst
111 }
112 m.Addr = dst
113 if err := c.SendMsg(&m, 0); err != nil {
114 return &net.OpError{Op: "write", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Addr: opAddr(dst), Err: err}
115 }
116 return nil
117 }
118
View as plain text