2021-04-08 15:57:31 -06:00
|
|
|
package headscale
|
|
|
|
|
|
|
|
import (
|
2021-05-08 05:27:53 -06:00
|
|
|
"errors"
|
2021-04-08 15:57:31 -06:00
|
|
|
"log"
|
|
|
|
|
2021-06-24 07:44:19 -06:00
|
|
|
"gorm.io/gorm"
|
2021-06-25 10:57:08 -06:00
|
|
|
"tailscale.com/types/wgkey"
|
2021-04-08 15:57:31 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
// RegisterMachine is executed from the CLI to register a new Machine using its MachineKey
|
2021-05-08 05:27:53 -06:00
|
|
|
func (h *Headscale) RegisterMachine(key string, namespace string) (*Machine, error) {
|
2021-04-08 15:57:31 -06:00
|
|
|
ns, err := h.GetNamespace(namespace)
|
|
|
|
if err != nil {
|
2021-05-08 05:27:53 -06:00
|
|
|
return nil, err
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|
2021-06-25 10:57:08 -06:00
|
|
|
mKey, err := wgkey.ParseHex(key)
|
2021-04-08 15:57:31 -06:00
|
|
|
if err != nil {
|
2021-05-08 05:27:53 -06:00
|
|
|
return nil, err
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|
|
|
|
db, err := h.db()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Cannot open DB: %s", err)
|
2021-05-08 05:27:53 -06:00
|
|
|
return nil, err
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|
|
|
|
m := Machine{}
|
2021-06-24 07:44:19 -06:00
|
|
|
if result := db.First(&m, "machine_key = ?", mKey.HexString()); errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
2021-05-08 05:27:53 -06:00
|
|
|
return nil, errors.New("Machine not found")
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if m.isAlreadyRegistered() {
|
2021-05-08 05:27:53 -06:00
|
|
|
return nil, errors.New("Machine already registered")
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
ip, err := h.getAvailableIP()
|
|
|
|
if err != nil {
|
2021-05-08 05:27:53 -06:00
|
|
|
return nil, err
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|
|
|
|
m.IPAddress = ip.String()
|
|
|
|
m.NamespaceID = ns.ID
|
|
|
|
m.Registered = true
|
2021-05-06 10:26:01 -06:00
|
|
|
m.RegisterMethod = "cli"
|
2021-04-08 15:57:31 -06:00
|
|
|
db.Save(&m)
|
2021-05-08 05:27:53 -06:00
|
|
|
return &m, nil
|
2021-04-08 15:57:31 -06:00
|
|
|
}
|