aboutsummaryrefslogtreecommitdiff
path: root/pkg/ipstack/ipstack.go
blob: c2d83ba32a4ad2775b853e6d15d864edb1f4ce44 (plain)
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
package ipstack

import (
	"encoding/binary"
	"fmt"
	ipv4header "github.com/brown-csci1680/iptcp-headers"
	"github.com/google/netstack/tcpip/header"
	"github.com/pkg/errors"
	"iptcp/pkg/lnxconfig"
	"log"
	"net"
	"net/netip"
	"sync"
	"time"
)

const (
	MAX_IP_PACKET_SIZE         = 1400
	LOCAL_COST          uint32 = 0
	STATIC_COST         uint32 = 4294967295 // 2^32 - 1
	MaxEntries                 = 64
	INFINITY                   = 16
	SIZE_OF_RIP_ENTRY          = 12
	SIZE_OF_RIP_MESSAGE        = 6
	RIP_PROTOCOL               = 200
	TEST_PROTOCOL              = 0
)

// STRUCTS ---------------------------------------------------------------------
type Interface struct {
	Name     string
	IpPrefix netip.Prefix
	UdpAddr  netip.AddrPort

	RecvSocket    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, dest *Neighbor, message []byte, hdr *ipv4header.IPv4Header) error

var protocolHandlers = make(map[int]HandlerFunc)

var routingTable = make(map[netip.Prefix]Hop)

// ************************************** 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.
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 parse the lnxfile and initializes the data structures and listener routines
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,
			RecvSocket:    net.UDPConn{},
			SocketChannel: make(chan bool),
			State:         true,
		}

		// create the UDP listener
		err := createUDPListener(iface.UDPAddr, &i.RecvSocket)
		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
}

// defines the go routine that listens on the UDP socket
func InterfaceListenerRoutine(i *Interface) {
	// decompose the interface
	socket := i.RecvSocket
	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
			}

			//if !isUp { // don't call the listeners if interface is down
			//	continue
			//}

			// TODO: remove these "training wheels"
			time.Sleep(1 * time.Millisecond)
			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 ******************************************************

// sets the interface to be up and sends a triggered update
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)
	}
}

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)
}

// sets the interface to be down and sends a triggered update
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)
}

// ************************************** 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 **********************************************************

// Sprint functions return a string representation of the myInterfaces 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
}

// Sprint functions return a string representation of the myNeighbors 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
}

func SprintRoutingTable() string {
	tmp := ""
	for prefix, hop := range routingTable {
		if hop.Type == "L" {
			tmp += fmt.Sprintf("%s\t%s\tLOCAL:%s\t%d\n", hop.Type, prefix.String(), hop.Interface.Name, 0)
		} else if hop.Type == "S" {
			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
}

// ************************************** BASIC FUNCTIONS **********************************************************

func CleanUp() {
	fmt.Print("Cleaning up...\n")
	// go through the interfaces, pop thread & close the UDP FDs
	for _, iface := range myInterfaces {
		if iface.SocketChannel != nil {
			close(iface.SocketChannel)
		}
		err := iface.RecvSocket.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)
}

// TODO: have it take TTL so we can decrement it when forwarding
func SendIP(src *netip.Addr, dest *Neighbor, protocolNum int, message []byte, destIP string, hdr *ipv4header.IPv4Header) (int, error) {
	iface, err := GetInterfaceByName(dest.Name)
	if !iface.State {
		return -1, errors.New("error: interface is down")
	}

	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 {
		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 -1, 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())
	// tmpConn, err := net.DialUDP("udp4", nil, sendAddr)
	// get the interface of this neighbor
	if err != nil {
		return -1, errors.WithMessage(err, "Could not bind to UDP port->\t"+dest.UdpAddr.String())
	}

	// bytesWritten, err := tmpConn.Write(bytesToSend)
	// TODO: make this faster by removing call
	bytesWritten, err := iface.RecvSocket.WriteToUDP(bytesToSend, sendAddr)
	if err != nil {
		fmt.Println("Error writing to UDP socket")
		return -1, errors.WithMessage(err, "Error writing to UDP socket")
	}

	return bytesWritten, nil
}

func RecvIP(iface *Interface, isOpen *bool) error {
	buffer := make([]byte, MAX_IP_PACKET_SIZE) // TODO: fix wordking

	// Read on the UDP port
	// Too much printing so I commented it out
	// fmt.Println("wating to read from UDP socket")
	_, _, err := iface.RecvSocket.ReadFromUDP(buffer)
	if err != nil {
		return err
	}

	if !*isOpen {
		return errors.New("interface is down")
	}

	// Marshal the received byte array into a UDP header
	// NOTE:  This does not validate the checksum or check any fields
	// (You'll need to do this part yourself)
	hdr, err := ipv4header.ParseHeader(buffer)
	if err != nil {
		// What should you if the message fails to parse?
		// Your node should not crash or exit when you get a bad message.
		// Instead, simply drop the packet and return to processing.
		fmt.Println("Error parsing header", err)
		return err
	}

	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
	}

	// 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)
	if hdr.Protocol != RIP_PROTOCOL {
		fmt.Println("I see a non-rip packet")
	}
	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, nil, message, hdr)
				if err != nil {
					fmt.Println(err)
				}
			}
			return nil
		}
	}

	// 4) 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 := LongestPrefix(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
}

