2024-03-14 00:28:36 +01:00
|
|
|
package hvpnnode3
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
|
|
|
const UUID_PATH = "/etc/hvpn/uuid"
|
|
|
|
const CONFIG_PATH = "/etc/hvpn"
|
|
|
|
const UUIDV4_LEN = 16
|
|
|
|
|
|
|
|
// Gets or creates a UUID for this node
|
|
|
|
func InitNodeUUID() (*uuid.UUID, error) {
|
|
|
|
|
|
|
|
// TODO: check and write to os.UserHomeDir() to avoid root
|
|
|
|
_, err := os.Stat(UUID_PATH)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
|
|
slog.Info(UUID_PATH + " does not exist. Creating...")
|
|
|
|
return createNodeUUID()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-18 18:30:40 +01:00
|
|
|
slog.Debug("UUID: Reading UUID")
|
2024-03-14 00:28:36 +01:00
|
|
|
f, err := os.Open(UUID_PATH)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
buffer := make([]byte, UUIDV4_LEN)
|
|
|
|
n, err := f.Read(buffer)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
slog.Debug("UUID: Read " + fmt.Sprint(n) + "bytes" )
|
|
|
|
|
|
|
|
uuid, err := uuid.FromBytes(buffer)
|
|
|
|
return &uuid, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func createNodeUUID() (*uuid.UUID, error) {
|
2024-03-18 18:30:40 +01:00
|
|
|
uuid, err := uuid.NewRandom()
|
2024-03-14 00:28:36 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2024-03-18 18:30:40 +01:00
|
|
|
err = os.MkdirAll(CONFIG_PATH, 0755)
|
2024-03-14 00:28:36 +01:00
|
|
|
if err != nil {
|
2024-03-18 18:30:40 +01:00
|
|
|
slog.Error(err.Error())
|
|
|
|
slog.Warn("Could not create /etc/hvpn directory!")
|
|
|
|
slog.Info("Proccedig without saving node UUID")
|
|
|
|
return &uuid, nil
|
2024-03-14 00:28:36 +01:00
|
|
|
}
|
2024-03-18 18:30:40 +01:00
|
|
|
|
|
|
|
mode := os.O_RDWR | os.O_CREATE | os.O_EXCL
|
|
|
|
f, err := os.OpenFile(UUID_PATH, mode, 0644)
|
2024-03-14 00:28:36 +01:00
|
|
|
if err != nil {
|
2024-03-18 18:30:40 +01:00
|
|
|
slog.Error(err.Error())
|
|
|
|
slog.Warn("Could not open uuid file")
|
|
|
|
slog.Info("Proccedig without saving node UUID")
|
|
|
|
return &uuid, nil
|
2024-03-14 00:28:36 +01:00
|
|
|
}
|
|
|
|
n, err := f.Write(uuid[:])
|
|
|
|
if err != nil {
|
2024-03-18 18:30:40 +01:00
|
|
|
slog.Error(err.Error())
|
|
|
|
slog.Warn("Could not write to uuid file")
|
|
|
|
slog.Info("Proccesing without saving node UUID")
|
|
|
|
return &uuid, nil
|
2024-03-14 00:28:36 +01:00
|
|
|
}
|
|
|
|
slog.Debug("UUID: Wrote " + fmt.Sprint(n) + "bytes")
|
|
|
|
return &uuid, nil
|
|
|
|
}
|