-
Notifications
You must be signed in to change notification settings - Fork 31
/
uci.go
399 lines (344 loc) · 10.2 KB
/
uci.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package uci
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
)
// Tree defines the base directory for UCI config files. The default value
// on OpenWrt devices point to /etc/config, so that is what the default
// tree uses as well (you can access the default tree with the package level
// functions with the same signature as in this interface).
type Tree interface {
// LoadConfig reads a config file into memory and returns nil. If the
// config is already loaded, and forceReload is false, an error of type
// ErrConfigAlreadyLoaded is returned. Errors reading the config file
// are returned verbatim.
//
// You don't need to explicitly call LoadConfig(): Accessing configs
// (and their sections) via Get, Set, Add, Delete, DeleteAll will
// load missing files automatically.
LoadConfig(name string, forceReload bool) error
// Commit writes all changes back to the system.
//
// Note: this is not transaction safe. If, for whatever reason, the
// writing of any file fails, the succeeding files are left untouched
// while the preceding files are not reverted.
Commit() error
// Revert undoes changes to the config files given as arguments. If
// no argument is given, all changes are reverted. This clears the
// internal memory and does not access the file system.
Revert(configs ...string)
// GetSections returns the names of all sections of a certain type
// in a config, and an error indicating whether the operation was
// successful.
GetSections(config, secType string) ([]string, error)
// Get retrieves (all) values for a fully qualified option, and a
// boolean indicating whether the config file and the config section
// within exists.
Get(config, section, option string) ([]string, bool)
// GetLast retrieves the last value that was defined for a fully
// qualified option, and a boolean indicating whether the config file,
// config section and the option exists.
GetLast(config, section, option string) (string, bool)
// GetBool works the same way as GetLast does but interprets the last
// specified value as a boolean. If the found value can't be
// interpreted as either true or false, it will return nil and false.
GetBool(config, section, option string) (bool, bool)
// SetType replaces the fully qualified option with the given values.
// It returns whether the config file and section exists. For new
// files and sections, you first need to initialize them with
// AddSection().
SetType(config, section, option string, typ OptionType, values ...string) error
// Del removes a fully qualified option.
Del(config, section, option string) error
// AddSection adds a new config section. If the section already exists,
// and the types match (existing type and given type), nothing happens.
// Otherwise an ErrSectionTypeMismatch is returned.
AddSection(config, section, typ string) error
// DelSection remove a config section and its options.
DelSection(config, section string) error
}
type tree struct {
dir string
configs map[string]*config
sync.Mutex
}
var _ Tree = (*tree)(nil)
// NewTree constructs new RootDir pointing to root.
func NewTree(root string) Tree {
return &tree{
dir: root,
configs: make(map[string]*config),
}
}
func (t *tree) LoadConfig(name string, forceReload bool) error {
t.Lock()
defer t.Unlock()
var exists bool
if t.configs != nil {
_, exists = t.configs[name]
}
if exists && !forceReload {
return ErrConfigAlreadyLoaded{name}
}
return t.loadConfig(name)
}
// loadConfig actually reads a config file. Its call must be guarded by
// locking the tree's mutex.
func (t *tree) loadConfig(name string) error {
body, err := os.ReadFile(filepath.Join(t.dir, name))
if err != nil {
return fmt.Errorf("reading config file failed: %w", err)
}
cfg, err := parse(name, string(body))
if err != nil {
return fmt.Errorf("parse: %w", err)
}
if t.configs == nil {
t.configs = make(map[string]*config)
}
t.configs[name] = cfg
return nil
}
func (t *tree) Commit() error {
t.Lock()
defer t.Unlock()
for _, config := range t.configs {
if !config.tainted {
continue
}
err := t.saveConfig(config)
if err != nil {
return err
}
}
return nil
}
func (t *tree) Revert(configs ...string) {
t.Lock()
if len(configs) == 0 {
t.configs = nil
}
for _, config := range configs {
delete(t.configs, config)
}
t.Unlock()
}
func (t *tree) GetSections(config string, secType string) ([]string, error) {
cfg, err := t.ensureConfigLoaded(config)
if err != nil {
return nil, fmt.Errorf("ensureConfigLoaded: %w", err)
}
names := []string{}
for _, s := range cfg.Sections {
if s.Type == secType {
names = append(names, cfg.sectionName(s))
}
}
return names, nil
}
func (t *tree) Get(config, section, option string) ([]string, bool) {
t.Lock()
defer t.Unlock()
if vals, ok := t.lookupValues(config, section, option); ok {
return vals, true
}
if err := t.loadConfig(config); err != nil {
return nil, false
}
return t.lookupValues(config, section, option)
}
func (t *tree) GetLast(config, section, option string) (string, bool) {
vals, ok := t.Get(config, section, option)
if !ok || len(vals) == 0 {
return "", false
}
return vals[len(vals)-1], true
}
func (t *tree) GetBool(config, section, option string) (bool, bool) {
val, ok := t.GetLast(config, section, option)
if !ok {
return false, false
}
switch val {
case "1", "on", "true", "yes", "enabled":
return true, true
case "0", "off", "false", "no", "disabled":
return false, true
default:
return false, false
}
}
func (t *tree) ensureConfigLoaded(config string) (*config, error) {
cfg, ok := t.configs[config]
if !ok {
if err := t.loadConfig(config); err != nil {
return nil, fmt.Errorf("loadConfig: %w", err)
}
cfg = t.configs[config]
}
return cfg, nil
}
func (t *tree) lookupOption(config, section, option string) (*option, bool) {
cfg, ok := t.configs[config]
if !ok {
return nil, false
}
sec := cfg.Get(section)
if sec == nil {
return nil, false
}
return sec.Get(option), true
}
func (t *tree) lookupValues(config, section, option string) ([]string, bool) {
opt, ok := t.lookupOption(config, section, option)
if !ok {
return nil, false
}
if opt == nil {
return nil, true
}
return opt.Values, true
}
func (t *tree) SetType(config, section, option string, typ OptionType, values ...string) error {
t.Lock()
defer t.Unlock()
cfg, err := t.ensureConfigLoaded(config)
if err != nil {
return fmt.Errorf("ensureConfigLoaded: %w", err)
}
sec := cfg.Get(section)
if sec == nil {
return ErrSectionNotFound{Section: section}
}
if opt := sec.Get(option); opt != nil {
opt.SetValues(values...)
} else {
sec.Add(newOption(option, typ, values...))
}
cfg.tainted = true
return nil
}
func (t *tree) Del(config, section, option string) error {
t.Lock()
defer t.Unlock()
cfg, err := t.ensureConfigLoaded(config)
if err != nil {
// we want to delete option but this failed
return fmt.Errorf("ensureConfigLoaded: %w", err)
}
sec := cfg.Get(section)
if sec == nil {
// same logic applies here
return ErrSectionNotFound{Section: section}
}
if sec.Del(option) {
cfg.tainted = true
}
return nil
}
func (t *tree) AddSection(config, section, typ string) error {
t.Lock()
defer t.Unlock()
cfg, err := t.ensureConfigLoaded(config)
if err != nil {
if errors.Is(err, ParseError{}) {
return fmt.Errorf("ensureConfigLoaded: %w", err)
}
if errors.Is(err, os.ErrNotExist) {
// we want to add a section, but it failed to load. If this is a file not found error, we can
// just create a new config and add the section to it.
// if it is a parse error we want to return that error
cfg = newConfig(config)
cfg.tainted = true
t.configs[config] = cfg
}
}
sec := cfg.Get(section)
if sec == nil {
cfg.Add(newSection(typ, section))
cfg.tainted = true
return nil
}
if sec.Type != typ {
return ErrSectionTypeMismatch{config, section, sec.Type, typ}
}
return nil
}
func (t *tree) DelSection(config, section string) error {
t.Lock()
defer t.Unlock()
cfg, err := t.ensureConfigLoaded(config)
if err != nil {
return fmt.Errorf("ensureConfigLoaded: %w", err)
}
cfg.Del(section)
cfg.tainted = true
return nil
}
func (t *tree) saveConfig(c *config) error {
// We need to create a tempfile in the tree's base directory, since
// os.Rename fails when that directory and ioutil.Tempdir are on
// different file systems (os.Rename being not much more than a shim
// for syscall.Renameat).
//
// The full path for f will hence be "$root/.$rnd.$name", which
// translates to something like "/etc/config/.42.network" on
// OpenWrt devices.
//
// We rely a bit on the fact that UCI ignores dotfiles in /etc/config,
// so this should not interfere with normal operations when we leave
// incomplete files behind (for whatever reason).
f, err := newTmpFile(t.dir, ".*."+c.Name)
if err != nil {
return err
}
_, err = c.WriteTo(f)
if err != nil {
f.Close()
_ = f.Remove()
return err
}
if err = f.Chmod(0o644); err != nil {
f.Close()
_ = f.Remove()
return fmt.Errorf("save: failed to set permissions: %w", err)
}
if err = f.Sync(); err != nil {
f.Close()
_ = f.Remove()
return fmt.Errorf("save: failed to sync: %w", err)
}
f.Close()
if err = f.Rename(filepath.Join(t.dir, c.Name)); err != nil {
return fmt.Errorf("save: failed to replace existing config: %w", err)
}
c.tainted = false
return nil
}
// tmpFile is used by *tree.saveConfig to create/update a config file.
type tmpFile interface {
io.Writer
Chmod(os.FileMode) error
Close() error
Remove() error
Rename(string) error
Sync() error
}
// newTmpFile purely exists to be replaced in tests.
var newTmpFile = func(dir, pattern string) (tmpFile, error) {
f, err := os.CreateTemp(dir, pattern)
if err != nil {
return nil, fmt.Errorf("failed to create temp file: %w", err)
}
return &tmpFileImpl{f}, nil
}
type tmpFileImpl struct{ *os.File }
func (tmp *tmpFileImpl) Chmod(mode os.FileMode) error { return tmp.File.Chmod(mode) }
func (tmp *tmpFileImpl) Close() error { return tmp.File.Close() }
func (tmp *tmpFileImpl) Remove() error { return os.Remove(tmp.File.Name()) }
func (tmp *tmpFileImpl) Rename(newpath string) error { return os.Rename(tmp.File.Name(), newpath) }
func (tmp *tmpFileImpl) Sync() error { return tmp.File.Sync() }