-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
475 lines (423 loc) · 12.2 KB
/
main.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
package main
import (
"bufio"
_ "embed"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"text/template"
"gopkg.in/yaml.v3"
)
type Config struct {
ConfigDir string `yaml:"config_dir"`
URTimezone string `yaml:"ur_timezone"`
OpenVPNClient bool `yaml:"ovpn_client_enable"`
OpenVPNClientCert string `yaml:"client.ovpn"`
OvpnClientRemove bool `yaml:"ovpnclient_remove"`
OpenVPNExtPort string `yaml:"openvpn_external_port"`
Eth2WifiEnable bool `yaml:"ethernet2wifi_enable"`
WifiSsid string `yaml:"wifi_ssid"`
WifiPass string `yaml:"wifi_password"`
WifiChannel string `yaml:"wifi_channel"`
WifiIntT1 string `yaml:"wifi_interface_t1"`
Wifi2Wifi bool `yaml:"wifi2wifi_enable"`
WifiModEnable bool `yaml:"wifi_mod_enable"`
WifiIntT2 string `yaml:"wifi_interface_t2"`
Wifi2EthEnable bool `yaml:"wifi2ethernet_enable"`
WifiConfigRemove bool `yaml:"wifi_config_remove"`
WifiModuleRemove bool `yaml:"wifi_module_remove"`
IPAddress string // to pass your IP address to the template
}
type InventoryConfig struct {
All struct {
Hosts struct {
Vpntv struct {
IP string `yaml:"ansible_host"`
AnsibleUser string `yaml:"ansible_user"`
AnsibleConnection string `yaml:"ansible_connection"`
AnsibleUse string `yaml:"ansible_use"`
} `yaml:"vpntv"`
} `yaml:"hosts"`
} `yaml:"all"`
}
//go:embed config.html
var configHTML string
func main() {
// Copy example.config.yml to config.yml
err := copyFile("example.config.yml", "config.yml")
copyFile("example.inventory.yml", "inventory.yml")
if err != nil {
log.Fatal(err)
}
//log.Printf("DBG: example.config.yml copied to config.yml")
//log.Printf("DBG: example.inventory.yml copied to inventory.yml")
// Truncate the webinstall.log file
f, err := os.OpenFile("webinstall.log", os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
defer f.Close()
//log.Printf("DBG: webinstall.log truncated")
// Write "announcement" to the webinstall.log file
if _, err := f.WriteString("Here will be the log of VPNTV installation progress, after you'll press \"Install\" button.\n"); err != nil {
log.Fatal(err)
}
//log.Printf("DBG: webinstall.log updated with \"announcement\"")
// Log the welcome message
log.Printf("Welcome! The web interface will guide you on installation process.\nInstallation logs: webinstall.log\n")
// Create a new router
r := http.NewServeMux()
// Register the routes
r.HandleFunc("/", editConfig)
r.HandleFunc("/save", saveConfig)
r.HandleFunc("/install", install)
r.HandleFunc("/webinstall.log", func(w http.ResponseWriter, r *http.Request) {
// Open the webinstall.log file
f, err := os.Open("webinstall.log")
if err != nil {
http.Error(w, "Error opening file", http.StatusInternalServerError)
return
}
defer f.Close()
// Create a new reader that reads from the file
reader := bufio.NewReader(f)
// Continuously read new lines from the file and write them to the response
for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
http.Error(w, "Error reading file", http.StatusInternalServerError)
return
}
_, err = w.Write([]byte(line))
if err != nil {
return
}
w.(http.Flusher).Flush()
}
})
// Handle file uploads
r.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
//log.Printf("DBG: /upload called from webui")
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
file, _, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// Get the type of configuration file to upload from the query parameter
fileType := r.URL.Query().Get("type")
if fileType == "" {
http.Error(w, "File type not specified", http.StatusBadRequest)
return
}
// Create a new file to write the uploaded file contents to
var filePath string
switch fileType {
case "openvpn":
filePath = "client-ovpn/client.ovpn"
case "openvpn-secret":
filePath = "client-ovpn/credentials.txt"
default:
http.Error(w, "Invalid file type specified", http.StatusBadRequest)
return
}
f, err := os.Create(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
//log.Printf("DBG: File created: %s", f.Name())
// Copy the contents of the uploaded file to the new file
_, err = io.Copy(f, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Printf("DBG: %s file upload successfully", fileType)
})
// Create a new server
srv := &http.Server{
Addr: ":8088",
Handler: r,
}
ip, err := getServerIP()
if err != nil {
log.Fatalf("Failed to get server IP: %v", err)
}
// Log the server startup message
log.Printf("Starting web server on http://%s%s\n", ip, srv.Addr)
// Start the server
err = srv.ListenAndServe()
if err != nil {
log.Fatal(err)
}
// Log the server shutdown message
log.Println("Server stopped.")
}
func getServerIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String(), nil
}
}
}
return "", nil
}
func readInventoryConfig() (InventoryConfig, error) {
var config InventoryConfig
file, err := os.Open("inventory.yml")
if err != nil {
return config, err
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return config, err
}
data := make([]byte, stat.Size())
_, err = file.Read(data)
if err != nil {
return config, err
}
err = yaml.Unmarshal(data, &config)
if err != nil {
return config, err
}
//log.Printf("DBG: Func Read inventory config. Data:\n")
//log.Printf("DBG: %+v", config)
return config, nil
}
func writeInventoryConfig(config InventoryConfig) error {
data, err := yaml.Marshal(config)
if err != nil {
return err
}
//log.Printf("Writing the following data to inventory.yml: %s", data)
file, err := os.Create("inventory.yml")
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
return err
}
//log.Printf("DBG: Func Write inventory config")
return nil
}
func editConfig(w http.ResponseWriter, r *http.Request) {
config, err := readConfig()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Printf("DBG: editConfig called. Starting to read inventory config")
inventoryConfig, err := readInventoryConfig()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Printf("DBG: inventory config read. Starting to get server IP")
ip, err := getServerIP()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
config.IPAddress = ip // Add the IP address to the config variable
tmpl, err := template.New("config").Parse(configHTML)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
type TemplateData struct {
Config Config
InventoryConfig InventoryConfig
}
//log.Printf("DBG: defined TemplateData struct. for inventory")
data := TemplateData{
Config: config,
InventoryConfig: inventoryConfig,
}
//log.Printf("DBG: defined data constan. Starting to combine template with data:\n")
//log.Printf("DBG: %+v", data)
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func saveConfig(w http.ResponseWriter, r *http.Request) {
config := Config{
ConfigDir: r.FormValue("config_dir"),
URTimezone: r.FormValue("ur_timezone"),
OpenVPNClient: r.FormValue("ovpn_client_enable") == "on",
OpenVPNClientCert: r.FormValue("ovpn_client_cert"),
OpenVPNExtPort: r.FormValue("openvpn_external_port"),
Eth2WifiEnable: r.FormValue("ethernet2wifi_enable") == "on",
WifiSsid: r.FormValue("wifi_ssid"),
WifiPass: r.FormValue("wifi_password"),
WifiIntT1: r.FormValue("wifi_interface"),
WifiChannel: r.FormValue("wifi_channel"),
Wifi2Wifi: r.FormValue("wifi2wifi_enable") == "on",
WifiModEnable: r.FormValue("wifi_mod_enable") == "on",
WifiIntT2: r.FormValue("wifi_interface_t2"),
Wifi2EthEnable: r.FormValue("wifi2ethernet_enable") == "on",
WifiConfigRemove: r.FormValue("wifi_config_remove") == "on",
WifiModuleRemove: r.FormValue("wifi_module_remove") == "on",
OvpnClientRemove: r.FormValue("ovpnclient_remove") == "on",
}
//log.Printf("DBG: Saving main config: %v", config)
err := writeConfig(config)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Printf("DBG: main config saved")
inventoryConfig := InventoryConfig{
All: struct {
Hosts struct {
Vpntv struct {
IP string `yaml:"ansible_host"`
AnsibleUser string `yaml:"ansible_user"`
AnsibleConnection string `yaml:"ansible_connection"`
AnsibleUse string `yaml:"ansible_use"`
} `yaml:"vpntv"`
} `yaml:"hosts"`
}{
Hosts: struct {
Vpntv struct {
IP string `yaml:"ansible_host"`
AnsibleUser string `yaml:"ansible_user"`
AnsibleConnection string `yaml:"ansible_connection"`
AnsibleUse string `yaml:"ansible_use"`
} `yaml:"vpntv"`
}{
Vpntv: struct {
IP string `yaml:"ansible_host"`
AnsibleUser string `yaml:"ansible_user"`
AnsibleConnection string `yaml:"ansible_connection"`
AnsibleUse string `yaml:"ansible_use"`
}{
IP: r.FormValue("vpntv_ip"),
AnsibleUser: r.FormValue("vpntv_ansible_user"),
AnsibleConnection: r.FormValue("vpntv_ansible_connection"),
AnsibleUse: r.FormValue("vpntv_ansible_use"),
},
},
},
}
//log.Printf("DBG: Inventory config saved. Starting writeInventoryConfig")
err = writeInventoryConfig(inventoryConfig)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Printf("DBG: writeInventoryConfig done. redirecting to /")
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func readConfig() (Config, error) {
var config Config
file, err := os.Open("config.yml")
if err != nil {
return config, err
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return config, err
}
data := make([]byte, stat.Size())
_, err = file.Read(data)
if err != nil {
return config, err
}
err = yaml.Unmarshal(data, &config)
if err != nil {
return config, err
}
return config, nil
}
func writeConfig(config Config) error {
if config.ConfigDir == "" {
config.ConfigDir = "~"
}
data, err := yaml.Marshal(config)
if err != nil {
return err
}
file, err := os.Create("config.yml")
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
return err
}
return nil
}
func copyFile(src, dst string) error {
input, err := os.ReadFile(src)
if err != nil {
return err
}
err = os.WriteFile(dst, input, 0644)
if err != nil {
return err
}
return nil
}
func install(w http.ResponseWriter, r *http.Request) {
go func() {
cmd := exec.Command("ansible-playbook", "main.yml", "-i", "inventory.yml")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
defer stdout.Close()
file, err := os.Create("webinstall.log")
if err != nil {
log.Fatal(err)
}
defer file.Close()
writer := io.MultiWriter(os.Stdout, file)
cmd.Stdout = writer
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
// Open the file in append mode and write the new line to it
f, err := os.OpenFile("webinstall.log", os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}
defer f.Close()
// Write "install complete" to the webinstall.log file
if _, err := f.WriteString("Installation completed! \nIf there is zero failed tasks - \"failed=0\", you good! \n"); err != nil {
log.Fatal(err)
log.Println("Installation completed!")
}
}()
http.Redirect(w, r, "/#install-form", http.StatusSeeOther)
}