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
|
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
*/
package ui
import (
"archive/zip"
"fmt"
"github.com/lxn/walk"
"github.com/lxn/win"
"golang.zx2c4.com/wireguard/windows/conf"
"golang.zx2c4.com/wireguard/windows/service"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"unsafe"
)
type TunnelsPage struct {
*walk.TabPage
listView *ListView
listContainer walk.Container
listToolbar *walk.ToolBar
confView *ConfView
fillerButton *walk.PushButton
fillerHandler func()
fillerContainer *walk.Composite
currentTunnelContainer *walk.Composite
}
func NewTunnelsPage() (*TunnelsPage, error) {
var err error
var disposables walk.Disposables
defer disposables.Treat()
tp := new(TunnelsPage)
if tp.TabPage, err = walk.NewTabPage(); err != nil {
return nil, err
}
disposables.Add(tp)
tp.SetTitle("Tunnels")
tp.SetLayout(walk.NewHBoxLayout())
tp.listContainer, _ = walk.NewComposite(tp)
vlayout := walk.NewVBoxLayout()
vlayout.SetMargins(walk.Margins{})
vlayout.SetSpacing(0)
tp.listContainer.SetLayout(vlayout)
//TODO: deal with remaining disposables in case the next line fails
if tp.listView, err = NewListView(tp.listContainer); err != nil {
return nil, err
}
tp.currentTunnelContainer, _ = walk.NewComposite(tp)
vlayout = walk.NewVBoxLayout()
vlayout.SetMargins(walk.Margins{})
tp.currentTunnelContainer.SetLayout(vlayout)
tp.fillerContainer, _ = walk.NewComposite(tp)
tp.fillerContainer.SetVisible(false)
hlayout := walk.NewHBoxLayout()
hlayout.SetMargins(walk.Margins{})
tp.fillerContainer.SetLayout(hlayout)
tp.fillerButton, _ = walk.NewPushButton(tp.fillerContainer)
buttonWidth := tp.DPI() * 2 //TODO: Use dynamic DPI
tp.fillerButton.SetMinMaxSize(walk.Size{buttonWidth, 0}, walk.Size{buttonWidth, 0})
tp.fillerButton.Clicked().Attach(func() {
if tp.fillerHandler != nil {
tp.fillerHandler()
}
})
tp.confView, _ = NewConfView(tp.currentTunnelContainer)
controlsContainer, _ := walk.NewComposite(tp.currentTunnelContainer)
controlsContainer.SetLayout(walk.NewHBoxLayout())
controlsContainer.Layout().SetMargins(walk.Margins{})
walk.NewHSpacer(controlsContainer)
editTunnel, _ := walk.NewPushButton(controlsContainer)
editTunnel.SetEnabled(false)
tp.listView.CurrentIndexChanged().Attach(func() {
editTunnel.SetEnabled(tp.listView.CurrentIndex() > -1)
})
editTunnel.SetText("Edit")
editTunnel.Clicked().Attach(tp.onEditTunnel)
disposables.Spare()
//TODO: expose walk.TableView.itemCountChangedPublisher.Event()
tp.listView.Property("ItemCount").Changed().Attach(tp.onTunnelsChanged)
tp.listView.SelectedIndexesChanged().Attach(tp.onSelectedTunnelsChanged)
tp.listView.ItemActivated().Attach(tp.onTunnelsViewItemActivated)
tp.listView.CurrentIndexChanged().Attach(tp.updateConfView)
tp.listView.Load(false)
tp.onTunnelsChanged()
return tp, nil
}
func (tp *TunnelsPage) CreateToolbar() {
if tp.listToolbar != nil {
return
}
// HACK: Because of https://github.com/lxn/walk/issues/481
// we need to put the ToolBar into its own Composite.
toolBarContainer, _ := walk.NewComposite(tp.listContainer)
hlayout := walk.NewHBoxLayout()
hlayout.SetMargins(walk.Margins{})
toolBarContainer.SetLayout(hlayout)
tp.listToolbar, _ = walk.NewToolBarWithOrientationAndButtonStyle(toolBarContainer, walk.Horizontal, walk.ToolBarButtonImageBeforeText)
imageSize := walk.Size{tp.DPI() / 6, tp.DPI() / 6} // Dividing by six is the same as dividing by 96 and multiplying by 16. TODO: Use dynamic DPI
imageList, _ := walk.NewImageList(imageSize, walk.RGB(0, 0, 0))
tp.listToolbar.SetImageList(imageList)
addMenu, _ := walk.NewMenu()
tp.AddDisposable(addMenu)
importAction := walk.NewAction()
importAction.SetText("Import tunnel(s) from file...")
importActionIcon, _ := loadSystemIcon("imageres", 3)
importActionImage, _ := walk.NewBitmapFromIcon(importActionIcon, imageSize)
importAction.SetImage(importActionImage)
importAction.SetShortcut(walk.Shortcut{walk.ModControl, walk.KeyO})
importAction.Triggered().Attach(tp.onImport)
addAction := walk.NewAction()
addAction.SetText("Add empty tunnel")
addActionIcon, _ := loadSystemIcon("imageres", 2)
addActionImage, _ := walk.NewBitmapFromIcon(addActionIcon, imageSize)
addAction.SetImage(addActionImage)
addAction.SetShortcut(walk.Shortcut{walk.ModControl, walk.KeyN})
addAction.Triggered().Attach(tp.onAddTunnel)
addMenu.Actions().Add(importAction)
addMenu.Actions().Add(addAction)
addMenuAction := walk.NewMenuAction(addMenu)
addMenuActionIcon, _ := loadSystemIcon("shell32", 149)
addMenuActionImage, _ := walk.NewBitmapFromIcon(addMenuActionIcon, imageSize)
addMenuAction.SetImage(addMenuActionImage)
addMenuAction.SetText("Add Tunnel")
addMenuAction.SetToolTip(importAction.Text())
addMenuAction.Triggered().Attach(tp.onImport)
tp.listToolbar.Actions().Add(addMenuAction)
tp.listToolbar.Actions().Add(walk.NewSeparatorAction())
deleteAction := walk.NewAction()
deleteActionIcon, _ := loadSystemIcon("shell32", 131)
deleteActionImage, _ := walk.NewBitmapFromIcon(deleteActionIcon, imageSize)
deleteAction.SetImage(deleteActionImage)
deleteAction.SetShortcut(walk.Shortcut{0, walk.KeyDelete})
deleteAction.SetToolTip("Remove selected tunnel(s)")
deleteAction.Triggered().Attach(tp.onDelete)
tp.listToolbar.Actions().Add(deleteAction)
tp.listToolbar.Actions().Add(walk.NewSeparatorAction())
exportAction := walk.NewAction()
exportActionIcon, _ := loadSystemIcon("imageres", 165) // Or "shell32", 45?
exportActionImage, _ := walk.NewBitmapFromIcon(exportActionIcon, imageSize)
exportAction.SetImage(exportActionImage)
exportAction.SetToolTip("Export all tunnels to zip...")
exportAction.Triggered().Attach(tp.onExportTunnels)
tp.listToolbar.Actions().Add(exportAction)
var size win.SIZE
tp.listToolbar.SendMessage(win.TB_GETIDEALSIZE, win.FALSE, uintptr(unsafe.Pointer(&size)))
tp.listContainer.SetMinMaxSize(walk.Size{int(size.CX), 0}, walk.Size{int(size.CX), 0})
}
func (tp *TunnelsPage) updateConfView() {
tp.confView.SetTunnel(tp.listView.CurrentTunnel())
}
func (tp *TunnelsPage) importFiles(paths []string) {
go func() {
syncedMsgBox := func(title string, message string, flags walk.MsgBoxStyle) {
tp.Synchronize(func() {
walk.MsgBox(tp.Form(), title, message, flags)
})
}
type unparsedConfig struct {
Name string
Config string
}
var (
unparsedConfigs []unparsedConfig
lastErr error
)
for _, path := range paths {
switch strings.ToLower(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), filepath.Ext(path)), 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 strings.ToLower(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), filepath.Ext(f.Name)), Config: string(textConfig)})
}
r.Close()
}
}
if lastErr != nil || unparsedConfigs == nil {
syncedMsgBox("Error", fmt.Sprintf("Could not import selected configuration: %v", lastErr), walk.MsgBoxIconWarning)
return
}
// Add in reverse order so that the first one is selected.
sort.Slice(unparsedConfigs, func(i, j int) bool {
//TODO: use proper tunnel string sorting/comparison algorithm, as the other comments indicate too.
return strings.Compare(unparsedConfigs[i].Name, unparsedConfigs[j].Name) > 0
})
existingTunnelList, err := service.IPCClientTunnels()
if err != nil {
syncedMsgBox("Error", fmt.Sprintf("Could not enumerate existing tunnels: %v", lastErr), walk.MsgBoxIconWarning)
return
}
existingLowerTunnels := make(map[string]bool, len(existingTunnelList))
for _, tunnel := range existingTunnelList {
existingLowerTunnels[strings.ToLower(tunnel.Name)] = true
}
configCount := 0
for _, unparsedConfig := range unparsedConfigs {
if existingLowerTunnels[strings.ToLower(unparsedConfig.Name)] {
lastErr = fmt.Errorf("Another tunnel already exists with the name ‘%s’", unparsedConfig.Name)
continue
}
config, err := conf.FromWgQuick(unparsedConfig.Config, unparsedConfig.Name)
if err != nil {
lastErr = err
continue
}
_, err = service.IPCClientNewTunnel(config)
if err != nil {
lastErr = err
continue
}
configCount++
}
tp.listView.Load(true)
m, n := configCount, len(unparsedConfigs)
switch {
case n == 1 && m != n:
syncedMsgBox("Error", fmt.Sprintf("Unable to import configuration: %v", lastErr), walk.MsgBoxIconWarning)
case n == 1 && m == n:
// nothing
case m == n:
syncedMsgBox("Imported tunnels", fmt.Sprintf("Imported %d tunnels", m), walk.MsgBoxIconInformation)
case m != n:
syncedMsgBox("Imported tunnels", fmt.Sprintf("Imported %d of %d tunnels", m, n), walk.MsgBoxIconWarning)
}
}()
}
func (tp *TunnelsPage) exportTunnels(filePath string) {
writeFileWithOverwriteHandling(tp.Form(), filePath, func(file *os.File) error {
writer := zip.NewWriter(file)
for _, tunnel := range tp.listView.model.tunnels {
cfg, err := tunnel.StoredConfig()
if err != nil {
return fmt.Errorf("onExportTunnels: tunnel.StoredConfig failed: %v", err)
}
w, err := writer.Create(tunnel.Name + ".conf")
if err != nil {
return fmt.Errorf("onExportTunnels: writer.Create failed: %v", err)
}
if _, err := w.Write(([]byte)(cfg.ToWgQuick())); err != nil {
return fmt.Errorf("onExportTunnels: cfg.ToWgQuick failed: %v", err)
}
}
return writer.Close()
})
}
func (tp *TunnelsPage) addTunnel(config *conf.Config) {
_, err := service.IPCClientNewTunnel(config)
if err != nil {
walk.MsgBox(tp.Form(), "Unable to create tunnel", err.Error(), walk.MsgBoxIconError)
}
}
func (tp *TunnelsPage) deleteTunnel(tunnel *service.Tunnel) {
err := tunnel.Delete()
if err != nil {
walk.MsgBox(tp.Form(), "Unable to delete tunnel", err.Error(), walk.MsgBoxIconError)
}
}
// Handlers
func (tp *TunnelsPage) onTunnelsViewItemActivated() {
go func() {
globalState, err := service.IPCClientGlobalState()
if err != nil || (globalState != service.TunnelStarted && globalState != service.TunnelStopped) {
return
}
oldState, err := tp.listView.CurrentTunnel().Toggle()
if err != nil {
tp.Synchronize(func() {
if oldState == service.TunnelUnknown {
walk.MsgBox(tp.Form(), "Failed to determine tunnel state", err.Error(), walk.MsgBoxIconError)
} else if oldState == service.TunnelStopped {
walk.MsgBox(tp.Form(), "Failed to activate tunnel", err.Error(), walk.MsgBoxIconError)
} else if oldState == service.TunnelStarted {
walk.MsgBox(tp.Form(), "Failed to deactivate tunnel", err.Error(), walk.MsgBoxIconError)
}
})
return
}
}()
}
func (tp *TunnelsPage) onEditTunnel() {
tunnel := tp.listView.CurrentTunnel()
if tunnel == nil {
// Misfired event?
return
}
if config := runTunnelEditDialog(tp.Form(), tunnel); config != nil {
go func() {
priorState, err := tunnel.State()
tunnel.Delete()
tunnel.WaitForStop()
tunnel, err2 := service.IPCClientNewTunnel(config)
if err == nil && err2 == nil && (priorState == service.TunnelStarting || priorState == service.TunnelStarted) {
tunnel.Start()
}
}()
}
}
func (tp *TunnelsPage) onAddTunnel() {
if config := runTunnelEditDialog(tp.Form(), nil); config != nil {
// Save new
tp.addTunnel(config)
}
}
func (tp *TunnelsPage) onDelete() {
indices := tp.listView.SelectedIndexes()
if len(indices) == 0 {
return
}
var topic string
if len(indices) > 1 {
topic = fmt.Sprintf("%d tunnels", len(indices))
} else {
topic = fmt.Sprintf("‘%s’", tp.listView.model.tunnels[0].Name)
}
if walk.DlgCmdNo == walk.MsgBox(
tp.Form(),
fmt.Sprintf("Delete %s", topic),
fmt.Sprintf("Are you sure you would like to delete %s? You cannot undo this action.", topic),
walk.MsgBoxYesNo|walk.MsgBoxIconWarning) {
return
}
selectTunnelAfter := ""
if len(indices) < len(tp.listView.model.tunnels) {
sort.Ints(indices)
max := 0
for i, idx := range indices {
if idx+1 < len(tp.listView.model.tunnels) && (i+1 == len(indices) || idx+1 != indices[i+1]) {
max = idx + 1
} else if idx-1 >= 0 && (i == 0 || idx-1 != indices[i-1]) {
max = idx - 1
}
}
selectTunnelAfter = tp.listView.model.tunnels[max].Name
}
for _, i := range indices {
tp.deleteTunnel(&tp.listView.model.tunnels[i])
}
if len(selectTunnelAfter) > 0 {
tp.listView.selectTunnel(selectTunnelAfter)
}
}
func (tp *TunnelsPage) onImport() {
tp.Form().Show() // Since the tray calls us sometimes, always make our parent visible.
dlg := walk.FileDialog{
Filter: "Configuration Files (*.zip, *.conf)|*.zip;*.conf|All Files (*.*)|*.*",
Title: "Import tunnel(s) from file...",
}
if ok, _ := dlg.ShowOpenMultiple(tp.Form()); !ok {
return
}
tp.importFiles(dlg.FilePaths)
}
func (tp *TunnelsPage) onExportTunnels() {
dlg := walk.FileDialog{
Filter: "Configuration ZIP Files (*.zip)|*.zip",
Title: "Export tunnels to zip...",
}
if ok, _ := dlg.ShowSave(tp.Form()); !ok {
return
}
if !strings.HasSuffix(dlg.FilePath, ".zip") {
dlg.FilePath += ".zip"
}
tp.exportTunnels(dlg.FilePath)
}
func (tp *TunnelsPage) swapFiller(enabled bool) bool {
//BUG: flicker switching with the currentTunnelContainer
if tp.fillerContainer.Visible() == enabled {
return enabled
}
tp.SetSuspended(true)
tp.fillerContainer.SetVisible(enabled)
tp.currentTunnelContainer.SetVisible(!enabled)
tp.SetSuspended(false)
return enabled
}
func (tp *TunnelsPage) onTunnelsChanged() {
if tp.swapFiller(tp.listView.model.RowCount() == 0) {
tp.fillerButton.SetText("Import tunnel(s) from file")
tp.fillerHandler = tp.onImport
}
}
func (tp *TunnelsPage) onSelectedTunnelsChanged() {
indices := tp.listView.SelectedIndexes()
if tp.swapFiller(len(indices) > 1) {
tp.fillerButton.SetText(fmt.Sprintf("Delete %d tunnels", len(indices)))
tp.fillerHandler = tp.onDelete
}
}
|