-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathconfig.go
518 lines (486 loc) · 14 KB
/
config.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Package config provides functions for reading the config.
package config
import (
"encoding/json"
"errors"
"log/slog"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/gravitl/netclient/ncutils"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/models"
"github.com/sasha-s/go-deadlock"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
const (
// LinuxAppDataPath - linux path
LinuxAppDataPath = "/etc/netclient/"
// MacAppDataPath - mac path
MacAppDataPath = "/Applications/Netclient/"
// WindowsAppDataPath - windows path
WindowsAppDataPath = "C:\\Program Files (x86)\\Netclient\\"
// Timeout timelimit for obtaining/releasing lockfile
Timeout = time.Second * 5
// ConfigLockfile lockfile to control access to config file
ConfigLockfile = "config.lck"
// MaxNameLength maximum length of a node name
MaxNameLength = 62
// DefaultListenPort default port for wireguard
DefaultListenPort = 51821
// DefaultMTU default MTU for wireguard
DefaultMTU = 1420
)
const (
UnKnown InitType = iota
Systemd
SysVInit
Runit
OpenRC
Initd
)
const (
// DefaultHostID {0EF230F0-2EAD-4370-B0F9-AFC2D2A039E6} is a fixed string,
// for creating the unique GUID. It's a meaningless unique GUID here to
// make sure only one network profile is created.
DefaultHostID = "0EF230F0-2EAD-4370-B0F9-AFC2D2A039E6"
)
// Initype - the type of init system in use
type InitType int
// String - returns the string representation of the init type
func (i InitType) String() string {
return [...]string{"unknown", "systemd", "sysvinit", "runit", "openrc", "initd"}[i]
}
var (
netclientCfgMutex = &deadlock.RWMutex{}
netclient Config // netclient contains the netclient config
// Version - default version string
Version = "dev"
// FwClose - firewall manager shutdown func
FwClose func() = func() {}
// WgPublicListenPort - host's wireguard public listen port
WgPublicListenPort int
// HostPublicIP - host's public ipv4 endpoint
HostPublicIP net.IP
// HostPublicIP6 - host's public ipv6 endpoint
HostPublicIP6 net.IP
// HostNatType - host's NAT type
HostNatType string
)
// Config configuration for netclient and host as a whole
type Config struct {
models.Host
PrivateKey wgtypes.Key `json:"privatekey" yaml:"privatekey"`
TrafficKeyPrivate []byte `json:"traffickeyprivate" yaml:"traffickeyprivate"`
HostPeers []wgtypes.PeerConfig `json:"-" yaml:"-"`
InitType InitType `json:"inittype" yaml:"inittype"`
//for Internet gateway
OriginalDefaultGatewayIp net.IP `json:"original_default_gateway_ip_old" yaml:"original_default_gateway_ip_old"`
CurrGwNmIP net.IP `json:"curr_gw_nm_ip" yaml:"curr_gw_nm_ip"`
//for manage DNS
DNSManagerType string `json:"dns_manager_type" yaml:"dns_manager_type"`
NameServers []string `json:"name_servers" yaml:"name_servers"`
DNSSearch string `json:"dns_search" yaml:"dns_search"`
DNSOptions string `json:"dns_options" yaml:"dns_options"`
}
func init() {
Servers = make(map[string]Server)
Nodes = make(map[string]Node)
}
// UpdateNetclient updates the in memory version of the host configuration
func UpdateNetclient(c Config) {
netclientCfgMutex.Lock()
defer netclientCfgMutex.Unlock()
if c.Verbosity != logger.Verbosity {
slog.Info("Logging verbosity updated to", "verbosity", strconv.Itoa(logger.Verbosity))
}
logger.Verbosity = c.Verbosity
ncutils.SetVerbosity(c.Verbosity)
netclient = c
}
func UpdateHost(host *models.Host) (resetInterface, restart, sendHostUpdate bool) {
hostCfg := Netclient()
if hostCfg == nil || host == nil {
return
}
if host.ListenPort != 0 && hostCfg.ListenPort != host.ListenPort {
// check if new port is free, otherwise don't update
if !ncutils.IsPortFree(host.ListenPort) {
// send the host update to server with actual port on the interface
host.ListenPort = hostCfg.ListenPort
sendHostUpdate = true
}
restart = true
}
if host.MTU != 0 && hostCfg.MTU != host.MTU {
resetInterface = true
}
// do not update fields that should not be changed by server
host.OS = hostCfg.OS
host.FirewallInUse = hostCfg.FirewallInUse
host.DaemonInstalled = hostCfg.DaemonInstalled
host.ID = hostCfg.ID
host.Version = hostCfg.Version
host.MacAddress = hostCfg.MacAddress
host.PublicKey = hostCfg.PublicKey
host.TrafficKeyPublic = hostCfg.TrafficKeyPublic
// don't update any public ports coming from server,overwrite the values
host.WgPublicListenPort = hostCfg.WgPublicListenPort
if !host.IsStatic {
// don't update nil endpoint
if host.EndpointIP == nil {
host.EndpointIP = hostCfg.EndpointIP
}
if host.EndpointIPv6 == nil {
host.EndpointIPv6 = hostCfg.EndpointIPv6
}
}
// store password before updating
host.HostPass = hostCfg.HostPass
hostCfg.Host = *host
UpdateNetclient(*hostCfg)
WriteNetclientConfig()
return
}
// Netclient returns a pointer to the im memory version of the host configuration
func Netclient() *Config {
netclientCfgMutex.RLock()
defer netclientCfgMutex.RUnlock()
return &netclient
}
// UpdateHostPeers - updates host peer map in the netclient config
func UpdateHostPeers(peers []wgtypes.PeerConfig) {
netclientCfgMutex.Lock()
defer netclientCfgMutex.Unlock()
netclient.HostPeers = peers
}
// DeleteServerHostPeerCfg - deletes the host peers for the server
func DeleteServerHostPeerCfg() {
netclientCfgMutex.Lock()
defer netclientCfgMutex.Unlock()
netclient.HostPeers = []wgtypes.PeerConfig{}
}
// DeleteClientNodes - delete the nodes in client config
func DeleteClientNodes() {
netclientCfgMutex.Lock()
defer netclientCfgMutex.Unlock()
netclient.Nodes = []string{}
}
// RemoveServerHostPeerCfg - sets remove flag for all peers on the given server peers
func RemoveServerHostPeerCfg() {
netclient := Netclient()
if netclient.HostPeers == nil {
netclient.HostPeers = []wgtypes.PeerConfig{}
return
}
peers := netclient.HostPeers
for i := range peers {
peer := peers[i]
peer.Remove = true
peers[i] = peer
}
netclient.HostPeers = peers
UpdateNetclient(*netclient)
_ = WriteNetclientConfig()
}
// SetVersion - sets version for use by other packages
func SetVersion(ver string) {
Version = ver
}
// ReadNetclientConfig reads the host configuration file and returns it as an instance.
func ReadNetclientConfig() (*Config, error) {
netclientl := Config{}
var err error
defer func() {
if err == nil {
netclientCfgMutex.Lock()
netclient = Config{}
netclient = netclientl
netclientCfgMutex.Unlock()
}
}()
lockfile := filepath.Join(os.TempDir(), ConfigLockfile)
file := GetNetclientPath() + "netclient.json"
if _, err := os.Stat(file); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(GetNetclientPath(), os.ModePerm); err != nil {
slog.Info("error creating netclient config directory", "error", err.Error())
}
if err := os.Chmod(GetNetclientPath(), 0775); err != nil {
slog.Info("error setting permissions on netclient config directory", "error", err.Error())
}
err = WriteNetclientConfig()
if err != nil {
logger.FatalLog("failed to initialize netclient config", err.Error())
}
} else {
return nil, err
}
}
if err = Lock(lockfile); err != nil {
return nil, err
}
defer Unlock(lockfile)
f, ferr := os.Open(file)
if ferr != nil {
err = ferr
return nil, err
}
defer f.Close()
if err = json.NewDecoder(f).Decode(&netclientl); err != nil {
return nil, err
}
return &netclientl, nil
}
// WriteNetclientConfiig writes the in memory host configuration to disk
func WriteNetclientConfig() error {
lockfile := filepath.Join(os.TempDir(), ConfigLockfile)
file := GetNetclientPath() + "netclient.json"
if _, err := os.Stat(file); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(GetNetclientPath(), os.ModePerm); err != nil {
logger.Log(0, "error creating netclient config directory", err.Error())
}
if err := os.Chmod(GetNetclientPath(), 0775); err != nil {
logger.Log(0, "error setting permissions on netclient config directory", err.Error())
}
} else if err != nil {
return err
}
}
if lerr := Lock(lockfile); lerr != nil {
return errors.New("failed to obtain lockfile " + lerr.Error())
}
defer Unlock(lockfile)
f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY, 0700)
if err != nil {
return err
}
defer f.Close()
netclientCfgMutex.Lock()
netclientI := netclient
netclientCfgMutex.Unlock()
j := json.NewEncoder(f)
j.SetIndent("", " ")
err = j.Encode(netclientI)
if err != nil {
return err
}
return f.Sync()
}
// GetNetclientPath - returns path to netclient config directory
func GetNetclientPath() string {
if runtime.GOOS == "windows" {
return WindowsAppDataPath
} else if runtime.GOOS == "darwin" {
return MacAppDataPath
} else {
return LinuxAppDataPath
}
}
// GetNetclientInstallPath returns the full path where netclient should be installed based on OS
func GetNetclientInstallPath() string {
switch runtime.GOOS {
case "windows":
return GetNetclientPath() + "netclient.exe"
case "macos":
return "/usr/local/bin/netclient"
default:
return "/usr/bin/netclient"
}
}
// Lock creates a lockfile with pid as contents
// if lockfile exists but belongs to defunct process
// the existing lockfile will be deleted and new one created
// if unable to create within TIMEOUT returns error
func Lock(lockfile string) error {
debug := netclient.Debug
start := time.Now()
pid := os.Getpid()
if debug {
logger.Log(0, "lock try")
}
for {
if _, err := os.Stat(lockfile); !errors.Is(err, os.ErrNotExist) {
if debug {
logger.Log(0, "file exists")
}
bytes, err := os.ReadFile(lockfile)
if err != nil || len(bytes) == 0 {
_ = os.Remove(lockfile)
} else {
var owner int
if err := json.Unmarshal(bytes, &owner); err != nil {
_ = os.Remove(lockfile)
} else {
if IsPidDead(owner) {
if err := os.Remove(lockfile); err != nil && debug {
logger.Log(0, "error removing lockfile", err.Error())
}
}
}
}
} else {
bytes, _ := json.Marshal(pid)
if err := os.WriteFile(lockfile, bytes, os.ModePerm); err != nil && debug {
logger.Log(0, "unable to write to lockfile: ", err.Error())
} else {
return nil
}
}
if debug {
logger.Log(0, "unable to get lock")
}
if time.Since(start) > Timeout {
return errors.New("TIMEOUT")
}
time.Sleep(time.Millisecond * 100)
}
}
// Unlock removes a lockfile if contents of lockfile match current pid
// also removes lockfile if owner process is no longer running
// will return TIMEOUT error if timeout exceeded
func Unlock(lockfile string) error {
var pid int
debug := netclient.Debug
start := time.Now()
if debug {
logger.Log(0, "unlock try")
}
for {
bytes, err := os.ReadFile(lockfile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
if debug {
logger.Log(0, "error reading file", err.Error())
}
return err
}
if debug {
logger.Log(0, "lockfile exists")
}
if err := json.Unmarshal(bytes, &pid); err == nil {
if pid == os.Getpid() {
if err := os.Remove(lockfile); err == nil {
if debug {
logger.Log(0, "removed lockfile")
}
return nil
} else {
if debug {
logger.Log(0, "error removing file", err.Error())
}
}
} else {
if debug {
logger.Log(0, "wrong pid")
}
if IsPidDead(pid) {
if err := os.Remove(lockfile); err != nil && debug {
logger.Log(0, "error removing lockfile", err.Error())
}
}
}
} else {
if debug {
logger.Log(0, "unmarshal err ", err.Error())
}
}
if debug {
logger.Log(0, "unable to unlock")
}
if time.Since(start) > Timeout {
return errors.New("TIMEOUT")
}
time.Sleep(time.Millisecond * 100)
}
}
// IsPidDead checks if given pid is not running
func IsPidDead(pid int) bool {
process, err := os.FindProcess(pid)
if err != nil {
return true
}
//FindProcess always returns err = nil on linux
err = process.Signal(syscall.Signal(0))
return errors.Is(err, os.ErrProcessDone)
}
// FormatName ensures name is in character set and is proper length
// Sets name to blank on failure
func FormatName(name string) string {
if !InCharSet(name) {
name = ncutils.DNSFormatString(name)
}
if len(name) > MaxNameLength {
name = ncutils.ShortenString(name, MaxNameLength)
}
if !InCharSet(name) || len(name) > MaxNameLength {
logger.Log(1, "could not properly format name, setting to blank")
name = ""
}
return name
}
// InCharSet verifies if all chars in string are part of defined charset
func InCharSet(name string) bool {
charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
for _, char := range name {
if !strings.Contains(charset, strings.ToLower(string(char))) {
return false
}
}
return true
}
// Convert converts netclient host/node struct to netmaker host/node structs
func Convert(h *Config, n *Node) (models.Host, models.Node) {
var host models.Host
var node models.Node
temp, err := json.Marshal(h)
if err != nil {
logger.Log(0, "host marshal error", h.Name, err.Error())
}
if err := json.Unmarshal(temp, &host); err != nil {
logger.Log(0, "host unmarshal err", h.Name, err.Error())
}
temp, err = json.Marshal(n)
if err != nil {
logger.Log(0, "node marshal error", h.Name, err.Error())
}
if err := json.Unmarshal(temp, &node); err != nil {
logger.Log(0, "node unmarshal err", h.Name, err.Error())
}
return host, node
}
// setFirewall - determine and record firewall in use
func SetFirewall() {
if ncutils.IsLinux() {
if ncutils.IsIPTablesPresent() {
netclient.FirewallInUse = models.FIREWALL_IPTABLES
} else if ncutils.IsNFTablesPresent() {
netclient.FirewallInUse = models.FIREWALL_NFTABLES
} else {
netclient.FirewallInUse = models.FIREWALL_NONE
}
} else {
netclient.FirewallInUse = models.FIREWALL_NONE
}
}
// FirewallHasChanged - checks if the firewall has changed
func FirewallHasChanged() bool {
if netclient.FirewallInUse == models.FIREWALL_NONE && !ncutils.IsLinux() {
return false
}
if netclient.FirewallInUse == models.FIREWALL_IPTABLES && ncutils.IsIPTablesPresent() {
return false
}
if netclient.FirewallInUse == models.FIREWALL_NFTABLES && ncutils.IsNFTablesPresent() {
return false
}
return true
}