aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/ui/manage_tunnels.go
blob: 815dee00bc4fa5e0db60f4eaec9c06d3bde34193 (plain) (blame)
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
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
 */

package ui

import (
	"archive/zip"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strings"
	"time"

	"github.com/lxn/walk"
	"github.com/lxn/win"
	"golang.zx2c4.com/wireguard/windows/conf"
	"golang.zx2c4.com/wireguard/windows/service"
	"golang.zx2c4.com/wireguard/windows/ui/syntax"
)

type ManageTunnelsWindow struct {
	*walk.MainWindow

	icon *walk.Icon

	tunnelTracker          *TunnelTracker
	tunnelsView            *TunnelsView
	confView               *ConfView
	tunnelAddedPublisher   walk.StringEventPublisher
	tunnelDeletedPublisher walk.StringEventPublisher
}

func NewManageTunnelsWindow(icon *walk.Icon) (*ManageTunnelsWindow, error) {
	var err error

	mtw := &ManageTunnelsWindow{
		icon: icon,
	}
	mtw.MainWindow, err = walk.NewMainWindowWithName("WireGuard")
	if err != nil {
		return nil, err
	}

	return mtw, mtw.setup()
}

func (mtw *ManageTunnelsWindow) setup() error {
	mtw.SetIcon(mtw.icon)
	font, err := walk.NewFont("Segoe UI", 9, 0)
	if err != nil {
		return err
	}
	mtw.AddDisposable(font)
	mtw.SetFont(font)
	mtw.SetSize(walk.Size{900, 600})
	mtw.SetLayout(walk.NewVBoxLayout())
	mtw.Closing().Attach(func(canceled *bool, reason walk.CloseReason) {
		// "Close to tray" instead of exiting application
		onQuit()
	})

	splitter, _ := walk.NewHSplitter(mtw)
	splitter.SetSuspended(true)
	defer func() {
		splitter.SetSuspended(false)
	}()

	tunnelsContainer, _ := walk.NewComposite(splitter)
	tunnelsContainer.SetLayout(walk.NewVBoxLayout())

	splitter.SetFixed(tunnelsContainer, true)

	mtw.tunnelsView, _ = NewTunnelsView(tunnelsContainer)
	mtw.tunnelsView.ItemActivated().Attach(mtw.onEditTunnel)
	mtw.tunnelsView.CurrentIndexChanged().Attach(mtw.updateConfView)

	service.IPCClientRegisterTunnelChange(func(tunnel *service.Tunnel, state service.TunnelState, err error) {
		mtw.tunnelsView.Invalidate()
	})

	// ToolBar actions
	{
		// HACK: Because of https://github.com/lxn/walk/issues/481
		// we need to put the ToolBar into its own Composite.
		toolBarContainer, _ := walk.NewComposite(tunnelsContainer)
		toolBarContainer.SetLayout(walk.NewHBoxLayout())

		tunnelsToolBar, _ := walk.NewToolBar(toolBarContainer)

		importAction := walk.NewAction()
		importAction.SetText("Import tunnels from file...")
		importAction.Triggered().Attach(mtw.onImport)

		addAction := walk.NewAction()
		addAction.SetText("Add empty tunnel")
		addAction.Triggered().Attach(mtw.onAddTunnel)

		exportLogAction := walk.NewAction()
		exportLogAction.SetText("Export log to file...")
		// TODO: Triggered().Attach()

		exportTunnelAction := walk.NewAction()
		exportTunnelAction.SetText("Export tunnels to zip...")
		// TODO: Triggered().Attach()

		// TODO: Add this to the dispose array (AddDisposable)
		addMenu, _ := walk.NewMenu()
		addMenu.Actions().Add(addAction)
		addMenu.Actions().Add(importAction)
		addMenuAction, _ := tunnelsToolBar.Actions().AddMenu(addMenu)
		addMenuAction.SetText("Add")

		deleteAction := walk.NewAction()
		tunnelsToolBar.Actions().Add(deleteAction)
		deleteAction.SetText("Delete")
		deleteAction.Triggered().Attach(mtw.onDelete)

		settingsMenu, _ := walk.NewMenu()
		settingsMenu.Actions().Add(exportLogAction)
		settingsMenu.Actions().Add(exportTunnelAction)
		settingsMenuAction, _ := tunnelsToolBar.Actions().AddMenu(settingsMenu)
		settingsMenuAction.SetText("Export")
	}

	currentTunnelContainer, _ := walk.NewComposite(splitter)
	currentTunnelContainer.SetLayout(walk.NewVBoxLayout())

	mtw.confView, _ = NewConfView(currentTunnelContainer)
	go func() {
		// TODO: teardown in Dispose()
		t := time.NewTicker(time.Second)
		for range t.C {
			mtw.updateConfView()
		}
	}()

	// TODO: Find a better place for this?
	// logfile, err := service.IPCClientLogFilePath()
	// var logger *ringlogger.Ringlogger
	// if err == nil {
	// 	logger, err = ringlogger.NewRinglogger(logfile, "GUI")
	// }
	// if err != nil {
	// 	walk.MsgBox(nil, "Unable to initialize logging", fmt.Sprintf("%v\n\nFile: %s", err, logfile), walk.MsgBoxIconError)
	// 	return err
	// }
	// NewLogView(currentTunnelContainer, logger)

	controlsContainer, _ := walk.NewComposite(currentTunnelContainer)
	controlsContainer.SetLayout(walk.NewHBoxLayout())
	controlsContainer.Layout().SetMargins(walk.Margins{})

	walk.NewHSpacer(controlsContainer)

	editTunnel, _ := walk.NewPushButton(controlsContainer)
	editTunnel.SetEnabled(false)
	mtw.tunnelsView.CurrentIndexChanged().Attach(func() {
		editTunnel.SetEnabled(mtw.tunnelsView.CurrentIndex() > -1)
	})
	editTunnel.SetText("Edit")
	editTunnel.Clicked().Attach(mtw.onEditTunnel)

	return nil
}

