-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublic.go
executable file
·433 lines (353 loc) · 9.3 KB
/
public.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
package webconfig
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/kambahr/go-mathsets"
)
// Refresh is the same as GetConfig. It reads the config from disk
// and fills-in the build-in fields accordingly.
func (c *Config) Refresh() {
c.GetConfig()
}
// GetJSON returns json of the Config struct.
func (c *Config) GetJSON() string {
b, err := json.Marshal(&c)
if err != nil {
fmt.Println(err)
return ""
}
s := fmt.Sprintf("%s", string(b))
s = strings.ReplaceAll(s, "\\u003e", ">")
s = strings.ReplaceAll(s, "\\u003c", "<")
return s
}
// hasSection check for the line(s) above to see if there
// a section.
func (c *Config) hasSection(lines []string, pos int) bool {
x := pos - 1
for {
if x < 1 {
break
}
l := strings.Trim(lines[x], " ")
if c.skipLine(l) {
x--
continue
}
v := strings.Split(l, " ")
if len(v) < 2 {
return true
}
x--
}
return false
}
// getData fills-in the Data section of the config.
func (c *Config) getData(line []string) {
inx := -1
for i := 0; i < len(line); i++ {
l := strings.Trim(line[i], " ")
if c.skipLine(l) || l == "" {
continue
}
if strings.HasPrefix(strings.ToLower(l), "data") {
inx = i
break
}
}
if inx < 0 {
// Data section was not found
return
}
// Go forward one
inx++
// Get the count of the map
dataCount := 0
for i := inx; i < len(line); i++ {
l := strings.Trim(line[i], " ")
if c.skipLine(l) || l == "" {
continue
}
dataCount++
}
// Split each line: as left/right (key/vlaue) and append to the Data map
c.Data = make(map[string]string, dataCount)
for i := inx; i < len(line); i++ {
l := strings.Trim(line[i], " ")
if c.skipLine(l) || l == "" {
continue
}
v := strings.Split(line[i], " ")
key := v[0]
val := ""
// account for multi-spaces between key and value.
for j := 1; j < len(v); j++ {
if v[j] != "" {
val = fmt.Sprintf("%s %s", val, v[j])
}
}
c.Data[key] = val
}
}
// GetConfig reads config values from file /appdata/.cfg.
// All values are part of a struct so lingering text in the config
// file will not be processed.
func (c *Config) GetConfig() {
f, err := ReadFile(c.ConfigFilePath)
if err != nil {
log.Fatal(err)
}
// do not process, if the file has not changed.
hs := fmt.Sprintf("%x", mathsets.Hash256Twice(f))
if hs == c.ConfigFileLastHash {
return
}
c.ConfigFileLastHash = hs
linex := strings.Split(string(f), "\n")
var line []string
// Begin with a blank line. If the frist section is on the first line,
// it may be skipped.
if len(linex) > 0 && linex[0] != "" && linex[0] != "#" {
line = append(line, "")
}
// Put the continuation of lines together.
// Also remove tabs and trime lines.
for i := 0; i < len(linex); i++ {
linex[i] = c.trimLine(linex[i])
if strings.HasSuffix(linex[i], "\\") {
// this and the next line
if (i + 1) >= len(linex) {
break
}
// Take out the \ at the end
linex[i] = linex[i][0 : len(linex[i])-1]
linex[i+1] = c.trimLine(linex[i+1])
s := fmt.Sprintf("%s%s", linex[i], linex[i+1])
line = append(line, s)
i++
continue
}
line = append(line, linex[i])
}
for i := 0; i < len(line); i++ {
l := strings.Trim(line[i], " ")
if c.skipLine(l) || l == "" {
continue
}
lLower := strings.ToLower(l)
if strings.HasPrefix(lLower, "maintenance-window") {
s := strings.ToLower(c.parseCofigLine(l, "maintenance-window"))
if s == "on" {
c.MaintenanceWindowOn = true
} else {
c.MaintenanceWindowOn = false
}
} else if strings.HasPrefix(lLower, "site") {
keys := []string{"hostname", "alternate-hostnames", "portno", "proto"}
i++
i = c.getConfigLeaves(line, i, "site", keys)
} else if strings.HasPrefix(lLower, "tls") {
keys := []string{"cert", "key"}
i++
i = c.getConfigLeaves(line, i, "tls", keys)
} else if strings.HasPrefix(lLower, "admin") {
keys := []string{"allowed-ip-addr", "run-on-startup", "portno"}
i++
i = c.getConfigLeaves(line, i, "admin", keys)
} else if strings.HasPrefix(lLower, "redirect-http-to-https") {
if strings.ToLower(c.parseCofigLine(l, "redirect-http-to-https")) == "yes" {
c.RedirectHTTPtoHTTPS = true
} else {
c.RedirectHTTPtoHTTPS = false
}
} else if strings.HasPrefix(lLower, "messagebanner") {
keys := []string{"display-mode", "seconds-to-display"}
i++
i = c.getConfigLeaves(line, i, "MessageBanner", keys)
} else if strings.HasPrefix(lLower, "http") {
keys := []string{"allowed-methods"}
i++
i = c.getConfigLeaves(line, i, "HTTP", keys)
} else if strings.HasPrefix(lLower, "urlpaths") {
keys := []string{"restrict-paths", "exclude-paths", "forward-paths", "conditional-http-service"}
i++
i = c.getConfigLeaves(line, i, "URLPaths", keys)
}
}
if c.MessageBanner.On && c.MessageBanner.SecondsToDisplay > 0 {
c.MessageBanner.TickCount = c.MessageBanner.SecondsToDisplay
go c.setTimeoutResetMsgBanner()
}
c.getData(line)
// Get the offenders
blockedIPPath := fmt.Sprintf("%s/.cfg/blocked-ip", c.AppDataPath)
if fileOrDirExists(blockedIPPath) {
f, err := ReadFile(blockedIPPath)
if err != nil {
log.Fatal(err)
}
line = strings.Split(string(f), "\n")
c.BlockedIP = make([]string, 0)
for i := 0; i < len(line); i++ {
l := strings.Trim(line[i], " ")
if strings.HasPrefix(l, "#") || l == "" {
continue
}
v := strings.Split(l, " ")
ip := v[0]
c.BlockedIP = append(c.BlockedIP, ip)
}
}
}
// UpdateConfigValue updates a value in the /.cfg/.all config file.
// parent is the name of the section (header). it should be blank, if
// if there is not section name.
// e.g.
//
// The following has no parent.
// hostname localhost
//
// and this one has a parent name and key/value
// TLS
// cert /usr/local/mydomain/appdata/tls/certx.pem
// key /usr/local/mydomain/appdata/tls/keyx.pem
func (c *Config) UpdateConfigValue(parent string, key string, newValue string) {
f, err := ReadFile(c.ConfigFilePath)
if err != nil {
log.Fatal(err)
}
key = strings.ToLower(key)
line := strings.Split(string(f), "\n")
for i := 0; i < len(line); i++ {
line[i] = strings.Replace(line[i], "\t", " ", -1)
line[i] = strings.TrimLeft(line[i], " ")
line[i] = strings.TrimRight(line[i], " ")
if c.skipLine(line[i]) {
continue
}
l := strings.ToLower(line[i])
if strings.HasPrefix(l, strings.ToLower(parent)) {
for {
i++
line[i] = strings.Replace(line[i], "\t", " ", -1)
line[i] = strings.TrimLeft(line[i], " ")
line[i] = strings.TrimRight(line[i], " ")
if i >= len(line) {
break
}
if c.skipLine(line[i]) {
continue
}
l = strings.ToLower(line[i])
if strings.HasPrefix(l, key) {
line[i] = fmt.Sprintf(" %s %s", key, newValue)
goto lblDone
}
}
}
}
lblDone:
// Write the lines to disk
fPath := fmt.Sprintf("%s/.cfg/.all.swap", c.AppDataPath)
fx, err := os.Create(fPath)
if err != nil {
log.Fatal(err)
}
// Remove extra lines
var line2 []string
count := len(line)
for i := 0; i < count; i++ {
line[i] = strings.Trim(line[i], " ")
if line[i] == "" {
if (i + 1) >= count {
break
}
if line[i+1] == "" {
continue
}
}
line2 = append(line2, line[i])
}
for i := 0; i < len(line2); i++ {
s := fmt.Sprintf("%s\n", line2[i])
fx.WriteString(s)
}
err = fx.Close()
if err == nil {
// replace the file
err = os.Rename(fPath, c.ConfigFilePath)
if err != nil {
fmt.Println(err)
}
}
// Refresh
c.GetConfig()
}
//--------------------------------------------------------------
// LoadJSONConfig loads json string containing comments into
// a map[string]interface{}. Comment lines must begin with a #.
// Use /* */ blocks to insert comments anywhere inside a JSON block.
// In addition to the raw format, map[string]interface{}, the content
// of the file is returned, in []byte (to unmarshall into a specific type).
func LoadJSONConfig(path string) (map[string]interface{}, []byte) {
var jsonStrArry string
if !fileOrDirExists(path) {
log.Fatal("config file does not exist")
}
b, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err.Error())
}
str := string(b)
lines := strings.Split(str, "\n")
var lines2 []string
for i := 0; i < len(lines); i++ {
s := lines[i]
s = strings.Trim(s, " ")
s = strings.ReplaceAll(lines[i], "\t", "")
if s == "" || strings.HasPrefix(s, "#") {
continue
}
// take out the inline comments
v := strings.Split(s, "#")
if len(v) > 1 {
s = v[0]
}
lines2 = append(lines2, s)
}
jsonStrArry = strings.Join(lines2, "")
jsonStrArry = RemovePhraseFromString(jsonStrArry, "/*", "*/")
b = []byte(jsonStrArry)
b = bytes.ReplaceAll(b, []byte(`\"`), []byte(`"`))
var m map[string]interface{}
json.Unmarshal(b, &m)
return m, b
}
// RemovePhraseFromString removes a phrase from a string.
func RemovePhraseFromString(s string, begin string, end string) string {
begin = strings.Trim(begin, " ")
end = strings.Trim(end, " ")
// Avoid recursion by using a label to go through
// many iterations until all target blocks of text are removed.
lblAgain:
i := strings.Index(s, begin)
if i < 0 {
// not found
return s
}
left := s[:i]
right := s[len(left):]
j := strings.Index(right, end)
right = right[j+len(end):]
s = fmt.Sprintf("%s%s", left, right)
i = strings.Index(s, begin)
if i > -1 {
goto lblAgain
}
return s
}