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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
|
package ipstack
// code begins on line 97 after imports, constants, and structs definitions
// This class is divided as follows:
// 1) INIT FUNCTIONS
// 2) DOWN/UP FUNCTIONS
// 3) SEND/RECV FUNCTIONS
// 4) CHECKSUM FUNCTIONS
// 5) RIP FUNCTIONS
// 6) PROTOCOL HANDLERS
// 7) HELPER FUNCTIONS
// 8) GETTER FUNCTIONS
// 9) PRINT FUNCTIONS
// 10) CLEANUP FUNCTION
import (
"encoding/binary"
"fmt"
ipv4header "github.com/brown-csci1680/iptcp-headers"
"github.com/google/netstack/tcpip/header"
"github.com/pkg/errors"
"iptcp/pkg/iptcp_utils"
"iptcp/pkg/lnxconfig"
"log"
"math/rand"
"net"
"net/netip"
"strings"
"sync"
"time"
// "github.com/google/netstack/tcpip/header"
)
const (
MAX_IP_PACKET_SIZE = 1400
LOCAL_COST uint32 = 0
STATIC_COST uint32 = 4294967295 // 2^32 - 1
INFINITY = 16
SIZE_OF_RIP_ENTRY = 12
RIP_PROTOCOL = 200
TEST_PROTOCOL = 0
TCP_PROTOCOL = 6
SIZE_OF_RIP_HEADER = 4
MAX_TIMEOUT = 12
)
// STRUCTS ---------------------------------------------------------------------
type Interface struct {
Name string
IpPrefix netip.Prefix
UdpAddr netip.AddrPort
Socket net.UDPConn
SocketChannel chan bool
State bool
}
type Neighbor struct {
Name string
VipAddr netip.Addr
UdpAddr netip.AddrPort
}
type RIPHeader struct {
command uint16
numEntries uint16
}
type RIPEntry struct {
prefix netip.Prefix
cost uint32
}
type Hop struct {
Cost uint32
Type string
Interface *Interface
VIP netip.Addr
}
// GLOBAL VARIABLES (data structures) ------------------------------------------
var myInterfaces []*Interface
var myNeighbors = make(map[string][]*Neighbor)
var myRIPNeighbors = make(map[string]*Neighbor)
type HandlerFunc func(src *Interface, message []byte, hdr *ipv4header.IPv4Header) error
var protocolHandlers = make(map[int]HandlerFunc)
var routingTable = make(map[netip.Prefix]Hop)
var timeoutTableMu sync.Mutex
var timeoutTable = make(map[netip.Prefix]int)
// ************************************** INIT FUNCTIONS **********************************************************
// reference: https://github.com/brown-csci1680/lecture-examples/blob/main/ip-demo/cmd/udp-ip-recv/main.go
// createUDPListener creates a UDP listener on the given UDP address.
// It SETS the conn parameter to the created UDP socket.
func createUDPListener(UdpAddr netip.AddrPort, conn *net.UDPConn) error {
listenString := UdpAddr.String()
listenAddr, err := net.ResolveUDPAddr("udp4", listenString)
if err != nil {
return errors.WithMessage(err, "Error resolving address->\t"+listenString)
}
tmpConn, err := net.ListenUDP("udp4", listenAddr)
if err != nil {
return errors.WithMessage(err, "Could not bind to UDP port->\t"+listenString)
}
*conn = *tmpConn
return nil
}
// Initialize initializes the data structures and creates the UDP sockets.
//
// It will return an error if the lnx file is not valid or if a socket fails to be created.
//
// After parsing the lnx file, it does the following:
// 1. adds each local interface to the routing table, as dictated by its subnet
// 2. adds neighbors to interface->neighbors[] map
// 3. adds RIP neighbors to RIP neighbor list
// 4. adds static routes to routing table
func Initialize(lnxFilePath string) error {
// Parse the file
lnxConfig, err := lnxconfig.ParseConfig(lnxFilePath)
if err != nil {
return errors.WithMessage(err, "Error parsing config file->\t"+lnxFilePath)
}
// 1) add each local "if" to the routing table, as dictated by its subnet
for _, iface := range lnxConfig.Interfaces {
prefix := netip.PrefixFrom(iface.AssignedIP, iface.AssignedPrefix.Bits())
i := &Interface{
Name: iface.Name,
IpPrefix: prefix,
UdpAddr: iface.UDPAddr,
Socket: net.UDPConn{},
SocketChannel: make(chan bool),
State: true,
}
// create the UDP listener
err := createUDPListener(iface.UDPAddr, &i.Socket)
if err != nil {
return errors.WithMessage(err, "Error creating UDP socket for interface->\t"+iface.Name)
}
// start the listener routine
go InterfaceListenerRoutine(i)
// add to the list of interfaces
myInterfaces = append(myInterfaces, i)
// add to the routing table
routingTable[prefix.Masked()] = Hop{LOCAL_COST, "L", i, prefix.Addr()}
}
// 2) add neighbors to if->neighbors map
for _, neighbor := range lnxConfig.Neighbors {
n := &Neighbor{
Name: neighbor.InterfaceName,
VipAddr: neighbor.DestAddr,
UdpAddr: neighbor.UDPAddr,
}
myNeighbors[neighbor.InterfaceName] = append(myNeighbors[neighbor.InterfaceName], n)
}
// 3) add RIP neighbors to RIP neighbor list
for _, route := range lnxConfig.RipNeighbors {
// add to RIP neighbors
for _, iface := range myInterfaces {
for _, neighbor := range myNeighbors[iface.Name] {
if neighbor.VipAddr == route {
myRIPNeighbors[neighbor.VipAddr.String()] = neighbor
break
}
}
}
}
// 4) add static routes to routing table
for prefix, addr := range lnxConfig.StaticRoutes {
// need loops to find the interface that matches the neighbor to send static to
// hops needs this interface
for _, iface := range myInterfaces {
for _, neighbor := range myNeighbors[iface.Name] {
if neighbor.VipAddr == addr {
routingTable[prefix] = Hop{STATIC_COST, "S", iface, addr}
break
}
}
}
}
return nil
}
// InterfaceListenerRoutine is a go routine for interfaces to listen on a UDP port.
//
// It is composed two go routines:
// 1. a go routine that hangs on the recv and calls RecvIP() when a packet is received
// 2. a go routine that listens on the channel for a signal to start/stop listening
//
// TODO: (performance) remove isUp and use the interface's value instead
func InterfaceListenerRoutine(i *Interface) {
// decompose the interface
socket := i.Socket
signal := i.SocketChannel
// booleans to control listening routine
isUp := true
closed := false
// fmt.Println("MAKING GO ROUTINE TO LISTEN:\t", socket.LocalAddr().String())
// go routine that hangs on the recv
go func() {
defer func() {
fmt.Println("exiting go routine that listens on ", socket.LocalAddr().String())
}()
for {
if closed { // stop this go routine if channel is closed
return
}
err := RecvIP(i, &isUp)
if err != nil {
continue
}
}
}()
for {
select {
// if the channel is closed, exit
case sig, ok := <-signal:
if !ok {
fmt.Println("channel closed, exiting")
closed = true
return
}
// fmt.Println("received isUP SIGNAL with value", sig)
isUp = sig
// if the channel is not closed, continue
default:
continue
}
}
}
// ************************************** DOWN/UP FUNCTIONS ******************************************************
// InterfaceUp brings up the link layer
//
// It does the following:
// 1. tells the listener (through a channel) to start listening
// 2. updates the interface state to up
// 3. sends RIP request to all neighbors of this iface to quickly update the routing table
func InterfaceUp(iface *Interface) {
// set the state to up and send the signal
iface.State = true
iface.SocketChannel <- true
// if were a router, send triggered updates on up
if _, ok := protocolHandlers[RIP_PROTOCOL]; ok {
ripEntries := make([]RIPEntry, 0)
ripEntries = append(ripEntries, RIPEntry{iface.IpPrefix.Masked(), LOCAL_COST})
SendTriggeredUpdates(ripEntries)
// send a request to all neighbors of this iface to get info ASAP
for _, neighbor := range myNeighbors[iface.Name] {
message := MakeRipMessage(1, nil)
addr := iface.IpPrefix.Addr()
_, err := SendIP(&addr, neighbor, RIP_PROTOCOL, message, neighbor.VipAddr.String(), nil)
if err != nil {
fmt.Println("Error sending RIP request to neighbor on interfaceup", err)
}
}
}
}
func InterfaceUpREPL(ifaceName string) {
iface, err := GetInterfaceByName(ifaceName)
if err != nil {
fmt.Println("Error getting interface by name", err)
return
}
// set the state to up and send the signal
InterfaceUp(iface)
}
// InterfaceDown cuts off the link layer.
//
// It does the following:
// 1. tells the listener (through a channel) to stop listening
// 2. updates the interface state to down
// 3. updates the routing table by removing the routes those neighbors connected to, sending triggered updates.
func InterfaceDown(iface *Interface) {
// set the state to down and send the signal
iface.SocketChannel <- false
iface.State = false
// if were a router, send triggered updates on down
if _, ok := protocolHandlers[RIP_PROTOCOL]; ok {
ripEntries := make([]RIPEntry, 0)
ripEntries = append(ripEntries, RIPEntry{iface.IpPrefix.Masked(), INFINITY})
SendTriggeredUpdates(ripEntries)
}
}
func InterfaceDownREPL(ifaceName string) {
iface, err := GetInterfaceByName(ifaceName)
if err != nil {
fmt.Println("Error getting interface by name", err)
return
}
// set the state to down and send the signal
InterfaceDown(iface)
}
// ************************************** SEND/RECV FUNCTIONS *******************************************************
// SendIP sends an IP packet to a destination
//
// If the header is nil, then a new header is created
// If the header is not nil, then it will use that header after decrementing TTL & recomputing checksum
//
// TODO: (performance) have this take in an interface instead of src for performance
func SendIP(src *netip.Addr, dest *Neighbor, protocolNum int, message []byte, destIP string, hdr *ipv4header.IPv4Header) (int, error) {
// check if the interface is up
iface, err := GetInterfaceByName(dest.Name)
if !iface.State {
return 0, errors.Errorf("error SEND: %s is down", iface.Name)
}
// if the header is nil, create a new one
if hdr == nil {
hdr = &ipv4header.IPv4Header{
Version: 4,
Len: 20, // Header length is always 20 when no IP options
TOS: 0,
TotalLen: ipv4header.HeaderLen + len(message),
ID: 0,
Flags: 0,
FragOff: 0,
TTL: 32,
Protocol: protocolNum,
Checksum: 0, // Should be 0 until checksum is computed
Src: *src,
Dst: netip.MustParseAddr(destIP),
Options: []byte{},
}
} else {
// if the header is not nil, decrement the TTL
hdr = &ipv4header.IPv4Header{
Version: 4,
Len: 20, // Header length is always 20 when no IP options
TOS: 0,
TotalLen: ipv4header.HeaderLen + len(message),
ID: 0,
Flags: 0,
FragOff: 0,
TTL: hdr.TTL - 1,
Protocol: protocolNum,
Checksum: 0, // Should be 0 until checksum is computed
Src: *src,
Dst: netip.MustParseAddr(destIP),
Options: []byte{},
}
}
// Assemble the header into a byte array
headerBytes, err := hdr.Marshal()
if err != nil {
return 0, err
}
// Compute the checksum (see below)
// Cast back to an int, which is what the Header structure expects
hdr.Checksum = int(ComputeChecksum(headerBytes))
headerBytes, err = hdr.Marshal()
if err != nil {
log.Fatalln("Error marshalling header: ", err)
}
// Combine the header and the message into a single byte array
bytesToSend := make([]byte, 0, len(headerBytes)+len(message))
bytesToSend = append(bytesToSend, headerBytes...)
bytesToSend = append(bytesToSend, []byte(message)...)
sendAddr, err := net.ResolveUDPAddr("udp4", dest.UdpAddr.String())
if err != nil {
return -1, errors.WithMessage(err, "Could not bind to UDP port->\t"+dest.UdpAddr.String())
}
// send the packet
bytesWritten, err := iface.Socket.WriteToUDP(bytesToSend, sendAddr)
if err != nil {
fmt.Println("Error writing to UDP socket")
return 0, errors.WithMessage(err, "Error writing to UDP socket")
}
return bytesWritten, nil
}
// RecvIP receives an IP packet from the interface
// To be called by the listener routine, representing one interface
// Upon receiving a packet, this function:
// 1. determines if packet is valid (checksum, TTL)
// 2. determines if the packet is for me. if so, SENDUP (call correct handler)
// 3. the packet is not SENTUP, then checks the routing table
// 4. if there is no route in the routing table, then prints an error and DROPS the packet
func RecvIP(iface *Interface, isOpen *bool) error {
buffer := make([]byte, MAX_IP_PACKET_SIZE)
// Read on the UDP port
// fmt.Println("wating to read from UDP socket")
_, _, err := iface.Socket.ReadFromUDP(buffer)
if err != nil {
return err
}
// check if the interface is up
if !*isOpen {
return errors.Errorf("error RECV: %s is down", iface.Name)
}
// Marshal the received byte array into a UDP header
hdr, err := ipv4header.ParseHeader(buffer)
if err != nil {
fmt.Println("Error parsing header", err)
return err
}
// checksum validation
headerSize := hdr.Len
headerBytes := buffer[:headerSize]
checksumFromHeader := uint16(hdr.Checksum)
computedChecksum := ValidateChecksum(headerBytes, checksumFromHeader)
var checksumState string
if computedChecksum == checksumFromHeader {
checksumState = "OK"
} else {
checksumState = "FAIL"
}
// Next, get the message, which starts after the header
messageLen := hdr.TotalLen - hdr.Len
message := buffer[headerSize : messageLen+headerSize]
// 1) check if the TTL & checksum is valid
TTL := hdr.TTL
if TTL == 0 {
// drop the packet
return nil
}
// check if the checksum is valid
if checksumState == "FAIL" {
// drop the packet
// fmt.Println("checksum failed, dropping packet")
return nil
}
//if hdr.Protocol != RIP_PROTOCOL {
// fmt.Println("I see a non-rip packet")
//}
// at this point, the packet is valid. next steps consider the forwarding of the packet
// 2) check if the message is for me, if so, sendUP (aka call the correct handler)
for _, myIface := range myInterfaces {
if hdr.Dst == myIface.IpPrefix.Addr() {
// see if there is a handler for this protocol
if handler, ok := protocolHandlers[hdr.Protocol]; ok {
if hdr.Protocol != RIP_PROTOCOL {
// fmt.Println("this test packet is exactly for me")
}
err := handler(myIface, message, hdr)
if err != nil {
fmt.Println(err)
}
}
return nil
}
}
// 3) check forwarding table.
// - if it's a local hop, send to that iface
// - if it's a RIP hop, send to the neighbor with that VIP
// fmt.Println("checking routing table")
hop, err := Route(hdr.Dst)
if err == nil { // on no err, found a match
// fmt.Println("found route", hop.VIP)
if hop.Type == "S" {
// default, static route
// drop in this case
return nil
}
// - local hop
if hop.Type == "L" {
// if it's a local route, then the name is the interface name
for _, neighbor := range myNeighbors[hop.Interface.Name] {
if neighbor.VipAddr == hdr.Dst {
_, err2 := SendIP(&hdr.Src, neighbor, hdr.Protocol, message, hdr.Dst.String(), hdr)
if err2 != nil {
return err2
}
}
}
}
// - rip hop
if hop.Type == "R" {
// if it's a rip route, then the check is against the hop vip
for _, neighbor := range myNeighbors[hop.Interface.Name] {
if neighbor.VipAddr == hop.VIP {
_, err2 := SendIP(&hdr.Src, neighbor, hdr.Protocol, message, hdr.Dst.String(), hdr)
if err2 != nil {
return err2
}
}
}
}
}
// if not in table, drop packet
return nil
}
// ************************************** CHECKSUM FUNCTIONS ******************************************************
// reference: https://github.com/brown-csci1680/lecture-examples/blob/main/ip-demo/cmd/udp-ip-recv/main.go
func ComputeChecksum(b []byte) uint16 {
checksum := header.Checksum(b, 0)
checksumInv := checksum ^ 0xffff
return checksumInv
}
func ValidateChecksum(b []byte, fromHeader uint16) uint16 {
checksum := header.Checksum(b, fromHeader)
return checksum
}
// ************************************** RIP FUNCTIONS *******************************************************
// PeriodicUpdateRoutine sends RIP updates to neighbors every 5 seconds
// TODO: (performace) consider making this multithreaded and loops above more efficient
func PeriodicUpdateRoutine() {
for {
// for each periodic update, we want to send our nodes in the table
for _, iface := range myInterfaces {
for _, n := range myNeighbors[iface.Name] {
_, in := myRIPNeighbors[n.VipAddr.String()]
// if the neighbor is not a RIP neighbor, skip it
if !in {
continue
}
// Sending to a rip neighbor
// create the entries
entries := make([]RIPEntry, 0)
for prefix, hop := range routingTable {
// implement split horizon + poison reverse at entry level
var cost uint32
if hop.VIP == n.VipAddr {
cost = INFINITY
} else {
cost = hop.Cost
}
entries = append(entries,
RIPEntry{
prefix: prefix,
cost: cost,
})
}
// make the message and send it
message := MakeRipMessage(2, entries)
addr := iface.IpPrefix.Addr()
_, err := SendIP(&addr, n, RIP_PROTOCOL, message, n.VipAddr.String(), nil)
if err != nil {
// fmt.Printf("Error sending RIP message to %s\n", n.VipAddr.String())
continue
}
}
}
// wait 5 sec and repeat
time.Sleep(5 * time.Second)
}
}
// SendTriggeredUpdates sends the entries consumed to ALL neighbors
func SendTriggeredUpdates(newEntries []RIPEntry) {
for _, iface := range myInterfaces {
for _, n := range myNeighbors[iface.Name] {
// only send to RIP neighbors, else skip
_, in := myRIPNeighbors[n.VipAddr.String()]
if !in {
continue
}
// send the made entries to the neighbor
message := MakeRipMessage(2, newEntries)
addr := iface.IpPrefix.Addr()
_, err := SendIP(&addr, n, RIP_PROTOCOL, message, n.VipAddr.String(), nil)
if err != nil {
// fmt.Printf("Error sending RIP triggered update to %s\n", n.VipAddr.String())
continue
}
}
}
}
// ManageTimeoutsRoutine manages the timeout table by incrementing the timeouts every second.
// If a timeout reaches MAX_TIMEOUT, then the entry is deleted from the routing table and a triggered update is sent.
func ManageTimeoutsRoutine() {
for {
time.Sleep(time.Second)
timeoutTableMu.Lock()
// check if any timeouts have occurred
for key, _ := range timeoutTable {
timeoutTable[key]++
// if the timeout is MAX_TIMEOUT, delete the entry
if timeoutTable[key] == MAX_TIMEOUT {
delete(timeoutTable, key)
newEntries := make([]RIPEntry, 0)
delete(routingTable, key)
newEntries = append(newEntries, RIPEntry{key, INFINITY})
// send triggered update on timeout
if len(newEntries) > 0 {
SendTriggeredUpdates(newEntries)
}
}
}
timeoutTableMu.Unlock()
//fmt.Println("Timeout table: ", timeoutTable)
}
}
// StartRipRoutines handles all the routines for RIP
// 1. sends a RIP request to every neighbor
// 2. starts the routine that sends periodic updates every 5 seconds
// 3. starts the routine that manages the timeout table
func StartRipRoutines() {
// send a request to every neighbor
go func() {
for _, iface := range myInterfaces {
for _, neighbor := range myNeighbors[iface.Name] {
// only send to RIP neighbors, else skip
_, in := myRIPNeighbors[neighbor.VipAddr.String()]
if !in {
continue
}
// send a request
message := MakeRipMessage(1, nil)
addr := iface.IpPrefix.Addr()
_, err := SendIP(&addr, neighbor, RIP_PROTOCOL, message, neighbor.VipAddr.String(), nil)
if err != nil {
return
}
}
}
}()
// start a routine that sends updates every 5 seconds
go PeriodicUpdateRoutine()
// make a "timeout" table, for each response we add to the table via rip
go ManageTimeoutsRoutine()
}
// ************************************** PROTOCOL HANDLERS *******************************************************
// RegisterProtocolHandler registers a protocol handler for a given protocol number
// Returns true if the protocol number is valid, false otherwise
func RegisterProtocolHandler(protocolNum int) bool {
switch protocolNum {
case RIP_PROTOCOL:
protocolHandlers[protocolNum] = HandleRIP
go StartRipRoutines()
return true
case TEST_PROTOCOL:
protocolHandlers[protocolNum] = HandleTestPackets
return true
case TCP_PROTOCOL:
protocolHandlers[protocolNum] = HandleTCP
return true
default:
return false
}
}
// HandleRIP handles incoming RIP packets in the following way:
// 1. if the command is a request, send a RIP response only to that requestor
// 2. if the command is a response, parse the entries, update the routing table from them,
// and send applicable triggered updates (see implementation for how to update)
func HandleRIP(src *Interface, message []byte, hdr *ipv4header.IPv4Header) error {
// parse the RIP message
command := int(binary.BigEndian.Uint16(message[0:2]))
switch command {
// request message
case 1:
//fmt.Println("Received RIP command for specific info")
// only send if the person asking is a RIP neighbor
neighbor, in := myRIPNeighbors[hdr.Src.String()]
if !in {
break
}
// build the entries
entries := make([]RIPEntry, 0)
for prefix, hop := range routingTable {
// implement split horizon + poison reverse at entry level
var cost uint32
if hop.VIP == hdr.Src {
cost = INFINITY
} else {
cost = hop.Cost
}
entries = append(entries,
RIPEntry{
prefix: prefix,
cost: cost,
})
}
// send the entries
res := MakeRipMessage(2, entries)
_, err := SendIP(&hdr.Dst, neighbor, RIP_PROTOCOL, res, hdr.Src.String(), nil)
if err != nil {
return err
}
break
// response message
case 2:
// fmt.Println("Received RIP response with", numEntries, "entries")
numEntries := int(binary.BigEndian.Uint16(message[2:4]))
// parse the entries
entries := make([]RIPEntry, 0)
for i := 0; i < numEntries; i++ {
offset := SIZE_OF_RIP_HEADER + i*SIZE_OF_RIP_ENTRY
// each field is 4 bytes
cost := binary.BigEndian.Uint32(message[offset : offset+4])
address, _ := netip.AddrFromSlice(message[offset+4 : offset+8])
mask := net.IPv4Mask(message[offset+8], message[offset+9], message[offset+10], message[offset+11])
// make the prefix
bits, _ := mask.Size()
prefix := netip.PrefixFrom(address, bits)
entries = append(entries, RIPEntry{prefix, cost})
}
// update the routing table
triggeredEntries := make([]RIPEntry, 0)
for _, entry := range entries {
destination := entry.prefix.Masked()
// make upperbound for cost infinity
var newCost uint32
if entry.cost == INFINITY {
newCost = INFINITY
} else {
newCost = entry.cost + 1
}
hop, isin := routingTable[destination]
// if prefix not in table, add it (as long as it's not infinity)
if !isin {
if newCost != INFINITY {
// given an update to table, this is now a triggeredUpdate
// triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost + 1})
routingTable[destination] = Hop{newCost, "R", src, hdr.Src}
timeoutTable[destination] = 0
}
continue
}
// if the entry is in the table, only two cases affect the table:
// 1) the entry SRC is updating (or confirming) the hop to itself
// in this case, only update if the cost is different
// if it's infinity, then the route has expired.
// we must set the cost to INF then delete the entry after 12 seconds
//
// 2) a different entry SRC reveals a shorter path to the destination
// in this case, update the routing table to use this new path
//
// all other cases don't meaningfully change the route
// first, upon an update from this prefix, reset its timeout
if hop.Type == "R" {
timeoutTableMu.Lock()
_, in := timeoutTable[destination]
if in {
if routingTable[destination].VIP == hdr.Src {
timeoutTable[destination] = 0
}
}
timeoutTableMu.Unlock()
}
// case 1) the entry SRC == the hop to itself
if hop.VIP == hdr.Src &&
newCost != hop.Cost {
// given an update to table, this is now a triggeredUpdate
triggeredEntries = append(triggeredEntries, RIPEntry{destination, newCost})
routingTable[destination] = Hop{newCost, "R", src, hop.VIP}
// if we receive infinity from the same neighbor, then delete the route after 12 sec
if entry.cost == INFINITY {
// remove after GC time if the COST is still INFINITY
go func() {
time.Sleep(time.Second * time.Duration(MAX_TIMEOUT))
if routingTable[destination].Cost == INFINITY {
delete(routingTable, destination)
timeoutTableMu.Lock()
delete(timeoutTable, destination)
timeoutTableMu.Unlock()
}
}()
}
continue
}
// case 2) a shorter route for this destination is revealed from a different neighbor
if newCost < hop.Cost && newCost != INFINITY {
triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost + 1})
routingTable[destination] = Hop{entry.cost + 1, "R", src, hdr.Src}
continue
}
}
// send out triggered updates
if len(triggeredEntries) > 0 {
SendTriggeredUpdates(triggeredEntries)
}
}
return nil
}
// prints the test packet as per the spec
func HandleTestPackets(src *Interface, message []byte, hdr *ipv4header.IPv4Header) error {
fmt.Printf("Received test packet: Src: %s, Dst: %s, TTL: %d, Data: %s\n",
hdr.Src.String(), hdr.Dst.String(), hdr.TTL, string(message))
return nil
}
func HandleTCP(src *Interface, message []byte, hdr *ipv4header.IPv4Header) error {
fmt.Println("I see a TCP packet")
tcpHeaderAndData := message
tcpHdr := iptcp_utils.ParseTCPHeader(tcpHeaderAndData)
tcpPayload := tcpHeaderAndData[tcpHdr.DataOffset:]
tcpChecksumFromHeader := tcpHdr.Checksum
tcpHdr.Checksum = 0
tcpComputedChecksum := iptcp_utils.ComputeTCPChecksum(&tcpHdr, hdr.Src, hdr.Dst, tcpPayload)
var tcpChecksumState string
if tcpComputedChecksum == tcpChecksumFromHeader {
tcpChecksumState = "OK"
} else {
tcpChecksumState = "FAIL"
}
if tcpChecksumState == "FAIL" {
// drop the packet
fmt.Println("checksum failed, dropping packet")
return nil
}
switch tcpHdr.Flags {
case header.TCPFlagSyn:
fmt.Println("I see a SYN flag")
// if the SYN flag is set, then send a SYNACK
available := false
// add to table if available
mapMutex.Lock()
for _, socketEntry := range VHostSocketMaps {
// todo: check between all 4 field in tuple
if socketEntry.LocalPort == tcpHdr.DstPort && socketEntry.LocalIP == hdr.Dst.String() && socketEntry.State == Listening {
// add a new socketEntry to the map
newEntry := &SocketEntry{
LocalPort: tcpHdr.DstPort,
RemotePort: tcpHdr.SrcPort,
LocalIP: hdr.Dst.String(),
RemoteIP: hdr.Src.String(),
State: SYNRECIEVED,
Socket: socketsMade,
}
// add the entry to the map
key := SocketKey{hdr.Dst.String(), tcpHdr.DstPort, hdr.Src.String(), tcpHdr.SrcPort}
VHostSocketMaps[key] = newEntry
socketsMade += 1
// add the entry to the map
available = true
break
}
}
mapMutex.Unlock()
// if no socket is available, then drop the packet
if !available {
fmt.Println("no socket available")
return nil
}
// make the header
tcpHdr := &header.TCPFields{
SrcPort: tcpHdr.DstPort,
DstPort: tcpHdr.SrcPort,
SeqNum: tcpHdr.SeqNum,
AckNum: tcpHdr.SeqNum + 1,
DataOffset: 20,
Flags: 0x12,
WindowSize: MAX_WINDOW_SIZE,
Checksum: 0,
UrgentPointer: 0,
}
// make the payload
synAckPayload := []byte{}
err := SendTCP(tcpHdr, synAckPayload, hdr.Dst, hdr.Src)
if err != nil {
fmt.Println(err)
}
break
case header.TCPFlagAck | header.TCPFlagSyn:
fmt.Println("I see a SYNACK flag")
// lookup for socket entry and update its state
mapMutex.Lock()
for _, socketEntry := range VHostSocketMaps {
if socketEntry.LocalPort == tcpHdr.DstPort && socketEntry.LocalIP == hdr.Dst.String() && socketEntry.State == SYNSENT {
socketEntry.State = Established
break
}
}
mapMutex.Unlock()
// send an ACK
// make the header
tcpHdr := &header.TCPFields{
SrcPort: tcpHdr.DstPort,
DstPort: tcpHdr.SrcPort,
SeqNum: tcpHdr.SeqNum + 1,
AckNum: tcpHdr.SeqNum,
DataOffset: 20,
Flags: 0x10,
WindowSize: MAX_WINDOW_SIZE,
Checksum: 0,
UrgentPointer: 0,
}
// make the payload
ackPayload := []byte{}
err := SendTCP(tcpHdr, ackPayload, hdr.Dst, hdr.Src)
if err != nil {
fmt.Println(err)
}
break
case header.TCPFlagAck:
fmt.Println("I see an ACK flag")
// lookup for socket entry and update its state
// set synChan to true (TODO)
// key := SocketKey{hdr.Dst.String(), tcpHdr.DstPort, hdr.Src.String(), tcpHdr.SrcPort}
// socketEntry, in := VHostSocketMaps[key]
// if !in {
// fmt.Println("no socket entry found")
// } else if socketEntry.State == Established {
// fmt.Println("socket entry found")
// // socketEntry.Conn.RecvBuffer.buffer = append(socketEntry.Conn.RecvBuffer.buffer, tcpPayload...)
// socketEntry.Conn.SendBuffer.una += uint32(len(tcpPayload))
// break
// }
socketEntry, in := VHostSocketMaps[SocketKey{hdr.Dst.String(), tcpHdr.DstPort, hdr.Src.String(), tcpHdr.SrcPort}]
if !in {
fmt.Println("no socket entry found")
} else if socketEntry.State == Established {
if len(tcpPayload) == 0 {
break
}
fmt.Println("socket entry found")
// infinite loop is created here
// make ack header
tcpHdr := &header.TCPFields{
SrcPort: tcpHdr.DstPort,
DstPort: tcpHdr.SrcPort,
SeqNum: tcpHdr.AckNum,
AckNum: tcpHdr.SeqNum + uint32(len(tcpPayload)),
DataOffset: 20,
Flags: 0x10,
WindowSize: MAX_WINDOW_SIZE,
Checksum: 0,
UrgentPointer: 0,
}
// make the payload
payloadToSend := []byte{}
err := SendTCP(tcpHdr, payloadToSend, hdr.Dst, hdr.Src)
if err != nil {
fmt.Println(err)
}
socketEntry.Conn.SendBuffer.una += uint32(len(tcpPayload))
ptr := socketEntry.Conn.RecvBuffer.recvNext
l := uint32(len(tcpPayload))
copy(socketEntry.Conn.RecvBuffer.buffer[ptr:ptr+l], tcpPayload)
socketEntry.Conn.RecvBuffer.recvNext += l
fmt.Println("recvNext: ", socketEntry.Conn.RecvBuffer.recvNext)
fmt.Println("recvBuffer: ", socketEntry.Conn.RecvBuffer.buffer)
break
}
mapMutex.Lock()
for _, socketEntry := range VHostSocketMaps {
if socketEntry.LocalPort == tcpHdr.DstPort && socketEntry.LocalIP == hdr.Dst.String() && socketEntry.State == SYNRECIEVED {
socketEntry.State = Established
break
}
}
mapMutex.Unlock()
break
default:
fmt.Println("I see a non TCP packet")
break
}
return nil
}
// *********************************************** HELPERS **********************************************************
// Route returns the next HOP, based on longest prefix match for a given ip
// TODO: revisit how to do this at the bit level, not hardcoded for 32 & 24
func Route(src netip.Addr) (Hop, error) {
possibleBits := [2]int{32, 24}
for _, bits := range possibleBits {
cmpPrefix := netip.PrefixFrom(src, bits)
for prefix, hop := range routingTable {
if cmpPrefix.Overlaps(prefix) {
return hop, nil
}
}
}
return Hop{}, errors.Errorf("error ROUTE: destination %s does not exist on routing table.", src)
}
// MakeRipMessage returns the byte array to be used in SendIp for a RIP packet
func MakeRipMessage(command uint16, entries []RIPEntry) []byte {
if command == 1 { // request message
buf := make([]byte, SIZE_OF_RIP_HEADER)
binary.BigEndian.PutUint16(buf[0:2], command)
binary.BigEndian.PutUint16(buf[2:4], uint16(0))
return buf
}
// command == 2, response message
// create the buffer
bufLen := SIZE_OF_RIP_HEADER + // sizeof uint16 is 2, we have two of them
len(entries)*SIZE_OF_RIP_ENTRY // each entry is 12
buf := make([]byte, bufLen)
// fill in the header
binary.BigEndian.PutUint16(buf[0:2], command)
binary.BigEndian.PutUint16(buf[2:4], uint16(len(entries)))
// fill in the entries
for i, entry := range entries {
offset := SIZE_OF_RIP_HEADER + i*SIZE_OF_RIP_ENTRY
binary.BigEndian.PutUint32(buf[offset:offset+4], entry.cost) // 0-3 = 4 bytes
copy(buf[offset+4:offset+8], entry.prefix.Addr().AsSlice()) // 4-7 = 4 bytes
// convert the prefix to a uint32
ipv4Netmask := uint32(0xffffffff)
ipv4Netmask <<= 32 - entry.prefix.Bits()
binary.BigEndian.PutUint32(buf[offset+8:offset+12], ipv4Netmask)
}
return buf
}
// ************************************** GETTER FUNCTIONS **********************************************************
func GetInterfaceByName(ifaceName string) (*Interface, error) {
// iterate through the interfaces and return the one with the same name
for _, iface := range myInterfaces {
if iface.Name == ifaceName {
return iface, nil
}
}
return nil, errors.Errorf("No interface with name %s", ifaceName)
}
func GetInterfaces() []*Interface {
return myInterfaces
}
func GetNeighbors() map[string][]*Neighbor {
return myNeighbors
}
func GetRoutes() map[netip.Prefix]Hop {
return routingTable
}
// ************************************** PRINT FUNCTIONS **********************************************************
// SprintInterfaces returns a string representation of the interfaces data structure
func SprintInterfaces() string {
tmp := ""
for _, iface := range myInterfaces {
if iface.State {
// if the state is up, print UP
tmp += fmt.Sprintf("%s\t%s\t%s\n", iface.Name, iface.IpPrefix.String(), "UP")
} else {
// if the state is down, print DOWN
tmp += fmt.Sprintf("%s\t%s\t%s\n", iface.Name, iface.IpPrefix.String(), "DOWN")
}
}
return tmp
}
// SprintNeighbors returns a string representation of the neighbors data structure
func SprintNeighbors() string {
tmp := ""
for _, iface := range myInterfaces {
if !iface.State {
// if the interface is down, skip it
continue
}
for _, n := range myNeighbors[iface.Name] {
tmp += fmt.Sprintf("%s\t%s\t%s\n", iface.Name, n.VipAddr.String(), n.UdpAddr.String())
}
}
return tmp
}
// SprintRoutingTable returns a string representation of the routing table
func SprintRoutingTable() string {
tmp := ""
for prefix, hop := range routingTable {
if hop.Type == "L" {
// if the hop is local, print LOCAL
tmp += fmt.Sprintf("%s\t%s\tLOCAL:%s\t%d\n", hop.Type, prefix.String(), hop.Interface.Name, hop.Cost)
} else if hop.Type == "S" {
// if the hop is static, don't print the cost
tmp += fmt.Sprintf("%s\t%s\t%s\t%s\n", hop.Type, prefix.String(), hop.VIP.String(), "-")
} else {
tmp += fmt.Sprintf("%s\t%s\t%s\t%d\n", hop.Type, prefix.String(), hop.VIP.String(), hop.Cost)
}
}
return tmp
}
// ************************************** CLEANUP FUNCTIONS **********************************************************
// CleanUp cleans up the data structures and closes the UDP sockets
func CleanUp() {
fmt.Print("Cleaning up...\n")
// go through the interfaces, pop thread & close the UDP FDs
for _, iface := range myInterfaces {
// close the channel
if iface.SocketChannel != nil {
close(iface.SocketChannel)
}
// close the UDP FD
err := iface.Socket.Close()
if err != nil {
continue
}
}
// delete all the neighbors
myNeighbors = make(map[string][]*Neighbor)
// delete all the interfaces
myInterfaces = nil
// delete the routing table
routingTable = make(map[netip.Prefix]Hop)
time.Sleep(5 * time.Millisecond)
}
// ************************************** TCP FUNCTIONS **********************************************************
type ConnectionState string
const (
Established ConnectionState = "ESTABLISHED"
Listening ConnectionState = "LISTENING"
Closed ConnectionState = "CLOSED"
SYNSENT ConnectionState = "SYNSENT"
SYNRECIEVED ConnectionState = "SYNRECIEVED"
MAX_WINDOW_SIZE = 65535
)
// VTCPListener represents a listener socket (similar to Go’s net.TCPListener)
type VTCPListener struct {
LocalAddr string
LocalPort uint16
RemoteAddr string
RemotePort uint16
Socket int
State ConnectionState
}
// // VTCPConn represents a “normal” socket for a TCP connection between two endpoints (similar to Go’s net.TCPConn)
type VTCPConn struct {
LocalAddr string
LocalPort uint16
RemoteAddr string
RemotePort uint16
Socket int
State ConnectionState
SendBuffer *SendBuffer
RecvBuffer *RecvBuffer
}
type SocketEntry struct {
Socket int
LocalIP string
LocalPort uint16
RemoteIP string
RemotePort uint16
State ConnectionState
Conn *VTCPConn
}
type SocketKey struct {
LocalIP string
LocalPort uint16
RemoteIP string
RemotePort uint16
}
type RecvBuffer struct {
recvNext uint32
lbr uint32
buffer []byte
windowSize uint16
}
type SendBuffer struct {
una uint32
nxt uint32
lbw uint32
buffer []byte
}
// create a socket map
// var VHostSocketMaps = make(map[int]*SocketEntry)
var VHostSocketMaps = make(map[SocketKey]*SocketEntry)
// create a channel map
var VHostChannelMaps = make(map[int]chan []byte)
var mapMutex = &sync.Mutex{}
var socketsMade = 0
var startingSeqNum = rand.Uint32()
// Listen Sockets
func VListen(port uint16) (*VTCPListener, error) {
myIP := GetInterfaces()[0].IpPrefix.Addr()
listener := &VTCPListener{
Socket: socketsMade,
State: Listening,
LocalPort: port,
LocalAddr: myIP.String(),
}
// add the socket to the socket map
mapMutex.Lock()
key := SocketKey{myIP.String(), port, "", 0}
VHostSocketMaps[key] = &SocketEntry{
Socket: socketsMade,
LocalIP: myIP.String(),
LocalPort: port,
RemoteIP: "0.0.0.0",
RemotePort: 0,
State: Listening,
}
mapMutex.Unlock()
socketsMade += 1
return listener, nil
}
func (l *VTCPListener) VAccept() (*VTCPConn, error) {
// synChan = make(chan bool)
for {
// wait for a SYN request
mapMutex.Lock()
for _, socketEntry := range VHostSocketMaps {
if socketEntry.State == Established {
// create a new VTCPConn
conn := &VTCPConn{
LocalAddr: socketEntry.LocalIP,
LocalPort: socketEntry.LocalPort,
RemoteAddr: socketEntry.RemoteIP,
RemotePort: socketEntry.RemotePort,
Socket: socketEntry.Socket,
State: Established,
SendBuffer: &SendBuffer{
una: 0,
nxt: 0,
lbw: 0,
buffer: make([]byte, MAX_WINDOW_SIZE),
},
RecvBuffer: &RecvBuffer{
recvNext: 0,
lbr: 0,
buffer: make([]byte, MAX_WINDOW_SIZE),
},
}
socketEntry.Conn = conn
mapMutex.Unlock()
return conn, nil
}
}
mapMutex.Unlock()
}
}
func GetRandomPort() uint16 {
const (
minDynamicPort = 49152
maxDynamicPort = 65535
)
return uint16(rand.Intn(maxDynamicPort-minDynamicPort) + minDynamicPort)
}
func VConnect(ip string, port uint16) (*VTCPConn, error) {
// get my ip address
myIP := GetInterfaces()[0].IpPrefix.Addr()
// get random port
portRand := GetRandomPort()
tcpHdr := &header.TCPFields{
SrcPort: portRand,
DstPort: port,
SeqNum: startingSeqNum,
AckNum: 0,
DataOffset: 20,
Flags: header.TCPFlagSyn,
WindowSize: MAX_WINDOW_SIZE,
Checksum: 0,
UrgentPointer: 0,
}
payload := []byte{}
ipParsed, err := netip.ParseAddr(ip)
if err != nil {
return nil, err
}
err = SendTCP(tcpHdr, payload, myIP, ipParsed)
if err != nil {
return nil, err
}
conn := &VTCPConn{
LocalAddr: myIP.String(),
LocalPort: portRand,
RemoteAddr: ip,
RemotePort: port,
Socket: socketsMade,
State: Established,
SendBuffer: &SendBuffer{
una: 0,
nxt: 0,
lbw: 0,
buffer: make([]byte, MAX_WINDOW_SIZE),
},
RecvBuffer: &RecvBuffer{
recvNext: 0,
lbr: 0,
buffer: make([]byte, MAX_WINDOW_SIZE),
windowSize: uint16(MAX_WINDOW_SIZE),
},
}
// add the socket to the socket map
key := SocketKey{myIP.String(), portRand, ip, port}
mapMutex.Lock()
VHostSocketMaps[key] = &SocketEntry{
Socket: socketsMade,
LocalIP: myIP.String(),
LocalPort: portRand,
RemoteIP: ip,
RemotePort: port,
State: SYNSENT,
Conn: conn,
}
mapMutex.Unlock()
socketsMade += 1
return conn, nil
}
func SendTCP(tcpHdr *header.TCPFields, payload []byte, myIP netip.Addr, ipParsed netip.Addr) error {
checksum := iptcp_utils.ComputeTCPChecksum(tcpHdr, myIP, ipParsed, payload)
tcpHdr.Checksum = checksum
tcpHeaderBytes := make(header.TCP, iptcp_utils.TcpHeaderLen)
tcpHeaderBytes.Encode(tcpHdr)
ipPacketPayload := make([]byte, 0, len(tcpHeaderBytes)+len(payload))
ipPacketPayload = append(ipPacketPayload, tcpHeaderBytes...)
ipPacketPayload = append(ipPacketPayload, []byte(payload)...)
// lookup neighbor
address := ipParsed
hop, err := Route(address)
if err != nil {
fmt.Println(err)
return err
}
myAddr := hop.Interface.IpPrefix.Addr()
for _, neighbor := range GetNeighbors()[hop.Interface.Name] {
if neighbor.VipAddr == address ||
neighbor.VipAddr == hop.VIP && hop.Type == "S" {
bytesWritten, err := SendIP(&myAddr, neighbor, TCP_PROTOCOL, ipPacketPayload, ipParsed.String(), nil)
fmt.Printf("Sent %d bytes to %s\n", bytesWritten, neighbor.VipAddr.String())
if err != nil {
fmt.Println(err)
}
}
}
return nil
}
func SprintSockets() string {
tmp := ""
for _, socket := range VHostSocketMaps {
// remove the spaces of the local and remote ip variables
socket.LocalIP = strings.ReplaceAll(socket.LocalIP, " ", "")
socket.RemoteIP = strings.ReplaceAll(socket.RemoteIP, " ", "")
if socket.RemotePort == 0 {
tmp += fmt.Sprintf("%d\t%s\t%d\t%s\t\t%d\t%s\n", socket.Socket, socket.LocalIP, socket.LocalPort, socket.RemoteIP, socket.RemotePort, socket.State)
continue
}
tmp += fmt.Sprintf("%d\t%s\t%d\t%s\t%d\t%s\n", socket.Socket, socket.LocalIP, socket.LocalPort, socket.RemoteIP, socket.RemotePort, socket.State)
}
return tmp
}
// MILESTONE 2
func (c *VTCPConn) VClose() error {
// check if the socket is in the map
key := SocketKey{c.LocalAddr, c.LocalPort, c.RemoteAddr, c.RemotePort}
mapMutex.Lock()
socketEntry, in := VHostSocketMaps[key]
mapMutex.Unlock()
if !in {
return errors.Errorf("error VClose: socket %d does not exist", c.Socket)
}
// change the state to closed
socketEntry.State = Closed
return nil
}
// advertise window = max window size - (next - 1 - lbr)
// early arrivals queue
var earlyArrivals = make([][]byte, 0)
// retranmission queue
var retransmissionQueue = make([][]byte, 0)
func (c *VTCPConn) VWrite(payload []byte) (int, error) {
// check if the socket is in the map
key := SocketKey{c.LocalAddr, c.LocalPort, c.RemoteAddr, c.RemotePort}
mapMutex.Lock()
socketEntry, in := VHostSocketMaps[key]
mapMutex.Unlock()
if !in {
return 0, errors.Errorf("error VWrite: socket %d does not exist", c.Socket)
}
// check if the state is established
if socketEntry.State != Established {
return 0, errors.Errorf("error VWrite: socket %d is not in established state", c.Socket)
}
// check if the payload is empty
if len(payload) == 0 {
return 0, nil
}
// check if the payload is larger than the window size
if len(payload) > MAX_WINDOW_SIZE {
return 0, errors.Errorf("error VWrite: payload is larger than the window size")
}
availableSendSpace := MAX_WINDOW_SIZE - c.SendBuffer.nxt - 1 - c.SendBuffer.lbw
// check if the payload is larger than the available window size
fmt.Println("space in send buffer", availableSendSpace, "recbuf next", c.RecvBuffer.recvNext, "lbr", c.RecvBuffer.lbr)
if len(payload) > int(availableSendSpace) {
return 0, errors.Errorf("error VWrite: payload is larger than the available space in send buffer")
}
// check if the payload is larger than the available window size
availableWindowSize := c.RecvBuffer.windowSize - uint16(c.RecvBuffer.recvNext-1-c.RecvBuffer.lbr)
// make the header
tcpHdr := &header.TCPFields{
SrcPort: c.LocalPort,
DstPort: c.RemotePort,
SeqNum: c.SendBuffer.nxt,
AckNum: startingSeqNum c.SendBuffer.una,
DataOffset: 20,
Flags: header.TCPFlagAck,
WindowSize: availableWindowSize,
Checksum: 0,
UrgentPointer: 0,
}
myIP := GetInterfaces()[0].IpPrefix.Addr()
ipParsed, err := netip.ParseAddr(c.RemoteAddr)
if err != nil {
return 0, err
}
err = SendTCP(tcpHdr, payload, myIP, ipParsed)
if err != nil {
return 0, err
}
// update the next sequence number
// c.SendBuffer.nxt += uint32(len(payload))
c.SendBuffer.lbw += uint32(len(payload))
return len(payload), nil
}
func (c *VTCPConn) VRead(numBytesToRead int) (int, string, error) {
// check if the socket is in the map
key := SocketKey{c.LocalAddr, c.LocalPort, c.RemoteAddr, c.RemotePort}
// mapMutex.Lock()
socketEntry, in := VHostSocketMaps[key]
// mapMutex.Unlock()
// check if the socket is in the map
if !in {
return 0, "", errors.Errorf("error VRead: socket %d does not exist", c.Socket)
}
// check if the state is established
if socketEntry.State != Established {
return 0, "", errors.Errorf("error VRead: socket %d is not in established state", c.Socket)
}
fmt.Println("I am in VRead")
// fmt.Println("I have", c.RecvBuffer.recvNext-c.RecvBuffer.lbr, "bytes to read")
fmt.Println("recvNext", c.RecvBuffer.recvNext, "lbr", c.RecvBuffer.lbr)
var diff uint32
if c.RecvBuffer.recvNext-c.RecvBuffer.lbr <= uint32(numBytesToRead) {
diff = c.RecvBuffer.recvNext - c.RecvBuffer.lbr
} else if c.RecvBuffer.recvNext-c.RecvBuffer.lbr > uint32(numBytesToRead) {
diff = uint32(numBytesToRead)
} else {
diff = 0
}
if c.RecvBuffer.lbr < c.RecvBuffer.recvNext && diff != 0 {
fmt.Println("I have enough data to read")
toReturn := string(socketEntry.Conn.RecvBuffer.buffer[c.RecvBuffer.lbr : c.RecvBuffer.lbr+diff])
// update the last byte read
c.RecvBuffer.lbr += diff
// increase the window size by bytes read
c.RecvBuffer.windowSize += uint16(diff)
// return the data
return int(diff), toReturn, nil
}
return 0, "", nil
}
|