Skip to content

Commit

Permalink
improve errors for missing directories
Browse files Browse the repository at this point in the history
Signed-off-by: Kristoffer Dalby <[email protected]>
  • Loading branch information
kradalby committed Feb 16, 2024
1 parent 1b01b9e commit 2e0fb7b
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions hscontrol/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
_ "net/http/pprof" //nolint
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
Expand Down Expand Up @@ -70,6 +71,7 @@ const (
AuthPrefix = "Bearer "
updateInterval = 5000
privateKeyFileMode = 0o600
headscaleDirPerm = 0o700

registerCacheExpiration = time.Minute * 15
registerCacheCleanup = time.Minute * 20
Expand Down Expand Up @@ -556,6 +558,12 @@ func (h *Headscale) Serve() error {
return fmt.Errorf("unable to remove old socket file: %w", err)
}

socketDir := filepath.Dir(h.cfg.UnixSocket)
err = ensureDir(socketDir)
if err != nil {
return fmt.Errorf("setting up unix socket: %w", err)
}

socketListener, err := net.Listen("unix", h.cfg.UnixSocket)
if err != nil {
return fmt.Errorf("failed to set up gRPC socket: %w", err)
Expand Down Expand Up @@ -923,6 +931,12 @@ func notFoundHandler(
}

func readOrCreatePrivateKey(path string) (*key.MachinePrivate, error) {
dir := filepath.Dir(path)
err := ensureDir(dir)
if err != nil {
return nil, fmt.Errorf("ensuring private key directory: %w", err)
}

privateKey, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
log.Info().Str("path", path).Msg("No private key file at path, creating...")
Expand Down Expand Up @@ -959,3 +973,21 @@ func readOrCreatePrivateKey(path string) (*key.MachinePrivate, error) {

return &machineKey, nil
}

func ensureDir(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, headscaleDirPerm)
if err != nil {
if errors.Is(err, os.ErrPermission) {
return fmt.Errorf(
"creating directory %s, failed with permission error, is it located somewhere Headscale can write?",
dir,
)
}

return fmt.Errorf("creating directory %s: %w", dir, err)
}
}

return nil
}

0 comments on commit 2e0fb7b

Please sign in to comment.