dissertation-2-code/config/config.go

92 lines
1.7 KiB
Go
Raw Normal View History

2020-10-23 20:07:15 +01:00
package config
2021-01-23 17:13:06 +00:00
import (
"github.com/go-playground/validator/v10"
"log"
"net"
2021-01-23 17:42:17 +00:00
"strings"
2021-01-23 17:13:06 +00:00
)
2020-10-23 20:07:15 +01:00
var v = validator.New()
2021-01-23 17:13:06 +00:00
func init() {
if err := v.RegisterValidation("iface", func(fl validator.FieldLevel) bool {
name, ok := fl.Field().Interface().(string)
if ok {
ifaces, err := net.Interfaces()
if err != nil {
log.Printf("error getting interfaces: %v", err)
return false
}
for _, i := range ifaces {
if i.Name == name {
return true
}
}
}
return false
}); err != nil {
2021-01-23 17:46:01 +00:00
panic(err)
2021-01-23 17:13:06 +00:00
}
}
2020-10-23 20:07:15 +01:00
type Configuration struct {
Host Host
Peers []Peer `validate:"dive"`
}
type Host struct {
2020-12-21 14:51:32 +00:00
Crypto string `validate:"required,oneof=None Blake2s"`
2020-11-29 22:06:38 +00:00
SharedKey string `validate:"required_if=Crypto Blake2s"`
2021-03-26 11:58:03 +00:00
MTU uint
2020-10-23 20:07:15 +01:00
}
type Peer struct {
2020-12-21 14:51:32 +00:00
Method string `validate:"oneof=TCP UDP"`
2020-10-23 20:07:15 +01:00
2021-01-23 17:13:06 +00:00
LocalHost string `validate:"omitempty,ip|iface"`
2020-10-24 17:44:14 +01:00
LocalPort uint `validate:"max=65535"`
RemoteHost string `validate:"required_with=RemotePort,omitempty,fqdn|ip"`
RemotePort uint `validate:"required_with=RemoteHost,omitempty,max=65535"`
2020-12-11 18:03:47 +00:00
Congestion string `validate:"required_unless=Method TCP,omitempty,oneof=NewReno None"`
2020-11-26 22:26:01 +00:00
2020-10-24 17:44:14 +01:00
KeepAlive uint
Timeout uint
RetryWait uint
2020-10-23 20:07:15 +01:00
}
2021-01-23 17:13:06 +00:00
func (p Peer) GetLocalHost() string {
if err := v.Var(p.LocalHost, "ip"); err == nil {
return p.LocalHost
}
iface, err := net.InterfaceByName(p.LocalHost)
if err != nil {
panic(err)
}
if iface != nil {
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
if len(addrs) > 0 {
2021-01-23 17:20:52 +00:00
addr := addrs[0].String()
2021-01-23 17:42:17 +00:00
addr = strings.Split(addr, "/")[0]
2021-01-23 17:20:52 +00:00
log.Printf("resolved interface `%s` to `%v`", p.LocalHost, addr)
return addr
2021-01-23 17:13:06 +00:00
}
}
return "invalid"
}
2020-10-23 20:07:15 +01:00
func (c Configuration) Validate() error {
return v.Struct(c)
}