// ************************************** RIP Routines *******************************************************

func makeRipMessage(command uint16, entries []RIPEntry) []byte {
	SIZE_OF_RIP_HEADER := 2 * 2 // 2 uint16s
	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
	}
	// else, command == 2, response message

	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)

	binary.BigEndian.PutUint16(buf[0:2], command)
	binary.BigEndian.PutUint16(buf[2:4], uint16(len(entries)))

	for i, entry := range entries {
		offset := 2*2 + 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

		ipv4Netmask := uint32(0xffffffff)
		ipv4Netmask <<= 32 - entry.prefix.Bits()
		binary.BigEndian.PutUint32(buf[offset+8:offset+12], ipv4Netmask)
	}

	return buf
}

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 !in {
					continue
				}
				// TODO: consider making this multithreaded and loops above more efficient

				// if we're here, we are sending this to a rip neighbor
				entries := make([]RIPEntry, 0)
				for prefix, hop := range routingTable {
					// implement split horizon + poison reverse at entry level
					// fmt.Println("prefix: ", prefix)
					var cost uint32
					if hop.VIP == n.VipAddr {
						cost = INFINITY
					} else {
						cost = hop.Cost
					}
					entries = append(entries,
						RIPEntry{
							prefix: prefix,
							cost:   cost,
						})
				}

				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
		time.Sleep(5 * time.Second)
	}
}

var mu sync.Mutex
var timeoutTable = make(map[netip.Addr]int)
var MAX_TIMEOUT = 12

func sendTriggeredUpdates(newEntries []RIPEntry) {
	for _, iface := range myInterfaces {
		for _, n := range myNeighbors[iface.Name] {
			_, in := myRIPNeighbors[n.VipAddr.String()]
			if !in {
				continue
			}

			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
			}
		}
	}
}

func manageTimeoutsRoutine() {
	for {
		time.Sleep(time.Second)

		// note: waitgroup causes deadlock then crashing
		//wg := &sync.WaitGroup{}
		//wg.Add(len(timeoutTable))
		//mu.Lock()
		//for prefix, _ := range timeoutTable {
		//	go func(p netip.Prefix) {
		//		timeoutTable[p]++
		//		if timeoutTable[p] == MAX_TIMEOUT {
		//			delete(routingTable, p)
		//			delete(timeoutTable, p)
		//			// TODO: send triggered update
		//		}
		//
		//		wg.Done()
		//	}(prefix)
		//}
		//wg.Wait()
		//mu.Unlock()

		mu.Lock()
		for addr, _ := range timeoutTable {
			timeoutTable[addr]++
			if timeoutTable[addr] == MAX_TIMEOUT {
				delete(timeoutTable, addr)

				newEntries := make([]RIPEntry, 0)
				for p, hop := range routingTable {
					if hop.VIP == addr {
						delete(routingTable, p)
						newEntries = append(newEntries, RIPEntry{p, INFINITY})
					}
				}
				// send triggered update on timeout
				if len(newEntries) > 0 {
					sendTriggeredUpdates(newEntries)
				}
			}
		}
		// fmt.Println("timeout table: ", timeoutTable)
		mu.Unlock()

		//fmt.Println("Timeout table: ", timeoutTable)
	}
}

