aboutsummaryrefslogtreecommitdiff
path: root/pkg/ipstack/ipstack.go
blob: 334aab598f510e91bdbf7363891f065c5ee0ef3c (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
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"
	"time"
	// "bytes"
	// "unicode"
)

const (
	MAX_IP_PACKET_SIZE         = 1400
	LOCAL_COST          uint32 = 0
	STATIC_COST         uint32 = 4294967295 // 2^32 - 1
	MaxEntries                 = 64
	INFINITY                   = 15
	SIZE_OF_RIP_ENTRY          = 12
	SIZE_OF_RIP_MESSAGE        = 6
	RIP_PROTOCOL               = 12
	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 RIPMessage struct {
	command    uint8
	numEntries uint8
	entries    []RIPEntry
}

type RIPEntry struct {
	address uint32
	cost    uint32
	mask    uint32
}

type Hop struct {
	Cost uint32
	Type string

	Interface *Interface
	VIP       netip.Addr
}

// GLOBAL VARIABLES (data structures) ------------------------------------------
var myVIP Interface
var myInterfaces []*Interface
var myNeighbors = make(map[string][]*Neighbor)

var myRIPNeighbors = make(map[string]bool)

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

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,
		}
		// Added this for printing purposes for REPL FYI, if you have a better way lmk

		err := createUDPListener(iface.UDPAddr, &i.RecvSocket)
		if err != nil {
			return errors.WithMessage(err, "Error creating UDP socket for interface->\t"+iface.Name)
		}

		go InterfaceListenerRoutine(i)
		myInterfaces = append(myInterfaces, i)

		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()] = true
					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
				}
			}
		}
	}

	// add protocol handlers
	return nil
}

func InterfaceListenerRoutine(i *Interface) {
	// decompose the interface
	socket := i.RecvSocket
	signal := i.SocketChannel

	// booleans to control listening routine
	isUp := true
	closed := false

	// go routine that hangs on the recv
	fmt.Println("MAKING GO ROUTINE TO LISTEN:\t", socket.LocalAddr().String())
	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 {
				fmt.Println("Error receiving IP packet", err)
				return
			}
		}
	}()

	for {
		select {
		case sig, ok := <-signal:
			if !ok {
				fmt.Println("channel closed, exiting")
				closed = true
				return
			}
			fmt.Println("received isUP SIGNAL with value", sig)
			isUp = sig
		default:
			continue
		}
	}
}

// ************************************** DOWN/UP FUNCTIONS ******************************************************

func InterfaceUp(iface *Interface) {
	iface.State = true
	iface.SocketChannel <- true
}

func InterfaceUpREPL(ifaceName string) {
	iface, err := GetInterfaceByName(ifaceName)
	if err != nil {
		fmt.Println("Error getting interface by name", err)
		return
	}
	InterfaceUp(iface)
}

// we could do either of these but the REPL results in less work done in router and host

func InterfaceDown(iface *Interface) {
	iface.SocketChannel <- false
	iface.State = false
}

