-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
109 lines (99 loc) · 2.52 KB
/
conn.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"errors"
"net"
"time"
)
var zeroLenByteArr = make([]byte, 0, 0)
type onNewConnCallback func(network network, ip net.IP, port int, data []byte) []byte
type networkConn interface {
bind(network network, ip net.IP, port int) error
unbind()
}
func newConn(callback onNewConnCallback, datagramSize uint) networkConn {
return &netConn{
callback: callback,
datagramSize: datagramSize,
isClosed: false,
deadline: 2 * time.Second,
listener: nil,
}
}
type netConn struct {
callback onNewConnCallback
datagramSize uint
isClosed bool
deadline time.Duration
listener net.Listener
}
func (n *netConn) bind(network network, ip net.IP, port int) error {
listener, err := listen(network, ip, port, n.datagramSize)
if err != nil {
log.Warning("Failed to bind to TCP port.", port, err)
return err
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
log.Debug("Failed to accept an incoming TCP connection.", err)
if !n.isClosed {
continue
}
break
}
remoteIp, err := getRemoteIp(conn.RemoteAddr())
if err != nil {
log.Error("Cannot get remote address.")
break
}
err = conn.SetDeadline(time.Now().Add(n.deadline))
if err != nil {
log.Debug("Failed to set connection deadline.")
}
buf := make([]byte, n.datagramSize)
readBytesCount, err := conn.Read(buf)
if err != nil {
log.Debug("Error while reading data.", err)
continue
}
if readBytesCount != int(n.datagramSize) {
log.Debug("Received data of unexpected length.", readBytesCount)
continue
}
bytesToSend := n.callback(network, remoteIp, port, buf)
if bytesToSend != nil {
writtenBytesCount, err := conn.Write(bytesToSend)
if writtenBytesCount != len(bytesToSend) {
log.Debug("Could not send all bytes. Sending will not be resumed.")
}
if err != nil {
log.Debug("Failed to write to an incoming TCP connection.", err)
}
}
err = conn.Close()
if err != nil {
log.Debug("Failed to close an incoming TCP connection.", err)
}
}
}()
return nil
}
func getRemoteIp(addr net.Addr) (net.IP, error) {
if tcpAddr, ok := addr.(*net.TCPAddr); ok {
return tcpAddr.IP, nil
} else if udpAddr, ok := addr.(*net.UDPAddr); ok {
return udpAddr.IP, nil
} else {
return nil, errors.New("unknown address type")
}
}
func (n *netConn) unbind() {
if n.listener == nil {
return
}
n.isClosed = true
if err := n.listener.Close(); err != nil {
log.Debug("Error while closing a connection.", err)
}
}