func (mtw *ManageTunnelsWindow) Show() {
	mtw.MainWindow.Show()
	// TODO: Upstream lxn/walk has VisibleChanged()
	mtw.updateConfView()
	win.SetForegroundWindow(mtw.Handle())
	win.BringWindowToTop(mtw.Handle())
}

func (mtw *ManageTunnelsWindow) TunnelTracker() *TunnelTracker {
	return mtw.tunnelTracker
}

func (mtw *ManageTunnelsWindow) SetTunnelTracker(tunnelTracker *TunnelTracker) {
	mtw.tunnelTracker = tunnelTracker

	mtw.confView.SetTunnelTracker(tunnelTracker)
}

func (mtw *ManageTunnelsWindow) SetTunnelState(tunnel *service.Tunnel, state service.TunnelState) {
	mtw.tunnelsView.SetTunnelState(tunnel, state)
	// mtw.confView.SetTunnelState(tunnel, state)
}

func (mtw *ManageTunnelsWindow) updateConfView() {
	if !mtw.Visible() {
		return
	}

	mtw.confView.SetTunnel(mtw.tunnelsView.CurrentTunnel())
}

func (mtw *ManageTunnelsWindow) runTunnelEdit(tunnel *service.Tunnel) *conf.Config {
	var (
		title  string
		name   string
		config conf.Config
	)

	if tunnel == nil {
		// Creating a new tunnel, create a new private key and use the default template
		title = "Create new tunnel"
		name = "New tunnel"
		pk, _ := conf.NewPrivateKey()
		config = conf.Config{Interface: conf.Interface{PrivateKey: *pk}}
	} else {
		title = "Edit tunnel"
		name = tunnel.Name
		config, _ = tunnel.StoredConfig()
	}

	dlg, _ := walk.NewDialog(mtw)
	dlg.SetIcon(mtw.icon)
	dlg.SetTitle(title)
	dlg.SetLayout(walk.NewGridLayout())
	// TODO: use size hints in layout elements to communicate the minimal width
	dlg.SetMinMaxSize(walk.Size{500, 400}, walk.Size{9999, 9999})
	dlg.Layout().(*walk.GridLayout).SetColumnStretchFactor(1, 3)
	dlg.Layout().SetSpacing(6)
	dlg.Layout().SetMargins(walk.Margins{18, 18, 18, 18})

	nameLabel, _ := walk.NewTextLabel(dlg)
	dlg.Layout().(*walk.GridLayout).SetRange(nameLabel, walk.Rectangle{0, 0, 1, 1})
	nameLabel.SetTextAlignment(walk.AlignHFarVCenter)
	nameLabel.SetText("Name:")

	nameEdit, _ := walk.NewLineEdit(dlg)
	dlg.Layout().(*walk.GridLayout).SetRange(nameEdit, walk.Rectangle{1, 0, 1, 1})
	// TODO: compute the next available tunnel name ?
	nameEdit.SetText(name)

	pubkeyLabel, _ := walk.NewTextLabel(dlg)
	dlg.Layout().(*walk.GridLayout).SetRange(pubkeyLabel, walk.Rectangle{0, 1, 1, 1})
	pubkeyLabel.SetTextAlignment(walk.AlignHFarVCenter)
	pubkeyLabel.SetText("Public key:")

	pubkeyEdit, _ := walk.NewLineEdit(dlg)
	dlg.Layout().(*walk.GridLayout).SetRange(pubkeyEdit, walk.Rectangle{1, 1, 1, 1})
	pubkeyEdit.SetReadOnly(true)
	pubkeyEdit.SetText("(unknown)")

	syntaxEdit, _ := syntax.NewSyntaxEdit(dlg)
	dlg.Layout().(*walk.GridLayout).SetRange(syntaxEdit, walk.Rectangle{0, 2, 2, 1})
	lastPrivate := ""
	syntaxEdit.PrivateKeyChanged().Attach(func(privateKey string) {
		if privateKey == lastPrivate {
			return
		}
		lastPrivate = privateKey
		key, _ := conf.NewPrivateKeyFromString(privateKey)
		if key != nil {
			pubkeyEdit.SetText(key.Public().String())
		} else {
			pubkeyEdit.SetText("(unknown)")
		}
	})
	syntaxEdit.SetText(config.ToWgQuick())

	buttonsContainer, _ := walk.NewComposite(dlg)
	dlg.Layout().(*walk.GridLayout).SetRange(buttonsContainer, walk.Rectangle{0, 3, 2, 1})
	buttonsContainer.SetLayout(walk.NewHBoxLayout())
	buttonsContainer.Layout().SetMargins(walk.Margins{})

	walk.NewHSpacer(buttonsContainer)

	saveButton, _ := walk.NewPushButton(buttonsContainer)
	saveButton.SetText("Save")
	saveButton.Clicked().Attach(func() {
		newName := nameEdit.Text()
		if newName == "" {
			walk.MsgBox(mtw, "Invalid configuration", "Name is required", walk.MsgBoxIconWarning)
			return
		}

		if tunnel != nil && tunnel.Name != newName {
			names, err := conf.ListConfigNames()
			if err != nil {
				walk.MsgBox(mtw, "Error", err.Error(), walk.MsgBoxIconError)
				return
			}

			for _, name := range names {
				if name == newName {
					walk.MsgBox(mtw, "Invalid configuration", fmt.Sprintf("Another tunnel already exists with the name ‘%s’.", newName), walk.MsgBoxIconWarning)
					return
				}
			}
		}

		if !conf.TunnelNameIsValid(newName) {
			walk.MsgBox(mtw, "Invalid configuration", fmt.Sprintf("Tunnel name ‘%s’ is invalid.", newName), walk.MsgBoxIconWarning)
			return
		}

		cfg, err := conf.FromWgQuick(syntaxEdit.Text(), newName)
		if err != nil {
			walk.MsgBox(mtw, "Error", err.Error(), walk.MsgBoxIconError)
			return
		}

		config = *cfg

		dlg.Accept()
	})

	cancelButton, _ := walk.NewPushButton(buttonsContainer)
	cancelButton.SetText("Cancel")
	cancelButton.Clicked().Attach(dlg.Cancel)

	dlg.SetCancelButton(cancelButton)
	dlg.SetDefaultButton(saveButton)

	if dlg.Run() == walk.DlgCmdOK {
		// Save
		return &config
	}

	return nil
}

