-
Notifications
You must be signed in to change notification settings - Fork 410
/
Copy pathstorewatcher_windows.go
93 lines (80 loc) · 2.27 KB
/
storewatcher_windows.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
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
*/
package conf
import (
"log"
"golang.org/x/sys/windows"
)
type StoreCallback struct {
cb func()
}
var storeCallbacks = make(map[*StoreCallback]bool)
func RegisterStoreChangeCallback(cb func()) *StoreCallback {
startWatchingConfigDir()
cb()
s := &StoreCallback{cb}
storeCallbacks[s] = true
return s
}
func (cb *StoreCallback) Unregister() {
delete(storeCallbacks, cb)
}
const (
fncFILE_NAME uint32 = 0x00000001
fncDIR_NAME uint32 = 0x00000002
fncATTRIBUTES uint32 = 0x00000004
fncSIZE uint32 = 0x00000008
fncLAST_WRITE uint32 = 0x00000010
fncLAST_ACCESS uint32 = 0x00000020
fncCREATION uint32 = 0x00000040
fncSECURITY uint32 = 0x00000100
)
//sys findFirstChangeNotification(path *uint16, watchSubtree bool, filter uint32) (handle windows.Handle, err error) [failretval==windows.InvalidHandle] = kernel32.FindFirstChangeNotificationW
//sys findNextChangeNotification(handle windows.Handle) (err error) = kernel32.FindNextChangeNotification
var haveStartedWatchingConfigDir bool
func startWatchingConfigDir() {
if haveStartedWatchingConfigDir {
return
}
haveStartedWatchingConfigDir = true
go func() {
h := windows.InvalidHandle
defer func() {
if h != windows.InvalidHandle {
windows.CloseHandle(h)
}
haveStartedWatchingConfigDir = false
}()
startover:
configFileDir, err := tunnelConfigurationsDirectory()
if err != nil {
return
}
h, err = findFirstChangeNotification(windows.StringToUTF16Ptr(configFileDir), true, fncFILE_NAME|fncDIR_NAME|fncATTRIBUTES|fncSIZE|fncLAST_WRITE|fncLAST_ACCESS|fncCREATION|fncSECURITY)
if err != nil {
log.Printf("Unable to monitor config directory: %v", err)
return
}
for {
s, err := windows.WaitForSingleObject(h, windows.INFINITE)
if err != nil || s == windows.WAIT_FAILED {
log.Printf("Unable to wait on config directory watcher: %v", err)
windows.CloseHandle(h)
h = windows.InvalidHandle
goto startover
}
for cb := range storeCallbacks {
cb.cb()
}
err = findNextChangeNotification(h)
if err != nil {
log.Printf("Unable to monitor config directory again: %v", err)
windows.CloseHandle(h)
h = windows.InvalidHandle
goto startover
}
}
}()
}