headscale/routes.go

74 lines
1.8 KiB
Go
Raw Normal View History

2021-04-28 10:55:29 -04:00
package headscale
import (
"encoding/json"
"errors"
"log"
"github.com/jinzhu/gorm/dialects/postgres"
"inet.af/netaddr"
)
// GetNodeRoutes returns the subnet routes advertised by a node (identified by
// namespace and node name)
func (h *Headscale) GetNodeRoutes(namespace string, nodeName string) (*[]netaddr.IPPrefix, error) {
m, err := h.GetMachine(namespace, nodeName)
if err != nil {
return nil, err
}
hi, err := m.GetHostInfo()
if err != nil {
return nil, err
}
return &hi.RoutableIPs, nil
}
// EnableNodeRoute enables a subnet route advertised by a node (identified by
// namespace and node name)
func (h *Headscale) EnableNodeRoute(namespace string, nodeName string, routeStr string) (*netaddr.IPPrefix, error) {
2021-04-28 10:55:29 -04:00
m, err := h.GetMachine(namespace, nodeName)
if err != nil {
return nil, err
2021-04-28 10:55:29 -04:00
}
hi, err := m.GetHostInfo()
if err != nil {
return nil, err
2021-04-28 10:55:29 -04:00
}
route, err := netaddr.ParseIPPrefix(routeStr)
if err != nil {
return nil, err
2021-04-28 10:55:29 -04:00
}
for _, rIP := range hi.RoutableIPs {
if rIP == route {
db, err := h.db()
if err != nil {
log.Printf("Cannot open DB: %s", err)
return nil, err
2021-04-28 10:55:29 -04:00
}
routes, _ := json.Marshal([]string{routeStr}) // TODO: only one for the time being, so overwriting the rest
m.EnabledRoutes = postgres.Jsonb{RawMessage: json.RawMessage(routes)}
db.Save(&m)
db.Close()
// THIS IS COMPLETELY USELESS.
// The peers map is stored in memory in the server process.
// Definetely not accessible from the CLI tool.
// We need RPC to the server - or some kind of 'needsUpdate' field in the DB
2021-04-28 10:55:29 -04:00
peers, _ := h.getPeers(*m)
h.pollMu.Lock()
for _, p := range *peers {
if pUp, ok := h.clientsPolling[uint64(p.ID)]; ok {
pUp <- []byte{}
}
}
h.pollMu.Unlock()
return &rIP, nil
2021-04-28 10:55:29 -04:00
}
}
return nil, errors.New("could not find routable range")
2021-04-28 10:55:29 -04:00
}