// importFiles tries to import a list of configurations.
func (mtw *ManageTunnelsWindow) importFiles(paths []string) {
	type unparsedConfig struct {
		Name   string
		Config string
	}

	var (
		unparsedConfigs []unparsedConfig
		lastErr         error
	)

	// Note: other versions of WireGuard start with all .zip files, then all .conf files.
	// To reproduce that if needed, inverse-sort the array.
	for _, path := range paths {
		switch filepath.Ext(path) {
		case ".conf":
			textConfig, err := ioutil.ReadFile(path)
			if err != nil {
				lastErr = err
				continue
			}
			unparsedConfigs = append(unparsedConfigs, unparsedConfig{Name: strings.TrimSuffix(filepath.Base(path), ".conf"), Config: string(textConfig)})
		case ".zip":
			// 1 .conf + 1 error .zip edge case?
			r, err := zip.OpenReader(path)
			if err != nil {
				lastErr = err
				continue
			}

			for _, f := range r.File {
				if filepath.Ext(f.Name) != ".conf" {
					continue
				}

				rc, err := f.Open()
				if err != nil {
					lastErr = err
					continue
				}
				textConfig, err := ioutil.ReadAll(rc)
				rc.Close()
				if err != nil {
					lastErr = err
					continue
				}
				unparsedConfigs = append(unparsedConfigs, unparsedConfig{Name: strings.TrimSuffix(filepath.Base(f.Name), ".conf"), Config: string(textConfig)})
			}

			r.Close()
		}
	}

	if lastErr != nil || unparsedConfigs == nil {
		walk.MsgBox(mtw, "Error", fmt.Sprintf("Could not parse some files: %v", lastErr), walk.MsgBoxIconWarning)
		return
	}

	var configs []*conf.Config

	for _, unparsedConfig := range unparsedConfigs {
		config, err := conf.FromWgQuick(unparsedConfig.Config, unparsedConfig.Name)
		if err != nil {
			lastErr = err
			continue
		}
		service.IPCClientNewTunnel(config)
		configs = append(configs, config)
	}

	m, n := len(configs), len(unparsedConfigs)
	switch {
	case n == 1 && m != n:
		walk.MsgBox(mtw, "Error", fmt.Sprintf("Could not parse some files: %v", lastErr), walk.MsgBoxIconWarning)
	case n == 1 && m == n:
		// TODO: Select tunnel in the list
	case m == n:
		walk.MsgBox(mtw, "Imported tunnels", fmt.Sprintf("Imported %d tunnels", m), walk.MsgBoxOK)
	case m != n:
		walk.MsgBox(mtw, "Imported tunnels", fmt.Sprintf("Imported %d of %d tunnels", m, n), walk.MsgBoxIconWarning)
	default:
		panic("unreachable case")
	}
}

