aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tunnel/winipcfg/interface_change_handler.go
blob: 6bb8cf2b0cb09bf13f8c9b267702dc876f1432b9 (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
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 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)
}

var (
	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) {
	cb := &InterfaceChangeCallback{callback}

	interfaceChangeMutex.Lock()
	defer interfaceChangeMutex.Unlock()

	interfaceChangeCallbacks[cb] = true

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

	return cb, nil
}

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

	delete(interfaceChangeCallbacks, callback)

	if len(interfaceChangeCallbacks) < 1 && interfaceChangeHandle != 0 {
		err := cancelMibChangeNotify2(interfaceChangeHandle)
		if err != nil {
			return err
		}
		interfaceChangeHandle = 0
	}

	return nil
}

func interfaceChanged(callerContext uintptr, row *MibIPInterfaceRow, notificationType MibNotificationType) uintptr {
	interfaceChangeMutex.Lock()
	for cb := range interfaceChangeCallbacks {
		cb.cb(notificationType, row)
	}
	interfaceChangeMutex.Unlock()
	return 0
}