func startRipRoutines() {
	// send a request to every neighbor
	go func() {
		for _, iface := range myInterfaces {
			for _, neighbor := range myNeighbors[iface.Name] {
				_, 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
				}
			}
		}
	}()

	go periodicUpdateRoutine()

	// make a "timeout" table, for each response we add to the table via rip
	go manageTimeoutsRoutine()

	// start a routine that sends updates every 10 seconds
}

// ************************************** Protocol Handlers *******************************************************

func RegisterProtocolHandler(protocolNum int) bool {
	if protocolNum == RIP_PROTOCOL {
		protocolHandlers[protocolNum] = handleRIP
		go startRipRoutines()
		return true
	}
	if protocolNum == TEST_PROTOCOL {
		protocolHandlers[protocolNum] = handleTestPackets
		return true
	}
	return false
}

func handleRIP(src *Interface, dest *Neighbor, message []byte, hdr *ipv4header.IPv4Header) error {
	// parse the RIP message
	SIZE_OF_RIP_HEADER := 2 * 2
	command := int(binary.BigEndian.Uint16(message[0:2]))
	switch command {
	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
		}

		// fmt.Println("he is my rip neighbor ", hdr.Src.String())

		// build the entries
		entries := make([]RIPEntry, 0)
		for prefix, hop := range routingTable {
			// implement split horizon + poison reverse at entry level
			// fmt.Println("prefix: ", prefix)
			var cost uint32
			if hop.VIP == hdr.Src {
				cost = INFINITY
			} else {
				cost = hop.Cost
			}
			entries = append(entries,
				RIPEntry{
					prefix: prefix,
					cost:   cost,
				})
		}
		res := makeRipMessage(2, entries)
		_, err := SendIP(&hdr.Dst, neighbor, RIP_PROTOCOL, res, hdr.Src.String(), nil)
		if err != nil {
			return err
		}
		break
	case 2:
		numEntries := int(binary.BigEndian.Uint16(message[2:4]))
		// fmt.Println("Received RIP response with", numEntries, "entries")

		// 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})
		}

		// add to routing table
		for _, entry := range entries {
			// fmt.Printf("Received RIP update: %s\t%d\t%d\n", address, entry.mask, entry.cost)

			if entry.prefix.Addr() == netip.MustParseAddr("0.0.0.0") { // TODO: investigate this
				continue
			}

			// TODO: investigate this. should we be sharing local nodes too?
			// potentially, may have to apply mask first
			// fmt.Println(address)

			destination := entry.prefix.Masked()
			// fmt.Println(prefix.String())

			triggeredEntries := make([]RIPEntry, 0)
			// check if the entry is already in the routing table and update if need be
			if hop, ok := routingTable[destination]; ok {
				// if the hop is the same as the incoming neighbor,
				// then we can increase the cost by that new value
				if hop.VIP == hdr.Src &&
					entry.cost > hop.Cost {
					// fmt.Println("Updating route to ", destination.String(), "with cost", entry.cost)
					if entry.cost >= INFINITY {
						// if we receive infinity from the same neighbor, then delete the route
						delete(routingTable, destination)
						triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost + 1})
					} else {
						routingTable[destination] = Hop{entry.cost + 1, "R", src, hdr.Src}
						triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost + 1})
					}
				}

				// if there is a shorter route for this destination on a different (or same) neighbor
				// then update to use that one
				if entry.cost < hop.Cost {
					if entry.cost == INFINITY {
						routingTable[destination] = Hop{entry.cost, "R", src, hdr.Src}
						triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost})
					} else {
						routingTable[destination] = Hop{entry.cost + 1, "R", src, hdr.Src}
						triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost + 1})
					}
				}

				// upon an update from this prefix, reset its timeout
				if hop.Type == "R" {
					mu.Lock()
					timeoutTable[hdr.Src] = 0
					mu.Unlock()
				}
			} else {
				if entry.cost < INFINITY {
					// if we receive infinity from the same neighbor, then delete the route
					routingTable[destination] = Hop{entry.cost + 1, "R", src, hdr.Src}
					// triggeredEntries = append(triggeredEntries, RIPEntry{destination, entry.cost + 1})
				}
			}

			// send out triggered updates
			if len(triggeredEntries) > 0 {
				sendTriggeredUpdates(triggeredEntries)
			}
		}
	}

	return nil
}

