-
Notifications
You must be signed in to change notification settings - Fork 51
/
afinetrawsocket.go
86 lines (74 loc) · 2.59 KB
/
afinetrawsocket.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// +build linux
package afinetrawsocket
import (
"fmt"
"syscall"
)
type rawsocket struct {
fd int
insock *syscall.SockaddrInet4
}
const (
// RawSocketMark is the mark asserted on all packet sent out of this socket
RawSocketMark = 0x63
// NetworkRawSocketMark is the mark on packet egressing
//the raw socket coming in from network
NetworkRawSocketMark = 0x40000063
//ApplicationRawSocketMark is the mark on packet egressing
//the raw socket coming from application
ApplicationRawSocketMark = 0x40000062
)
// SocketWriter interface exposes an interface to write and close sockets
type SocketWriter interface {
WriteSocket(buf []byte) error
CloseSocket() error
}
// CreateSocket returns a handle to SocketWriter interface
func CreateSocket(mark int, deviceName string) (SocketWriter, error) {
fd, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_MARK, mark); err != nil {
syscall.Close(fd) // nolint
return nil, fmt.Errorf("Received error %s while setting socket Option SO_MARK", err)
}
if err := syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1); err != nil {
syscall.Close(fd) // nolint
return nil, fmt.Errorf("Received error %s while setting socket Option IP_HDRINCL", err)
}
insock := &syscall.SockaddrInet4{
Port: 0,
}
// TODO: Make this a const
NfnlBuffSize := (75 * 1024)
sockrcvbuf := 500 * int(NfnlBuffSize)
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, sockrcvbuf); err != nil {
syscall.Close(fd) // nolint
return nil, fmt.Errorf("Received error %s while setting socket Option SO_RCVBUF", err)
}
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, sockrcvbuf); err != nil {
syscall.Close(fd) // nolint
return nil, fmt.Errorf("Received error %s while setting socket Option SO_SNDBUF", err)
}
lingerconf := &syscall.Linger{
Onoff: 1,
Linger: 0,
}
if err := syscall.SetsockoptLinger(fd, syscall.SOL_SOCKET, syscall.SO_LINGER, lingerconf); err != nil {
syscall.Close(fd) // nolint
return nil, fmt.Errorf("Received error %s while setting socket Option SO_SNDBUF", err)
}
return &rawsocket{
fd: fd,
insock: insock,
}, nil
}
func (sock *rawsocket) WriteSocket(buf []byte) error {
//This is an IP frame dest address at byte[16]
copy(sock.insock.Addr[:], buf[16:])
if err := syscall.Sendto(sock.fd, buf[:], 0, sock.insock); err != nil {
return fmt.Errorf("received error %s while sending to socket", err)
}
return nil
}
func (sock *rawsocket) CloseSocket() error {
return syscall.Close(sock.fd)
}