summaryrefslogtreecommitdiff
path: root/internal/config/config.go
blob: 06da9b3aecf2449b22fea9b83fe6365f569579dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Package config implements functions for saving a struct to a file
// It then provides functions to later read it such that we can restore the same struct
package config

import (
	"encoding/json"
	"log/slog"
	"os"
	"path"

	"codeberg.org/eduVPN/eduvpn-common/internal/config/atomicfile"
	"codeberg.org/eduVPN/eduvpn-common/internal/config/v1"
	"codeberg.org/eduVPN/eduvpn-common/internal/config/v2"
	"codeberg.org/eduVPN/eduvpn-common/internal/discovery"
	"codeberg.org/eduVPN/eduvpn-common/internal/util"
)

const stateFile = "state.json"

// Config represents the config state file
type Config struct {
	directory string
	// V2 indicates we are version 2
	V2 *v2.V2
}

func (c *Config) filename() string {
	return path.Join(c.directory, stateFile)
}

// Discovery gets the discovery list from the state file
func (c *Config) Discovery() *discovery.Discovery {
	return &c.V2.Discovery
}

// HasSecureInternet returns whether or not the configuration has a secure internet server
func (c *Config) HasSecureInternet() bool {
	return c.V2.HasSecureInternet()
}

// Save saves the state file to disk
func (c *Config) Save() error {
	if err := util.EnsureDirectory(c.directory); err != nil {
		return err
	}

	join := Versioned{V2: c.V2}
	cfg, err := json.Marshal(join)
	if err != nil {
		return err
	}
	if err = atomicfile.WriteFile(c.filename(), cfg, 0o600); err != nil {
		return err
	}
	return nil
}

// Load loads the state file from disk
func (c *Config) Load() error {
	bts, err := os.ReadFile(c.filename())
	if err != nil {
		return err
	}
	var buf Versioned
	if err = json.Unmarshal(bts, &buf); err != nil {
		return err
	}
	if buf.V2 != nil {
		c.V2 = buf.V2
		return nil
	}
	if buf.V1 != nil {
		c.V2 = v2.FromV1(buf.V1)
	}
	return nil
}

// Versioned is the final top-level state file that is written to disk
type Versioned struct {
	// V1 is the version 1 state file that is no longer used but converted from
	V1 *v1.V1 `json:"v1,omitempty"`
	// V2 is the version 2 state file
	V2 *v2.V2 `json:"v2,omitempty"`
}

// NewFromDirectory creates a new config struct from a directory
// It does this by loading the JSON file from disk
func NewFromDirectory(dir string) *Config {
	cfg := Config{
		directory: dir,
	}
	err := cfg.Load()
	if err != nil {
		slog.Debug("failed to load configuration", "error", err)
	}
	if cfg.V2 == nil {
		cfg.V2 = &v2.V2{}
	}
	return &cfg
}