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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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-14 22:26:22 +01:00
|
|
|
err := os.MkdirAll(CONFIG_PATH, 0755)
|
2024-03-14 00:28:36 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
mode := os.O_RDWR | os.O_CREATE | os.O_EXCL
|
2024-03-14 22:26:22 +01:00
|
|
|
f, err := os.OpenFile(UUID_PATH, mode, 0644)
|
2024-03-14 00:28:36 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
uuid, err := uuid.NewRandom()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
n, err := f.Write(uuid[:])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
slog.Debug("UUID: Wrote " + fmt.Sprint(n) + "bytes")
|
|
|
|
return &uuid, nil
|
|
|
|
}
|