func handleTestPackets(src *Interface, dest *Neighbor, 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
}

// ************************************** CHECKSUM FUNCTIONS ******************************************************

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 **********************************************************

// TODO @ MICHAEL: LONGEST PREFIX MATCHING
func LongestPrefix(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("No route to ip %s on table.", src)
}

//
//func SendRIPMessage(src Interface, dest *Neighbor, message *RIPMessage) error {
//	hdr := ipv4header.IPv4Header{
//		Version:  4,
//		Len:      20, // Header length is always 20 when no IP options
//		TOS:      0,
//		TotalLen: ipv4header.HeaderLen + 4 + len(message.entries)*SIZE_OF_RIP_ENTRY,
//		ID:       0,
//		Flags:    0,
//		FragOff:  0,
//		TTL:      32,
//		Protocol: RIP_PROTOCOL,
//		Checksum: 0, // Should be 0 until checksum is computed
//		Src:      src.IpPrefix.Addr(),
//		Dst:      netip.MustParseAddr(dest.VipAddr.String()),
//		Options:  []byte{},
//	}
//
//	headerBytes, err := hdr.Marshal()
//	if err != nil {
//		return err
//	}
//
//	hdr.Checksum = int(ComputeChecksum(headerBytes))
//
//	headerBytes, err = hdr.Marshal()
//	if err != nil {
//		log.Fatalln("Error marshalling header:  ", err)
//	}
//
//	bytesToSend := make([]byte, 0)
//	bytesToSend = append(bytesToSend, headerBytes...)
//
//	// make the RIP message
//	//buf := make([]byte, SIZE_OF_RIP_MESSAGE+len(message.entries)*SIZE_OF_RIP_ENTRY)
//	//buf[0] = message.command
//	//buf[1] = message.numEntries
//
//	buf := make([]byte, 4)
//	binary.BigEndian.PutUint16(buf[0:2], message.command)
//	binary.BigEndian.PutUint16(buf[2:], message.numEntries)
//
//	bytesToSend = append(bytesToSend, buf...)
//
//	for _, entry := range message.entries {
//		// offset := SIZE_OF_RIP_MESSAGE + i*SIZE_OF_RIP_ENTRY
//		// each field is 4 bytes
//		buf := make([]byte, SIZE_OF_RIP_ENTRY)
//		binary.BigEndian.PutUint32(buf, entry.address)   // 0-3 = 4 bytes
//		binary.BigEndian.PutUint32(buf[3:8], entry.mask) // 4-7 = 4 bytes
//		binary.BigEndian.PutUint32(buf[8:], entry.cost)  // 8-11 = 4 bytes
//
//		bytesToSend = append(bytesToSend, buf...)
//	}
//
//	// send RIP message
//	sendAddr, err := net.ResolveUDPAddr("udp4", dest.UdpAddr.String())
//	// tmpConn, err := net.DialUDP("udp4", nil, sendAddr)
//	if err != nil {
//		return errors.WithMessage(err, "Could not bind to UDP port->\t"+dest.UdpAddr.String())
//	}
//
//	iface, err := GetInterfaceByName(dest.Name)
//	//_, err = tmpConn.Write(bytesToSend)
//	_, err = iface.RecvSocket.WriteToUDP(bytesToSend, sendAddr)
//	if err != nil {
//		return err
//	}
//
//	return nil
//}

