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

package winipcfg

import (
	"sync"

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

// InterfaceChangeCallback structure allows interface change callback handling.
type InterfaceChangeCallback struct {
	cb   func(notificationType MibNotificationType, iface *MibIPInterfaceRow)
	wait sync.WaitGroup
}

var (
	interfaceChangeAddRemoveMutex = sync.Mutex{}
	interfaceChangeMutex          = sync.Mutex{}
	interfaceChangeCallbacks      = make(map[*InterfaceChangeCallback]bool)
	interfaceChangeHandle         = windows.Handle(0)
)

// RegisterInterfaceChangeCallback registers a new InterfaceChangeCallback. If this particular callback is already
// registered, the function will silently return. Returned InterfaceChangeCallback.Unregister method should be used
// to unregister.
func RegisterInterfaceChangeCallback(callback func(notificationType MibNotificationType, iface *MibIPInterfaceRow)) (*InterfaceChangeCallback, error) {
	s := &InterfaceChangeCallback{cb: callback}

	interfaceChangeAddRemoveMutex.Lock()
	defer interfaceChangeAddRemoveMutex.Unlock()

	interfaceChangeMutex.Lock()
	defer interfaceChangeMutex.Unlock()

	interfaceChangeCallbacks[s] = true

	if interfaceChangeHandle == 0 {
		err := notifyIPInterfaceChange(windows.AF_UNSPEC, windows.NewCallback(interfaceChanged), 0, false, &interfaceChangeHandle)
		if err != nil {
			delete(interfaceChangeCallbacks, s)
			interfaceChangeHandle = 0
			return nil, err
		}
	}

	return s, nil
}

// Unregister unregisters the callback.
func (callback *InterfaceChangeCallback) Unregister() error {
	interfaceChangeAddRemoveMutex.Lock()
	defer interfaceChangeAddRemoveMutex.Unlock()

	interfaceChangeMutex.Lock()
	delete(interfaceChangeCallbacks, callback)
	removeIt := len(interfaceChangeCallbacks) == 0 && interfaceChangeHandle != 0
	interfaceChangeMutex.Unlock()

	callback.wait.Wait()

	if removeIt {
		err := cancelMibChangeNotify2(interfaceChangeHandle)
		if err != nil {
			return err
		}
		interfaceChangeHandle = 0
	}

	return nil
}

func interfaceChanged(callerContext uintptr, row *MibIPInterfaceRow, notificationType MibNotificationType) uintptr {
	rowCopy := *row
	interfaceChangeMutex.Lock()
	for cb := range interfaceChangeCallbacks {
		cb.wait.Add(1)
		go func(cb *InterfaceChangeCallback) {
			cb.cb(notificationType, &rowCopy)
			cb.wait.Done()
		}(cb)
	}
	interfaceChangeMutex.Unlock()
	return 0
}