func (mtw *ManageTunnelsWindow) addTunnel(config *conf.Config) {
	tunnel, err := service.IPCClientNewTunnel(config)
	if err != nil {
		walk.MsgBox(mtw, "Unable to create tunnel", err.Error(), walk.MsgBoxIconError)
		return
	}

	model := mtw.tunnelsView.model
	model.tunnels = append(model.tunnels, tunnel)
	model.PublishRowsReset()
	model.Sort(model.SortedColumn(), model.SortOrder())

	for i, t := range model.tunnels {
		if t.Name == tunnel.Name {
			mtw.tunnelsView.SetCurrentIndex(i)
			break
		}
	}

	mtw.confView.SetTunnel(&tunnel)

	mtw.tunnelAddedPublisher.Publish(tunnel.Name)
}

func (mtw *ManageTunnelsWindow) deleteTunnel(tunnel *service.Tunnel) {
	tunnel.Delete()

	model := mtw.tunnelsView.model

	for i, t := range model.tunnels {
		if t.Name == tunnel.Name {
			model.tunnels = append(model.tunnels[:i], model.tunnels[i+1:]...)
			model.PublishRowsRemoved(i, i)
			break
		}
	}

	mtw.tunnelDeletedPublisher.Publish(tunnel.Name)
}

func (mtw *ManageTunnelsWindow) TunnelAdded() *walk.StringEvent {
	return mtw.tunnelAddedPublisher.Event()
}

func (mtw *ManageTunnelsWindow) TunnelDeleted() *walk.StringEvent {
	return mtw.tunnelDeletedPublisher.Event()
}

// Handlers

func (mtw *ManageTunnelsWindow) onEditTunnel() {
	tunnel := mtw.tunnelsView.CurrentTunnel()
	if tunnel == nil {
		// Misfired event?
		return
	}

	if config := mtw.runTunnelEdit(tunnel); config != nil {
		// Delete old one
		mtw.deleteTunnel(tunnel)

		// Save new one
		mtw.addTunnel(config)
	}
}

func (mtw *ManageTunnelsWindow) onAddTunnel() {
	if config := mtw.runTunnelEdit(nil); config != nil {
		// Save new
		mtw.addTunnel(config)
	}
}

func (mtw *ManageTunnelsWindow) onDelete() {
	currentTunnel := mtw.tunnelsView.CurrentTunnel()
	if currentTunnel == nil {
		// Misfired event?
		return
	}

	if walk.DlgCmdNo == walk.MsgBox(
		mtw,
		fmt.Sprintf(`Delete "%s"`, currentTunnel.Name),
		fmt.Sprintf(`Are you sure you want to delete "%s"?`, currentTunnel.Name),
		walk.MsgBoxYesNo|walk.MsgBoxIconWarning) {
		return
	}

	mtw.deleteTunnel(currentTunnel)

	mtw.tunnelDeletedPublisher.Publish(currentTunnel.Name)
}

func (mtw *ManageTunnelsWindow) onImport() {
	dlg := &walk.FileDialog{}
	// dlg.InitialDirPath
	dlg.Filter = "Configuration Files (*.zip, *.conf)|*.zip;*.conf|All Files (*.*)|*.*"
	dlg.Title = "Import tunnel(s) from file..."

	if ok, _ := dlg.ShowOpenMultiple(mtw); !ok {
		return
	}

	mtw.importFiles(dlg.FilePaths)
}