Repository navigation
Expand file tree
/
Copy pathWindowsRadio.WifiWatch.cs
More file actions
276 lines (247 loc) · 10.6 KB
/
Copy pathWindowsRadio.WifiWatch.cs
File metadata and controls
276 lines (247 loc) · 10.6 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using static WindowsDeviceControl.Win32Error;
namespace WindowsDeviceControl;
public static unsafe partial class WindowsRadio
{
private const uint WlanNotificationSourceNone = 0;
private const uint WlanNotificationSourceAcm = 0x00000008;
private const uint AcmScanComplete = 7;
private const uint AcmConnectionComplete = 10;
private const uint AcmConnectionAttemptFail = 11;
private const uint AcmDisconnected = 21;
private const uint AcmScanListRefresh = 26;
/// <summary>Starts reporting Wi-Fi scan and connection changes.</summary>
/// <param name="onEvent">
/// Called on a WLAN service thread, never the caller's, and one call at a time for this
/// registration. Post to your own thread before touching UI state, and keep the callback
/// short: it runs inside the WLAN notification path. Exceptions it throws are swallowed,
/// because a native callback cannot propagate them.
/// </param>
/// <returns>
/// The registration. Disposing it is the stop: it unregisters, waits for a callback that is
/// already running to return, then closes the WLAN handle. Disposing it again does nothing.
/// </returns>
/// <exception cref="Win32Exception">
/// The WLAN handle could not be opened, or Windows refused to
/// register for notifications.
/// </exception>
/// <remarks>
/// Every call creates an independent registration on a WLAN handle of its own, so several
/// can run side by side and disposing one leaves the others reporting. Never dispose a
/// registration from inside its own callback: Windows waits for the running callback before
/// the unregister returns, so that call never completes. Post the disposal to another thread
/// instead. Dispose every registration before the process exits, because native code holds
/// the callback until then. A registration ends silently when the WLAN service restarts;
/// start a new one when you want the feed back.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="onEvent" /> is null.</exception>
public static IDisposable StartWifiWatch(Action<WifiWatchEvent> onEvent)
{
ArgumentNullException.ThrowIfNull(onEvent);
var watch = new WifiWatch(onEvent);
watch.Registration = WlanNotificationRegistration.Start(watch.OnNotification);
return watch;
}
/// <summary>
/// Whether an ACM completion names the profile being joined. A completion without a profile
/// name could be any connection on the adapter, an unrelated auto-connect included, so it
/// decides nothing; the wait then ends at its timeout and the connected network is checked.
/// </summary>
/// <param name="profile">Profile name from the native connection event.</param>
/// <param name="expected">Profile name used by this connection attempt.</param>
/// <returns>True only for a nonempty, ordinally equal profile name.</returns>
internal static bool IsCompletionForProfile(string profile, string expected)
{
return profile.Length > 0 && string.Equals(profile, expected, StringComparison.Ordinal);
}
/// <summary>The change an ACM notification code reports, or null for one that changes nothing.</summary>
private static WifiWatchEvent? MapWatchEvent(uint code)
{
return code switch
{
AcmScanComplete or AcmScanListRefresh => WifiWatchEvent.ScanCompleted,
AcmConnectionComplete or AcmConnectionAttemptFail or AcmDisconnected =>
WifiWatchEvent.ConnectionChanged,
_ => null
};
}
/// <summary>One <see cref="StartWifiWatch" /> registration and its delivery gate.</summary>
private sealed class WifiWatch(Action<WifiWatchEvent> events) : IDisposable
{
private readonly object _gate = new();
private int _disposed;
internal WlanNotificationRegistration? Registration { get; set; }
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
// Unregistering waits for a callback that is already running, and that callback holds
// _gate, so the registration is released outside it.
Registration?.Dispose();
}
internal void OnNotification(WlanNotificationData notification)
{
if (Volatile.Read(ref _disposed) != 0 || MapWatchEvent(notification.Code) is not { } change)
{
return;
}
lock (_gate)
{
if (Volatile.Read(ref _disposed) == 0)
{
events(change);
}
}
}
}
private sealed class ConnectionVerdict : IDisposable
{
private readonly Guid _adapter;
private readonly string _profile;
private readonly ManualResetEventSlim _ready = new(false);
private ConnectionOutcome? _outcome;
private WlanNotificationRegistration? _registration;
private ConnectionVerdict(Guid adapter, string profile)
{
_adapter = adapter;
_profile = profile;
}
public void Dispose()
{
_registration?.Dispose();
_ready.Dispose();
}
/// <summary>Registers for the adapter's connection completions before the request is sent.</summary>
/// <exception cref="Win32Exception">The WLAN handle could not be opened or registered.</exception>
public static ConnectionVerdict Start(Guid adapter, string profile)
{
var verdict = new ConnectionVerdict(adapter, profile);
try
{
verdict._registration = WlanNotificationRegistration.Start(verdict.OnNotification);
}
catch
{
verdict.Dispose();
throw;
}
return verdict;
}
internal ConnectionOutcome? Wait(TimeSpan timeout)
{
return _ready.Wait(timeout) ? _outcome : null;
}
private void OnNotification(WlanNotificationData notification)
{
if (notification.InterfaceId != _adapter
|| notification.Code is not AcmConnectionComplete and not AcmConnectionAttemptFail)
{
return;
}
var reason = 0u;
var profile = string.Empty;
if (notification.Data != 0
&& notification.DataSize >= (uint)sizeof(WlanConnectionNotificationData))
{
var payload = (WlanConnectionNotificationData*)notification.Data;
reason = payload->ReasonCode;
profile = NativeText.ReadFixed(payload->ProfileName, 256);
}
if (!IsCompletionForProfile(profile, _profile))
{
return;
}
_outcome = new ConnectionOutcome(
notification.Code == AcmConnectionComplete && reason == 0,
reason);
_ready.Set();
}
}
/// <summary>An ACM notification handler registered on a WLAN client handle of its own.</summary>
/// <remarks>
/// Native code holds only the delegate's function pointer, so the registration keeps
/// the delegate alive until disposal has unregistered it and closed the handle. Disposal
/// happens once, however often it is called.
/// </remarks>
private sealed class WlanNotificationRegistration : IDisposable
{
private readonly WlanNotificationCallback _callback;
private readonly WlanClient _client;
private readonly Action<WlanNotificationData> _handler;
private int _disposed;
private WlanNotificationRegistration(WlanClient client, Action<WlanNotificationData> handler)
{
_client = client;
_handler = handler;
_callback = OnNative;
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
// Unregister before closing: the unregister waits for a running callback, so the
// delegate stays rooted and the handle open until no native call can reach either.
WlanRegisterNotification(_client.Handle, WlanNotificationSourceNone, 0, 0, 0, 0, 0);
_client.Dispose();
GC.KeepAlive(_callback);
}
/// <summary>Opens a client handle and registers the handler for ACM notifications on it.</summary>
/// <param name="handler">Receives each ACM notification on the WLAN service thread.</param>
/// <exception cref="Win32Exception">
/// <c>WlanOpenHandle</c> or <c>WlanRegisterNotification</c> failed; the native status is
/// <see cref="Win32Exception.NativeErrorCode" />.
/// </exception>
internal static WlanNotificationRegistration Start(Action<WlanNotificationData> handler)
{
var client = WlanClient.Open();
try
{
var registration = new WlanNotificationRegistration(client, handler);
var status = WlanRegisterNotification(
client.Handle,
WlanNotificationSourceAcm,
1,
Marshal.GetFunctionPointerForDelegate(registration._callback),
0,
0,
0);
Check(status, "WlanRegisterNotification");
return registration;
}
catch
{
// Only the handle is closed: nothing was registered, so there is nothing to unregister.
client.Dispose();
throw;
}
}
private void OnNative(nint data, nint context)
{
try
{
// WLAN occasionally delivers a null notification pointer.
if (data == 0)
{
return;
}
var notification = *(WlanNotificationData*)data;
if (notification.Source == WlanNotificationSourceAcm)
{
_handler(notification);
}
}
catch
{
// A native service callback cannot propagate managed failures.
}
}
}
private readonly record struct ConnectionOutcome(bool Succeeded, uint Reason);
}