aboutsummaryrefslogtreecommitdiff
path: root/pkg/routingtable/routingtable.go
blob: 90b64ae0385d24d164a75778f6a1085f8882dc21 (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
package routingtable

import (
	"fmt"
	"github.com/pkg/errors"
	"net/netip"
)

type Address struct {
	Addr   netip.Addr
	Prefix netip.Prefix
}

type Hop struct {
	Cost     uint32
	VipAsStr string
}

type RoutingTable map[Address]Hop

const (
	STATIC_COST uint32 = 4294967295 // 2^32 - 1
)

// TODO: consider making this take in arguments, such as a config file
func New() *RoutingTable {
	var table = make(RoutingTable)
	return &table
}

//func Initialize(config lnxconfig.IPConfig) error {
//	if len(os.Args) != 2 {
//		fmt.Printf("Usage:  %s <configFile>\n", os.Args[0])
//		os.Exit(1)
//	}
//	fileName := os.Args[1]
//
//	lnxConfig, err := lnxconfig.ParseConfig(fileName)
//	if err != nil {
//		panic(err)
//	}
//
//	// make and populate routing table
//	table = make(map[Address]Route)
//	for _, iface := range lnxConfig.Interfaces {
//		var address = Address{iface.AssignedIP, iface.AssignedPrefix}
//		var route = Route{Address{iface.AssignedIP, iface.AssignedPrefix}, 0, iface.AssignedPrefix}
//		table[address] = route
//	}
//
//
//}

func AddRoute(srcAddr Address, cost uint32, addrAsStr string, tableReference *RoutingTable) error {
	if _, ok := (*tableReference)[srcAddr]; ok {
		return errors.New("Route already exists")
	}

	(*tableReference)[srcAddr] = Hop{cost, addrAsStr}
	return nil
}

func RemoveRoute(dest Address, table *RoutingTable) error {
	if _, ok := (*table)[dest]; !ok {
		return errors.New("Route doesn't exist")
	}

	delete(*table, dest)
	return nil
}

// TODO: implement this with most specific prefix matching
func Route(dest Address, table *RoutingTable) (Hop, error) {
	// get the most specific route
	for address, route := range *table {
		if address.Prefix.Contains(dest.Addr) {
			return route, nil
		}
	}
	return Hop{}, errors.New("Route doesn't exist")
}

func SprintRoutingTable(table *RoutingTable) string {
	message := ""
	for address, route := range *table {
		message += fmt.Sprintf("%s/%d\t%d\n", address.Addr, address.Prefix, route.Cost)
	}

	return message
}