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

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

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

type Route struct {
	dest Address
	cost uint32
	mask netip.Prefix
}

var table map[Address]Route

//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(dest Address, cost uint32, mask netip.Prefix) error {
	if _, ok := table[dest]; ok {
		return errors.New("Route already exists")
	}

	table[dest] = Route{dest, cost, mask}
	return nil
}

func RemoveRoute(dest Address) 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 GetRoute(dest Address) (Route, error) {
	// get the most specific route
	for key, value := range table {
		if key.prefix.Contains(dest.addr) {
			return value, nil
		}
	}
	return Route{}, errors.New("Route doesn't exist")
}

func SprintRoutingTable() string {
	message := ""
	for address, route := range table {
		message += fmt.Sprintf("%s/%d\t%d\n", address.addr, address.prefix, route.cost)
	}

	return message
}