func InterfaceDownREPL(ifaceName string) {
	iface, err := GetInterfaceByName(ifaceName)
	if err != nil {
		fmt.Println("Error getting interface by name", err)
		return
	}
	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 GetNeighborByIP(ipAddr string) (*Neighbor, error) {
	// iterate through the neighbors and return the one with the same ipAddr
	for _, neighbors := range myNeighbors {
		for _, neighbor := range neighbors {
			if neighbor.VipAddr.String() == ipAddr {
				return neighbor, nil
			}
		}
	}

	return nil, errors.Errorf("No interface with ip %s", ipAddr)
}

func GetNeighborsToInterface(ifaceName string) ([]*Neighbor, error) {
	if neighbors, ok := myNeighbors[ifaceName]; ok {
		return neighbors, nil
	}

	return nil, errors.Errorf("No interface with name %s", ifaceName)
}

func GetMyVIP() Interface {
	return myVIP
}

func GetInterfaces() []*Interface {
	return myInterfaces
}

func GetNeighbors() map[string][]*Neighbor {
	return myNeighbors
}

func GetRoutes() map[netip.Prefix]Hop {
	return routingTable
}

// ************************************** PRINT FUNCTIONS **********************************************************

func SprintInterfaces() {
	for _, iface := range myInterfaces {
		if iface.State {
			fmt.Printf("%s\t%s\t%s\n", iface.Name, iface.IpPrefix.String(), "UP")
		} else {
			fmt.Printf("%s\t%s\t%s\n", iface.Name, iface.IpPrefix.String(), "DOWN")
		}
	}
}

func SprintNeighbors() {
	for ifaceName, neighbor := range myNeighbors {
		for _, n := range neighbor {
			fmt.Printf("%s\t%s\t%s\n", ifaceName, n.VipAddr.String(), n.UdpAddr.String())
		}
	}
}

func SprintRoutingTable() {
	for prefix, hop := range routingTable {
		if hop.Type == "L" {
			fmt.Printf("%s\t%s\tLOCAL:%s\t%d\n", hop.Type, prefix.String(), hop.Interface.Name, 0)
		} else if hop.Type == "S" {
			fmt.Printf("%s\t%s\t%s\t%s\n", hop.Type, prefix.String(), hop.VIP.String(), "-")
		} else {
			fmt.Printf("%s\t%s\t%s\t%d\n", hop.Type, prefix.String(), hop.VIP.String(), hop.Cost)
		}
	}
}

func DebugNeighbors() {
	for ifaceName, neighbor := range myNeighbors {
		for _, n := range neighbor {
			fmt.Printf("%s\t%s\t%s\n", ifaceName, n.UdpAddr.String(), n.VipAddr.String())
		}
	}
}

// TODO @ MICHAEL:
// func RemoveNeighbor(neighbor Neighbor) {
// 	// TODO: remove from routing table
// 	myRoutes := GetRoutes()
// 	for prefix, hop := range myRoutes {
// 		if hop.VipAsStr == neighbor.VipAddr.String() {
// 			delete(myRoutes, prefix)
// 		}
// 	}

// 	// TODO: remove from myNeighbors
// 	myNeighbors[neighbor.VipAddr.String()] = nil

// 	// TODO: close the UDP socket
// 	err := neighbor.SendSocket.Close()
// 	if err != nil {
// 		fmt.Println("Error closing UDP socket", err)
// 	}

// }
// untested function above

// ************************************** 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) error {
	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.TTL--
	}

	// Assemble the header into a byte array
	headerBytes, err := hdr.Marshal()
	if err != nil {
		return 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)
	if err != nil {
		return errors.WithMessage(err, "Could not bind to UDP port->\t"+dest.UdpAddr.String())
	}

	bytesWritten, err := tmpConn.Write(bytesToSend)
	if err != nil {
		return err
	}

	fmt.Printf("Sent %d bytes to %s\n", bytesWritten, dest.VipAddr.String())

	return nil
}

func RecvIP(iface *Interface, isOpen *bool) error {
	fmt.Printf("Receiving IP packet on %s\n", iface.Name)

	// deconstruct interface
	prefix := iface.IpPrefix
	conn := iface.RecvSocket

	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 := conn.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")
	}
	if hdr.Dst == prefix.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(iface, 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(nil, 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(nil, neighbor, hdr.Protocol, message, hdr.Dst.String(), hdr)
					if err2 != nil {
						return err2
					}
				}
			}
		}
	}

	// if not in table, drop packet
	return nil
}

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

func periodicUpdateRoutine() {
	for {
		// 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,
				})
			// fmt.Printf("Sending RIP update: %s\t%d\t%d\n", prefix.Addr().String(), uint32(prefix.Bits()), hop.Cost)
		}

		// send to each neighbor
		for _, iface := range myInterfaces {
			for _, n := range myNeighbors[iface.Name] {
				_, in := myRIPNeighbors[n.VipAddr.String()]
				if !in {
					continue
				}
				message := NewRIPMessage(2, entries)
				err := SendRIPMessage(*iface, n, message)
				if err != nil {
					// fmt.Printf("Error sending RIP message to %s\n", n.VipAddr.String())
					continue
				}
			}
		}

		// wait 5 sec
		time.Sleep(5 * time.Second)
	}
}

