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
|
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
*/
package conf
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc/mgr"
)
func maybeMigrateConfiguration(c string) {
if disableAutoMigration {
return
}
oldRoot, err := windows.KnownFolderPath(windows.FOLDERID_LocalAppData, windows.KF_FLAG_DEFAULT)
if err != nil {
return
}
oldC := filepath.Join(oldRoot, "WireGuard", "Configurations")
files, err := ioutil.ReadDir(oldC)
if err != nil {
return
}
migratedConfigs := make(map[string]string)
for i := range files {
if files[i].IsDir() {
continue
}
fileName := files[i].Name()
newPath := filepath.Join(c, fileName)
newFile, err := os.OpenFile(newPath, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
continue
}
oldPath := filepath.Join(oldC, fileName)
oldConfig, err := ioutil.ReadFile(oldPath)
if err != nil {
newFile.Close()
os.Remove(newPath)
continue
}
_, err = newFile.Write(oldConfig)
if err != nil {
newFile.Close()
os.Remove(newPath)
continue
}
newFile.Close()
os.Remove(oldPath)
migratedConfigs[strings.ToLower(oldPath)] = newPath
log.Printf("Migrated configuration from ‘%s’ to ‘%s’", oldPath, newPath)
}
if os.Remove(oldC) == nil {
oldLog := filepath.Join(oldRoot, "WireGuard", "log.bin")
oldRoot := filepath.Join(oldRoot, "WireGuard")
os.Remove(oldLog)
os.Remove(oldRoot)
}
if len(migratedConfigs) == 0 {
return
}
m, err := mgr.Connect()
if err != nil {
return
}
defer m.Disconnect()
services, err := m.ListServices()
if err != nil {
return
}
matcher, err := regexp.Compile(" /tunnelservice \"?([^\"]+)\"?$")
if err != nil {
return
}
for _, svcName := range services {
if !strings.HasPrefix(svcName, "WireGuardTunnel$") {
continue
}
svc, err := m.OpenService(svcName)
if err != nil {
continue
}
config, err := svc.Config()
if err != nil {
continue
}
matches := matcher.FindStringSubmatchIndex(config.BinaryPathName)
if len(matches) != 4 {
svc.Close()
continue
}
newName, found := migratedConfigs[strings.ToLower(config.BinaryPathName[matches[2]:])]
if !found {
svc.Close()
continue
}
config.BinaryPathName = config.BinaryPathName[:matches[0]] + fmt.Sprintf(" /tunnelservice \"%s\"", newName)
err = svc.UpdateConfig(config)
svc.Close()
if err != nil {
continue
}
log.Printf("Migrated service command line arguments for ‘%s’", svcName)
}
}
|