This repository has been archived by the owner on Oct 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
route_change_handler.go
67 lines (60 loc) · 1.73 KB
/
route_change_handler.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
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
*/
package winipcfg
import (
"golang.org/x/sys/windows"
"os"
"sync"
"unsafe"
)
type RouteChangeCallback struct {
cb func(notificationType MibNotificationType, route *Route)
}
var (
routeChangeMutex = sync.Mutex{}
routeChangeCallbacks = make(map[*RouteChangeCallback]bool)
routeChangeHandle = uintptr(0)
)
func RegisterRouteChangeCallback(cb func(notificationType MibNotificationType, route *Route)) (*RouteChangeCallback, error) {
routeChangeMutex.Lock()
defer routeChangeMutex.Unlock()
s := &RouteChangeCallback{cb}
routeChangeCallbacks[s] = true
if routeChangeHandle == 0 {
result := notifyRouteChange2(AF_UNSPEC, windows.NewCallback(routeChanged), 0, false,
unsafe.Pointer(&routeChangeHandle))
if result != 0 {
delete(routeChangeCallbacks, s)
routeChangeHandle = 0
return nil, os.NewSyscallError("iphlpapi.NotifyRouteChange2", windows.Errno(result))
}
}
return s, nil
}
func (cb *RouteChangeCallback) Unregister() error {
routeChangeMutex.Lock()
defer routeChangeMutex.Unlock()
delete(routeChangeCallbacks, cb)
if len(routeChangeCallbacks) == 0 && routeChangeHandle != 0 {
result := cancelMibChangeNotify2(routeChangeHandle)
if result != 0 {
return os.NewSyscallError("iphlpapi.CancelMibChangeNotify2", windows.Errno(result))
}
routeChangeHandle = uintptr(0)
}
return nil
}
func routeChanged(callerContext unsafe.Pointer, wtr *wtMibIpforwardRow2, notificationType MibNotificationType) uintptr {
route, err := wtr.toRoute()
if route == nil || err != nil {
return 0
}
routeChangeMutex.Lock()
for cb := range routeChangeCallbacks {
cb.cb(notificationType, route)
}
routeChangeMutex.Unlock()
return 0
}