aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/conf/storewatcher_windows.go
blob: 0c4b74e7489572572b5a9581a99e6d56d75489d9 (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
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
 */

package conf

import (
	"log"

	"golang.org/x/sys/windows"
)

var haveStartedWatchingConfigDir bool

func startWatchingConfigDir() {
	if haveStartedWatchingConfigDir {
		return
	}
	haveStartedWatchingConfigDir = true
	go func() {
		h := windows.InvalidHandle
		defer func() {
			if h != windows.InvalidHandle {
				windows.FindCloseChangeNotification(h)
			}
			haveStartedWatchingConfigDir = false
		}()
	startover:
		configFileDir, err := tunnelConfigurationsDirectory()
		if err != nil {
			return
		}
		h, err = windows.FindFirstChangeNotification(configFileDir, true, windows.FILE_NOTIFY_CHANGE_FILE_NAME|windows.FILE_NOTIFY_CHANGE_DIR_NAME|windows.FILE_NOTIFY_CHANGE_ATTRIBUTES|windows.FILE_NOTIFY_CHANGE_SIZE|windows.FILE_NOTIFY_CHANGE_LAST_WRITE|windows.FILE_NOTIFY_CHANGE_LAST_ACCESS|windows.FILE_NOTIFY_CHANGE_CREATION|windows.FILE_NOTIFY_CHANGE_SECURITY)
		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.FindCloseChangeNotification(h)
				h = windows.InvalidHandle
				goto startover
			}

			for cb := range storeCallbacks {
				cb.cb()
			}

			err = windows.FindNextChangeNotification(h)
			if err != nil {
				log.Printf("Unable to monitor config directory again: %v", err)
				windows.FindCloseChangeNotification(h)
				h = windows.InvalidHandle
				goto startover
			}
		}
	}()
}