2021-04-08 21:57:31 +00:00
|
|
|
package headscale
|
|
|
|
|
|
|
|
import (
|
2021-05-08 11:27:53 +00:00
|
|
|
"errors"
|
2021-04-08 21:57:31 +00:00
|
|
|
"log"
|
|
|
|
|
|
|
|
"tailscale.com/wgengine/wgcfg"
|
|
|
|
)
|
|
|
|
|
|
|
|
// RegisterMachine is executed from the CLI to register a new Machine using its MachineKey
|
2021-05-08 11:27:53 +00:00
|
|
|
func (h *Headscale) RegisterMachine(key string, namespace string) (*Machine, error) {
|
2021-04-08 21:57:31 +00:00
|
|
|
ns, err := h.GetNamespace(namespace)
|
|
|
|
if err != nil {
|
2021-05-08 11:27:53 +00:00
|
|
|
return nil, err
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|
|
|
|
mKey, err := wgcfg.ParseHexKey(key)
|
|
|
|
if err != nil {
|
2021-05-08 11:27:53 +00:00
|
|
|
return nil, err
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|
|
|
|
db, err := h.db()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Cannot open DB: %s", err)
|
2021-05-08 11:27:53 +00:00
|
|
|
return nil, err
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
m := Machine{}
|
|
|
|
if db.First(&m, "machine_key = ?", mKey.HexString()).RecordNotFound() {
|
2021-05-08 11:27:53 +00:00
|
|
|
return nil, errors.New("Machine not found")
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if m.isAlreadyRegistered() {
|
2021-05-08 11:27:53 +00:00
|
|
|
return nil, errors.New("Machine already registered")
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ip, err := h.getAvailableIP()
|
|
|
|
if err != nil {
|
2021-05-08 11:27:53 +00:00
|
|
|
return nil, err
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|
|
|
|
m.IPAddress = ip.String()
|
|
|
|
m.NamespaceID = ns.ID
|
|
|
|
m.Registered = true
|
2021-05-06 16:26:01 +00:00
|
|
|
m.RegisterMethod = "cli"
|
2021-04-08 21:57:31 +00:00
|
|
|
db.Save(&m)
|
2021-05-08 11:27:53 +00:00
|
|
|
return &m, nil
|
2021-04-08 21:57:31 +00:00
|
|
|
}
|