//func RequestRip() {
//	// create RIP message
//	message := NewRIPMessage(1, []RIPEntry{})
//
//	// send RIP message to RIP neighbors
//	for _, neighbors := range myNeighbors {
//		for _, neighbor := range neighbors {
//			// check if neighbor is RIP neighbor
//			// if not, continue
//			for _, ripNeighbor := range myRIPNeighbors {
//				if neighbor.VipAddr.String() == ripNeighbor.String() {
//					// send RIP message
					// err := SendRIPMessage(myVIP, neighbor, message)
//					if err != nil {
//						continue
//					}
//				}
//			}
//			continue
//		}
//	}
//}
//
//func BroadcastPeriodicUpdates() {
//	// for each periodic update, we want to send our nodes in the table
//	entries := make([]RIPEntry, len(routingTable))
//	for prefix, hop := range routingTable {
//		entries = append(entries,
//			RIPEntry{
//				address: ConvertIPToUint32(prefix.Addr().String()),
//				mask:    uint32(prefix.Bits()),
//				cost:    hop.Cost,
//			})
//	}
//	message := NewRIPMessage(2, entries)
//
//	// send to each neighbor
//	for _, iface := range myInterfaces {
//		for _, n := range myNeighbors[iface.Name] {
//			err := SendRIPMessage(*iface, n, message)
//			if err != nil {
//				fmt.Printf("Error sending RIP message to %s\n", n.VipAddr.String())
//				continue
//			}
//		}
//	}
//
//}

//// THIS MIGHT BE WRONG...
//func SendUpdates() {
//	entries := make([]RIPEntry, len(routingTable))
//	// create RIP entries from its interfaces to one another
//	for _, iface := range myInterfaces {
//		for _, iface2 := range myInterfaces {
//			if iface.Name == iface2.Name {
//				continue
//			}
//			// TODO @ MICHAEL: fix this
//			// hardcoded way to get cost to 0, fix if you want a better way
//			entry := &RIPEntry{
//				address: ConvertIPToUint32(iface2.IpPrefix.Addr().String()),
//				cost:    17,
//				mask:    ConvertIPToUint32(iface.IpPrefix.Addr().String()),
//			}
//			entries = append(entries, *entry)
//
//			entry = &RIPEntry{
//				address: ConvertIPToUint32(iface.IpPrefix.Addr().String()),
//				cost:    17,
//				mask:    ConvertIPToUint32(iface2.IpPrefix.Addr().String()),
//			}
//			entries = append(entries, *entry)
//		}
//	}
//
//	// create RIP entries from its neighbors
//	for _, neighbors := range myNeighbors {
//		for _, neighbor := range neighbors {
//			ipUint32 := ConvertIPToUint32(neighbor.VipAddr.String())
//			var neighborUint32 uint32
//			for _, interfaces := range myInterfaces {
//				if ifaceContainsIP(*interfaces, neighbor.VipAddr) {
//					neighborUint32 = ConvertIPToUint32(interfaces.IpPrefix.Addr().String())
//					break
//				}
//			}
//
//			// create RIP entry
//			entry := &RIPEntry{
//				address: ipUint32,
//				cost:    LOCAL_COST,
//				mask:    neighborUint32,
//			}
//
//			// add to entries and create RIP message
//			entries = append(entries, *entry)
//			message := NewRIPMessage(2, entries)
//
//			// send RIP message
//			for _, Interfaces := range myInterfaces {
//				if Interfaces.Name == neighbor.Name {
					// err := SendRIPMessage(myVIP, neighbor, message)
//					if err != nil {
//						continue
//					}
//				}
//			}
//
//		}
//	}
//}

// TODO @ MICHEAL: Handle links going down and link recovery
// func CheckAndUpdateRoutingTable() {
// 	for {
// 	time.Sleep(12 * time.Second)
// 	for prefix, hop := range routingTable {
// 		// delete route if not refreshed in 12 seconds
// 		// not sure if there is a better way to do this
// 		if hop.Type == "R" {
// 			delete(routingTable, prefix)
// 			SendUpdates()
// 		}
// 	}
// 	}
// }

// TODO @ MICHAEL: Triggered Updates and Split Horizon with Poisoned Reverse