-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.go
254 lines (217 loc) · 6.54 KB
/
socket.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package bifrost
import (
"bytes"
"encoding/binary"
"fmt"
"math/rand"
"net"
"strconv"
"strings"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/emef/bitfield"
)
// Socket is the core connectivity object that listens for packets and sends them
// out
type Socket struct {
listenAddr *net.UDPAddr
listenConn *net.UDPConn
remoteAddr *net.UDPAddr
bufSize int
Inbound chan *Packet
Outbound chan *Packet
Events chan *Event
timeout time.Duration
pIdentifier []byte
wg *sync.WaitGroup
cm *connectionManager
packetloss int
}
// NewSocket creates and returns a new Socket
func NewSocket(ip string, remote string, rPort int, bufSize int, pIdentifier []byte, timeOut int, lPort int) *Socket {
if len(ip) <= 0 {
log.Fatal("Invalid string for IP passed to NewSocket")
}
addrString := fmt.Sprintf("%s:%d", ip, lPort)
listenAddr, err := net.ResolveUDPAddr("udp", addrString)
if err != nil {
log.Fatalf("Error trying to resolve UDP Address: %s. Error was: %s", addrString, err)
}
listenConn, err := net.ListenUDP("udp", listenAddr)
if err != nil {
log.Fatalf("Error trying to listen: %s", err.Error())
}
listenConn.SetReadBuffer(1048576)
if err != nil {
log.Fatalf("Error trying to listen on socket: %s", err)
}
newSocket := Socket{}
newSocket.listenAddr = listenAddr
newSocket.listenConn = listenConn
if remote != "" && rPort != 0 {
remoteString := fmt.Sprintf("%s:%d", remote, rPort)
remoteAddr, err := net.ResolveUDPAddr("udp", remoteString)
newSocket.remoteAddr = remoteAddr
if err != nil {
log.Fatalf("Error trying to connect to remote server: %s", err)
}
}
newSocket.bufSize = bufSize
newSocket.Inbound = make(chan *Packet, 1024)
newSocket.Outbound = make(chan *Packet, 1024)
newSocket.Events = make(chan *Event, 1024)
newSocket.pIdentifier = pIdentifier
newSocket.cm = newConnectionManager(&newSocket)
newSocket.packetloss = 0
timeoutString := fmt.Sprintf("%ds", timeOut)
timeout, err := time.ParseDuration(timeoutString)
newSocket.timeout = timeout
return &newSocket
}
func (s *Socket) listen(wg *sync.WaitGroup) {
defer wg.Done()
buf := make([]byte, s.bufSize)
for {
buf = buf[0:]
bytesRead, addr, err := s.listenConn.ReadFromUDP(buf)
if err != nil {
log.Printf("Error reading from socket: %s", err.Error())
continue
}
//log.Printf("RECV: Processing new packet: %s", addr.String())
newPacket := NewPacket(nil, nil)
// Extract the various fields from the data received
copy(newPacket.protocolID, buf[0:4])
copy(newPacket.sequence, buf[4:8])
copy(newPacket.ack, buf[8:12])
newPacket.acks = bitfield.BitField(buf[12:16])
newPacket.payload = make([]byte, bytesRead-16)
copy(newPacket.payload, buf[16:bytesRead])
findResult := s.cm.find(addr)
if findResult == nil {
newConn := newConnection(addr, s, s.cm)
s.cm.add(newConn)
findResult = newConn
} else {
findResult.updateLastHeard()
}
newPacket.C = findResult
findResult.addReceived(newPacket)
if findResult.sequenceMoreRecent(binary.LittleEndian.Uint32(newPacket.sequence),
binary.LittleEndian.Uint32(findResult.remoteSequence),
findResult.maxSeq) {
copy(findResult.remoteSequence, newPacket.sequence)
}
//log.Printf("Processing acks")
findResult.processAck(newPacket.ack, &newPacket.acks)
//log.Printf("RECV: Ack/s for packet %d are: %d : %s", newPacket.SequenceInt(), newPacket.AckInt(), newPacket.PrintAcks())
newPacket.C = findResult
//log.Printf("packet seq is %d and remote sequence is %d", newPacket.SequenceInt(), findResult.RemoteSequenceInt())
if bytes.Equal(buf[16:20], []byte("kpal")) {
continue
}
s.Inbound <- newPacket
if err != nil {
log.Printf("Listen socket error: %s", err.Error())
}
}
}
func (s *Socket) send(wg *sync.WaitGroup) {
defer wg.Done()
ticker := time.NewTicker(time.Millisecond * 4)
for _ = range ticker.C {
p := <-s.Outbound
c := s.cm.find(p.Connection().Addr)
if c == nil {
newConn := newConnection(p.sender, s, s.cm)
s.cm.add(newConn)
c = newConn
}
p.sequenceLock.Lock()
copy(p.sequence, c.localSequence)
p.sequenceLock.Unlock()
c.incrementLocalSequence()
c.remoteSequenceLock.Lock()
copy(p.ack, c.remoteSequence)
c.remoteSequenceLock.Unlock()
c.addUnacked(p)
p.acks = c.composeAcks()
if c.LocalSequenceInt() > c.maxSeq {
c.SetLocalSequence(uint32(0))
}
//log.Printf("New packet has seq %d", p.SequenceInt())
c.updateLastSent()
//log.Printf("SEND: New packet seq is %d %p", p.SequenceInt(), p.sequence)
var data []byte
data = append(data, p.protocolID...)
data = append(data, p.sequence...)
data = append(data, p.ack...)
data = append(data, p.acks...)
data = append(data, p.payload...)
// log.Printf("In send data is: %v payload is: %v", data, p.payload)
//chance := rand.Float64()
//if chance < 0.1 {
// log.Printf("Throwing away packet: %d", p.SequenceInt())
// continue
//}
//log.Printf("Sending to %s", p.Sender())
//if math.Mod(float64(p.SequenceInt()), 100) == 0 {
//log.Printf("SEND: Ack/s for packet %d are %d : %s", p.SequenceInt(), p.AckInt(), p.PrintAcks())
//}
if s.packetloss > 0 {
randChance := rand.Int31n(100)
if randChance <= int32(s.packetloss) {
continue
}
}
_, err := s.listenConn.WriteToUDP(data, p.C.Addr)
if err != nil {
log.Printf("Error writing packet: %s", err)
continue
}
//log.Printf("Time for send was: %s", time.Since(sendStart))
}
}
//for p := range s.Outbound {
// Start starts the Socket listening and sending
func (s *Socket) Start(wg *sync.WaitGroup) {
go s.listen(wg)
wg.Add(1)
go s.send(wg)
}
// SetTimeout lets the user set the timeout for a Socket. If a Connection has
// not been heard from within that time, they are considered disconnected
func (s *Socket) SetTimeout(d time.Duration) bool {
s.timeout = d
return true
}
// SetProtocolID let's the user set a specific protocol ID to watch for in
// UDP packets. If it isn't present, the packet is ignored
func (s *Socket) SetProtocolID(pID []byte) bool {
s.pIdentifier = pID
return true
}
// GetRemoteAddress returns the remote address of the socket
func (s *Socket) GetRemoteAddress() *net.UDPAddr {
return s.remoteAddr
}
// Stop shuts down a socket
func (s *Socket) Stop() {
s.cm.control <- true
close(s.Outbound)
close(s.Inbound)
}
func (s *Socket) ListenConn() *net.UDPConn {
return s.listenConn
}
// ListenPort returns the port the socket is listening on
func (s *Socket) ListenPort() int {
tmp := s.listenConn.LocalAddr()
p := strings.Split(tmp.String(), ":")
pInt, err := strconv.Atoi(p[1])
if err != nil {
return 0
}
return pInt
}