//timeoutTable := make(map[netip.Addr]time.Time)
//func manageTimeoutsRoutine() {
//	for
//}

func startRipRoutines() {
	// send a request to every neighbor
	go func() {
		for _, iface := range myInterfaces {
			for _, neighbor := range myNeighbors[iface.Name] {
				// send a request
				message := NewRIPMessage(1, nil)
				err := SendRIPMessage(*iface, neighbor, message)
				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 {
	command := message[0]
	switch command {
	case 1:
		// request
		// SendUpdates()
		break
	case 2:
		numEntries := message[1]

		// parse the entries
		entries := make([]RIPEntry, 0, numEntries)
		for i := 0; i < int(numEntries); i++ {
			offset := SIZE_OF_RIP_MESSAGE + i*SIZE_OF_RIP_ENTRY

			// each field is 4 bytes
			address := binary.BigEndian.Uint32(message[offset : offset+4])
			mask := binary.BigEndian.Uint32(message[offset+4 : offset+8])
			cost := binary.BigEndian.Uint32(message[offset+8 : offset+12])

			// add to entries
			entries = append(entries, RIPEntry{address: address, mask: mask, cost: cost})
		}

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

			if address == "0.0.0.0" { // TODO: investigate this
				continue
			}

			prefix := netip.PrefixFrom(netip.MustParseAddr(address), int(entry.mask))
			// fmt.Println(prefix.String())

			// check if the entry is already in the routing table and update if need be
			if node, ok := routingTable[prefix.Masked()]; ok {
				if entry.cost < node.Cost {
					routingTable[prefix.Masked()] = Hop{entry.cost + 1, "R", src, hdr.Src}
				}
				continue
			}

			if entry.cost == 17 {
				routingTable[prefix.Masked()] = Hop{0, "R", src, hdr.Src}
			} else {
				routingTable[prefix.Masked()] = Hop{entry.cost + 1, "R", src, hdr.Src}
			}
		}
	}

	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 NewRIPMessage(command uint8, entries []RIPEntry) *RIPMessage {
	return &RIPMessage{
		command:    command,
		numEntries: uint8(len(entries)),
		entries:    entries,
	}
}

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 + 1 + 1 + len(message.entries)*12,
		ID:       0,
		Flags:    0,
		FragOff:  0,
		TTL:      32,
		Protocol: 12,
		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, len(headerBytes)+4+1+1+len(message.entries)*12)
	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

	for i, entry := range message.entries {
		offset := SIZE_OF_RIP_MESSAGE + i*SIZE_OF_RIP_ENTRY
		// each field is 4 bytes
		binary.BigEndian.PutUint32(buf[offset:offset+4], entry.address)
		binary.BigEndian.PutUint32(buf[offset+4:offset+8], entry.mask)
		binary.BigEndian.PutUint32(buf[offset+8:offset+12], entry.cost)
	}

	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())
	}
	_, err = tmpConn.Write(bytesToSend)
	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
					}
				}
			}

		}
	}
}

func ifaceContainsIP(iface Interface, ip netip.Addr) bool {
	// check if the ip is in the interface's prefix
	if iface.IpPrefix.Contains(netip.MustParseAddr(ip.String())) {
		return true
	}
	return false
}

func ConvertIPToUint32(ip string) uint32 {
	netIP := net.ParseIP(ip)
	ipBytes := netIP.To4()
	ipUint32 := uint32(ipBytes[0])<<24 | uint32(ipBytes[1])<<16 | uint32(ipBytes[2])<<8 | uint32(ipBytes[3])
	return ipUint32
}

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