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

package winipcfg

import (
	"sync"

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

// RouteChangeCallback structure allows route change callback handling.
type RouteChangeCallback struct {
	cb func(notificationType MibNotificationType, route *MibIPforwardRow2)
}

var (
	routeChangeAddRemoveMutex = sync.Mutex{}
	routeChangeMutex          = sync.Mutex{}
	routeChangeCallbacks      = make(map[*RouteChangeCallback]bool)
	routeChangeHandle         = windows.Handle(0)
)

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

	routeChangeAddRemoveMutex.Lock()
	defer routeChangeAddRemoveMutex.Unlock()

	routeChangeMutex.Lock()
	defer routeChangeMutex.Unlock()

	routeChangeCallbacks[s] = true

	if routeChangeHandle == 0 {
		err := notifyRouteChange2(windows.AF_UNSPEC, windows.NewCallback(routeChanged), 0, false, &routeChangeHandle)
		if err != nil {
			delete(routeChangeCallbacks, s)
			routeChangeHandle = 0
			return nil, err
		}
	}

	return s, nil
}

// Unregister unregisters the callback.
func (callback *RouteChangeCallback) Unregister() error {
	routeChangeAddRemoveMutex.Lock()
	defer routeChangeAddRemoveMutex.Unlock()

	routeChangeMutex.Lock()
	delete(routeChangeCallbacks, callback)
	removeIt := len(routeChangeCallbacks) == 0 && routeChangeHandle != 0
	routeChangeMutex.Unlock()

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

	return nil
}

func routeChanged(callerContext uintptr, row *MibIPforwardRow2, notificationType MibNotificationType) uintptr {
	routeChangeMutex.Lock()
	for cb := range routeChangeCallbacks {
		cb.cb(notificationType, row)
	}
	routeChangeMutex.Unlock()
	return 0
}