-
Notifications
You must be signed in to change notification settings - Fork 0
/
srh-quic.go
454 lines (401 loc) · 15.2 KB
/
srh-quic.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package middleware
import (
"context"
"crypto/tls"
"encoding/binary"
"fmt"
"io"
"log"
"os"
"strings"
"time"
"github.com/gfads/midarch/pkg/gmidarch/development/messages"
"github.com/gfads/midarch/pkg/gmidarch/development/messages/miop"
"github.com/gfads/midarch/pkg/shared"
"github.com/gfads/midarch/pkg/shared/lib"
"github.com/quic-go/quic-go"
)
// @Type: SRHQUIC
// @Behaviour: Behaviour = I_Accept -> I_Receive -> InvR.e1 -> TerR.e1 -> I_Send -> Behaviour
type SRHQUIC struct {
// Graph exec.ExecGraph
}
// var ConnsSRHQUIC []quic.Connection
// var StreamsSRHQUIC []quic.Stream
// var LnSRHQUIC quic.Listener
// var c1Quic = make(chan []byte)
// var c2Quic = make(chan []byte)
// var currentConnectionQuic = -1
// var stateQuic = 0
func (s SRHQUIC) availableConnectionFromPool(clientsPtr *[]*messages.Client, ip string) (bool, int) {
clients := *clientsPtr
if ip != "" {
for idx, client := range clients {
if client.Ip == ip {
return true, idx
}
if client.UDPConnection != nil || client.Connection != nil {
client.UDPConnection = nil
client.Connection = nil // TODO dcruzb: verify memory leak (didn't close the connection)
return true, idx
}
}
}
//lib.PrintlnDebug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Total clients", len(clients))
if len(clients) < 2 { //shared.MAX_NUMBER_OF_CONNECTIONS { TODO dcruzb: go back the env var
client := messages.Client{
Ip: "",
Connection: nil,
UDPConnection: nil,
QUICConnection: nil,
QUICStream: nil,
}
*clientsPtr = append(clients, &client)
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Total Clients", len(*clientsPtr))
return true, len(*clientsPtr) - 1
}
for idx, client := range clients {
if client == nil {
client := messages.Client{
Ip: "",
Connection: nil,
UDPConnection: nil,
QUICConnection: nil,
QUICStream: nil,
}
clients[idx] = &client
return true, idx
}
if client.UDPConnection != nil {
client.UDPConnection.Close()
client.UDPConnection = nil
return true, idx
}
if client.Connection != nil {
client.Ip = ""
client.Connection.Close()
client.Connection = nil
return true, idx
}
}
return false, -1
}
func (s SRHQUIC) I_Accept(id string, msg *messages.SAMessage, info *interface{}, reset *bool) {
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "SRHQUIC Version Not adapted")
infoTemp := *info
srhInfo := infoTemp.(*messages.SRHInfo)
// srhInfo.Counter++
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Total Cons", len(srhInfo.Clients))
//log.Println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Counter", srhInfo.Counter)
// check if a listener has been already created
if srhInfo.QUICLn == nil { // no listener created
//servAddr, err := net.ResolveTCPAddr("tcp", host+":"+port)
//if err != nil {
// log.Fatalf("SRH:: %v\n", err)
//}
quicConfig := quic.Config{KeepAlivePeriod: 60 * time.Second}
ln, err := quic.ListenAddr(srhInfo.EndPoint.Host+":"+srhInfo.EndPoint.Port, getServerTLSQuicConfig(), &quicConfig)
if err != nil {
log.Fatalf("SRHQUIC:: %v\n", err)
}
srhInfo.QUICLn = ln
}
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Total Clients out", len(srhInfo.Clients))
connectionAvailable, availableConenctionIndex := s.availableConnectionFromPool(&srhInfo.Clients, "")
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Total Clients out", len(srhInfo.Clients))
if !connectionAvailable {
//lib.PrintlnDebug("------------------------------>", shared.GetFunction(), "end", "SRHQUIC Version Not adapted - No connection available")
time.Sleep(1 * time.Millisecond)
return
}
go func() {
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Clients Index", availableConenctionIndex)
// Accept connections
conn, err := srhInfo.QUICLn.Accept(context.Background())
if err != nil {
shared.ErrorHandler(shared.GetFunction(), err.Error())
}
srhInfo.QUICConns = append(srhInfo.QUICConns, conn)
//srhInfo.CurrentConn = conn
lib.PrintlnDebug("SRHQUIC Version Not adapted >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Buscou nova conexão, ip:", conn.RemoteAddr().String())
//connectionAvailable, availableConenctionIndex := s.availableConnectionFromPool(&srhInfo.Clients, conn.RemoteAddr().String())
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Total Clients out", len(srhInfo.Clients))
//if !connectionAvailable {
// lib.PrintlnDebug("------------------------------>", shared.GetFunction(), "end", "SRHQUIC Version Not adapted - No connection available")
// return
//}
if len(srhInfo.Clients) <= availableConenctionIndex {
lib.PrintlnDebug("SRHQUIC Got len(srhInfo.Clients) <= availableConenctionIndex")
*reset = true
return
}
client := srhInfo.Clients[availableConenctionIndex]
client.Ip = conn.RemoteAddr().String()
client.QUICConnection = conn
client.QUICStream, err = client.QUICConnection.AcceptStream(context.Background())
//stream, err := tempConn.OpenStreamSync(context.Background())
if err != nil {
shared.ErrorHandler(shared.GetFunction(), err.Error())
}
//log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Connected Client", client)
// Update info
*info = srhInfo
// Start goroutine
go s.handler(info, availableConenctionIndex)
}()
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "end", "SRHQUIC Version Not adapted")
return
}
func (s SRHQUIC) I_Receive(id string, msg *messages.SAMessage, info *interface{}, reset *bool) {
// tempPort := *elemInfo[0]
// port := tempPort.(string)
// host := "0.0.0.0" //"127.0.0.1" // TODO
// if LnSRHQUIC == nil { // listener was not created yet
// //servAddr, err := net.ResolveTCPAddr("tcp", host+":"+port)
// //if err != nil {
// // log.Fatalf("SRH:: %v\n", err)
// //}
// quicConfig := quic.Config{KeepAlivePeriod: 60 * time.Second}
// ln, err := quic.ListenAddr(host+":"+port, getServerTLSQuicConfig(), &quicConfig)
// if err != nil {
// log.Fatalf("SRHQUIC:: %v\n", err)
// }
// LnSRHQUIC = ln
// }
// switch stateQuic {
// case 0:
// go acceptAndReadQuic(currentConnectionQuic, c1Quic)
// stateQuic = 1
// case 1:
// go readQuic(currentConnectionQuic, c1Quic)
// stateQuic = 2
// case 2:
// go readQuic(currentConnectionQuic, c1Quic)
// }
//go acceptAndRead(currentConnectionQuic, c1Quic, done)
//go read(currentConnectionQuic, c2Quic, done)
infoTemp := *info
srhInfo := infoTemp.(*messages.SRHInfo)
select {
case tempMsgReceived := <-srhInfo.RcvedMessages:
// *msg = messages.SAMessage{Payload: tempMsgReceived}
// Update info
*info = srhInfo
msg.Payload = tempMsgReceived.Msg
lib.PrintlnDebug("SRHQUIC Version Not adapted: tempMsgReceived", tempMsgReceived)
lib.PrintlnDebug("SRHQUIC Version Not adapted: tempMsgReceived.QUICStream", tempMsgReceived.QUICStream)
if tempMsgReceived.QUICStream == nil {
*reset = true
return
}
if isNewConnection, miopPacket := s.isNewConnection(tempMsgReceived.Msg); isNewConnection {
lib.PrintlnDebug("SRHQUIC Version Not adapted: tempMsgReceived >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", miopPacket)
*reset = true
return
}
msg.ToAddr = tempMsgReceived.ToAddress //Chn.RemoteAddr().String()
default:
{
*reset = true
return
}
}
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "end", "SRHQUIC Version Not adapted")
return
}
// func acceptAndReadQuic(currentConnectionQuic int, c chan []byte) {
// // accept connections
// temp, err := LnSRHQUIC.Accept(context.Background())
// if err != nil {
// fmt.Printf("SRHQUIC:: %v\n", err)
// os.Exit(1)
// }
// ConnsSRHQUIC = append(ConnsSRHQUIC, temp) // Quic Session
// currentConnectionQuic++
// // receive size
// size := make([]byte, shared.SIZE_OF_MESSAGE_SIZE, shared.SIZE_OF_MESSAGE_SIZE)
// tempConn := ConnsSRHQUIC[currentConnectionQuic]
// stream, err := tempConn.AcceptStream(context.Background())
// //stream, err := tempConn.OpenStreamSync(context.Background())
// StreamsSRHQUIC = append(StreamsSRHQUIC, stream)
// if err != nil {
// fmt.Printf("SRHQUIC:: %v\n", err)
// os.Exit(1)
// }
// _, err = stream.Read(size)
// if err == io.EOF {
// {
// fmt.Printf("SRHQUIC:: Accept and Read\n")
// os.Exit(0)
// }
// } else if err != nil && err != io.EOF {
// fmt.Printf("SRHQUIC:: %v\n", err)
// os.Exit(1)
// }
// stream2 := StreamsSRHQUIC[currentConnectionQuic]
// // receive message
// msgTemp := make([]byte, binary.LittleEndian.Uint32(size))
// _, err = stream2.Read(msgTemp)
// if err != nil {
// fmt.Printf("SRHQUIC:: %v\n", err)
// os.Exit(1)
// }
// c <- msgTemp
// }
// func readQuic(currentConnectionQuic int, c chan []byte) {
// // receive size
// size := make([]byte, shared.SIZE_OF_MESSAGE_SIZE, shared.SIZE_OF_MESSAGE_SIZE)
// stream := StreamsSRHQUIC[currentConnectionQuic]
// _, err := stream.Read(size)
// if err == io.EOF {
// fmt.Printf("SRHQUIC:: Read\n")
// os.Exit(0)
// } else if err != nil && err != io.EOF {
// fmt.Printf("SRHQUIC:: %v\n", err)
// os.Exit(1)
// }
// // receive message
// msgTemp := make([]byte, binary.LittleEndian.Uint32(size))
// _, err = stream.Read(msgTemp)
// if err != nil {
// fmt.Printf("SRHQUIC:: %v\n", err)
// os.Exit(1)
// }
// c <- msgTemp
// return
// }
func (e SRHQUIC) I_Send(id string, msg *messages.SAMessage, info *interface{}, reset *bool) {
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "SRHQUIC Version Not adapted")
infoTemp := *info
srhInfo := infoTemp.(*messages.SRHInfo)
lib.PrintlnDebug("msg.ToAddr", msg.ToAddr, "srhInfo.Clients", srhInfo.Clients)
client := srhInfo.GetClientFromAddr(msg.ToAddr, srhInfo.Clients)
stream := client.QUICStream //srhInfo.CurrentConn
if stream == nil {
*reset = true
return
}
lib.PrintlnDebug("SRHQUIC Version Not adapted >>>>> QUIC => msg.ToAddr:", msg.ToAddr, "QUIC stream:", stream, "AdaptId:", client.AdaptId)
msgPayload := msg.Payload.([]byte)
// send message's size
size := make([]byte, shared.SIZE_OF_MESSAGE_SIZE, shared.SIZE_OF_MESSAGE_SIZE)
binary.LittleEndian.PutUint32(size, uint32(len(msgPayload)))
_, err := stream.Write(size)
if err != nil {
fmt.Printf("SRHQUIC:: %v\n", err)
os.Exit(1)
}
// send message
_, err = stream.Write(msgPayload)
if err != nil {
fmt.Printf("SRHQUIC:: %v\n", err)
os.Exit(1)
}
// update info
*info = srhInfo
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "end", "SRHQUIC Version Not adapted")
return
}
func (s SRHQUIC) handler(info *interface{}, connectionIndex int) {
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "SRHQUIC Version Not adapted")
infoTemp := *info
srhInfo := infoTemp.(*messages.SRHInfo)
stream := srhInfo.Clients[connectionIndex].QUICStream //CurrentConn
executeForever := srhInfo.ExecuteForever
for {
if !*executeForever {
break
}
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "FOR", "SRHQUIC Version Not adapted")
size := make([]byte, shared.SIZE_OF_MESSAGE_SIZE, shared.SIZE_OF_MESSAGE_SIZE)
_, err := stream.Read(size)
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "Read finished", "SRHQUIC Version Not adapted")
if err != nil {
if err == io.EOF ||
strings.Contains(err.Error(), "use of closed network connection") ||
strings.Contains(err.Error(), "timeout: no recent network activity") {
srhInfo.Clients[connectionIndex] = nil
lib.PrintlnError("EOF error - Will not kill the app")
break
} else if err != nil && err != io.EOF {
lib.PrintlnError("Not EOF error - Will kill the app")
shared.ErrorHandler(shared.GetFunction(), err.Error())
}
}
// receive message
msgTemp := make([]byte, binary.LittleEndian.Uint32(size))
_, err = stream.Read(msgTemp)
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "use of closed network connection") {
srhInfo.Clients[connectionIndex] = nil
lib.PrintlnError("EOF error - Will not kill the app")
break
} else if err != nil && err != io.EOF {
lib.PrintlnError("Not EOF error - Will kill the app")
shared.ErrorHandler(shared.GetFunction(), err.Error())
}
}
if changeProtocol, miopPacket := s.isAdapt(msgTemp); changeProtocol {
if miopPacket.Bd.ReqBody.Body[2] == "Ok" {
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "Received Ok to Adapt", "SRHQUIC Version Not adapted")
break
}
}
if isNewConnection, _ := s.isNewConnection(msgTemp); isNewConnection { // TODO dcruzb: move to I_Receive
//newConnection = true
lib.PrintlnDebug("QUIC Is New Connection")
//miopPacket := miop.CreateReqPacket("Connect", []interface{}{miopPacket.Bd.ReqBody.Body[0], "Ok"}, miopPacket.Bd.ReqBody.Body[0].(int)) // idx is the Connection ID
//msgPayload := Jsonmarshaller{}.Marshall(miopPacket)
lib.PrintlnDebug("QUIC Before send")
//s.send(conn, addr, msgPayload)
lib.PrintlnDebug("QUIC After send")
//if miopPacket.Bd.ReqBody.Body[2] == "Ok" {
// lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "Received Ok to Adapt", "SRHUDP Version Not adapted")
// break
//}
continue
}
rcvMessage := messages.ReceivedMessages{Msg: msgTemp, QUICStream: stream, ToAddress: srhInfo.Clients[connectionIndex].Ip}
lib.PrintlnDebug("SRHQUIC Version Not adapted: handler >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> received message")
if !*executeForever {
break
}
srhInfo.RcvedMessages <- rcvMessage
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "FOR end", "SRHQUIC Version Not adapted")
}
lib.PrintlnDebug("----------------------------------------->", shared.GetFunction(), "end", "SRHQUIC Version Not adapted")
}
func (s SRHQUIC) isAdapt(msgFromServer []byte) (bool, miop.MiopPacket) {
//log.Println("----------------------------------------->", shared.GetFunction(), "CRHTCP Version Not adapted")
miop := Jsonmarshaller{}.Unmarshall(msgFromServer)
return miop.Bd.ReqHeader.Operation == "ChangeProtocol", miop
}
func (s SRHQUIC) isNewConnection(msgFromServer []byte) (bool, miop.MiopPacket) {
//log.Println("----------------------------------------->", shared.GetFunction(), "CRHTCP Version Not adapted")
miop := Jsonmarshaller{}.Unmarshall(msgFromServer)
return miop.Bd.ReqHeader.Operation == "Connect", miop
}
func getServerTLSQuicConfig() *tls.Config {
if shared.CRT_PATH == "" {
log.Fatal("SRHQUIC:: Error:: Environment variable 'CRT_PATH' not configured\n")
}
if shared.KEY_PATH == "" {
log.Fatal("SRHQUIC:: Error:: Environment variable 'KEY_PATH' not configured\n")
}
cert, err := tls.LoadX509KeyPair(shared.CRT_PATH, shared.KEY_PATH)
if err != nil {
log.Fatal("Error loading certificate. ", err)
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
NextProtos: []string{"MidArchQuic"}, // TODO dcruzb: Verify what NextProtos should be
}
return tlsConfig
}
// func (e SRHQUIC) Selector(elem interface{}, elemInfo []*interface{}, op string, msg *messages.SAMessage, info []*interface{}, r *bool) {
// if op[2] == 'R' { // I_Receive
// elem.(SRHQUIC).I_Receive(msg, info, elemInfo)
// } else { // "I_Send"
// elem.(SRHQUIC).I_Send(msg, info, elemInfo)
// }
// }