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() } } slog.Debug("UUID: Reading UUID") 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) { uuid, err := uuid.NewRandom() if err != nil { return nil, err } err = os.MkdirAll(CONFIG_PATH, 0755) if err != nil { slog.Error(err.Error()) slog.Warn("Could not create /etc/hvpn directory!") slog.Info("Proccedig without saving node UUID") return &uuid, nil } mode := os.O_RDWR | os.O_CREATE | os.O_EXCL f, err := os.OpenFile(UUID_PATH, mode, 0644) if err != nil { slog.Error(err.Error()) slog.Warn("Could not open uuid file") slog.Info("Proccedig without saving node UUID") return &uuid, nil } n, err := f.Write(uuid[:]) if err != nil { slog.Error(err.Error()) slog.Warn("Could not write to uuid file") slog.Info("Proccesing without saving node UUID") return &uuid, nil } slog.Debug("UUID: Wrote " + fmt.Sprint(n) + "bytes") return &uuid, nil }