-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
NetworkAddressChange.Unix.cs
344 lines (309 loc) · 12.9 KB
/
NetworkAddressChange.Unix.cs
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
// Linux implementation of NetworkChange
public partial class NetworkChange
{
private static Socket? s_socket;
private static Socket? Socket
{
get
{
Debug.Assert(Monitor.IsEntered(s_gate));
return s_socket;
}
set
{
Debug.Assert(Monitor.IsEntered(s_gate));
s_socket = value;
}
}
// Lock controlling access to delegate subscriptions, socket, availability-changed state and timer.
private static readonly object s_gate = new object();
// The "leniency" window for NetworkAvailabilityChanged socket events.
// All socket events received within this duration will be coalesced into a
// single event. Generally, many route changed events are fired in succession,
// and we are not interested in all of them, just the fact that network availability
// has potentially changed as a result.
private const int AvailabilityTimerWindowMilliseconds = 150;
private static readonly TimerCallback s_availabilityTimerFiredCallback = OnAvailabilityTimerFired;
private static Timer? s_availabilityTimer;
private static bool s_availabilityHasChanged;
[UnsupportedOSPlatform("illumos")]
[UnsupportedOSPlatform("solaris")]
public static event NetworkAddressChangedEventHandler? NetworkAddressChanged
{
add
{
if (value != null)
{
lock (s_gate)
{
if (Socket == null)
{
CreateSocket();
}
s_addressChangedSubscribers.TryAdd(value, ExecutionContext.Capture());
}
}
}
remove
{
if (value != null)
{
lock (s_gate)
{
if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0)
{
Debug.Assert(Socket == null,
"Socket is not null, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged.");
return;
}
s_addressChangedSubscribers.Remove(value);
if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0)
{
CloseSocket();
}
}
}
}
}
[UnsupportedOSPlatform("illumos")]
[UnsupportedOSPlatform("solaris")]
public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityChanged
{
add
{
if (value != null)
{
lock (s_gate)
{
if (Socket == null)
{
CreateSocket();
}
if (s_availabilityTimer == null)
{
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
bool restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
s_availabilityTimer = new Timer(s_availabilityTimerFiredCallback, null, Timeout.Infinite, Timeout.Infinite);
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
ExecutionContext.RestoreFlow();
}
}
s_availabilityChangedSubscribers.TryAdd(value, ExecutionContext.Capture());
}
}
}
remove
{
if (value != null)
{
lock (s_gate)
{
if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0)
{
Debug.Assert(Socket == null,
"Socket is not null, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged.");
return;
}
s_availabilityChangedSubscribers.Remove(value);
if (s_availabilityChangedSubscribers.Count == 0)
{
if (s_availabilityTimer != null)
{
s_availabilityTimer.Dispose();
s_availabilityTimer = null;
s_availabilityHasChanged = false;
}
if (s_addressChangedSubscribers.Count == 0)
{
CloseSocket();
}
}
}
}
}
}
private static unsafe void CreateSocket()
{
Debug.Assert(Monitor.IsEntered(s_gate));
Debug.Assert(Socket == null, "Socket is not null, must close existing socket before opening another.");
var sh = new SafeSocketHandle();
IntPtr newSocket;
Interop.Error result = Interop.Sys.CreateNetworkChangeListenerSocket(&newSocket);
if (result != Interop.Error.SUCCESS)
{
string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage();
sh.Dispose();
throw new NetworkInformationException(message);
}
Marshal.InitHandle(sh, newSocket);
Socket = new Socket(sh);
// Don't capture ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(
static socket => ReadEventsAsync(socket),
Socket, preferLocal: false);
}
private static void CloseSocket()
{
Debug.Assert(Monitor.IsEntered(s_gate));
Debug.Assert(Socket != null, "Socket was null when CloseSocket was called.");
Socket.Dispose();
Socket = null;
}
private static async void ReadEventsAsync(Socket socket)
{
try
{
while (true)
{
// Wait for data to become available.
await socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None).ConfigureAwait(false);
Interop.Error result = ReadEvents(socket);
if (result != Interop.Error.SUCCESS &&
result != Interop.Error.EAGAIN)
{
throw new Win32Exception(result.Info().RawErrno);
}
}
}
catch (ObjectDisposedException)
{ } // Socket disposed.
catch (SocketException se) when (se.SocketErrorCode == SocketError.OperationAborted)
{ } // ReceiveAsync aborted by disposing Socket.
catch (Exception ex)
{
// Unexpected error.
Debug.Fail($"Unexpected error: {ex}");
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(ex);
}
static unsafe Interop.Error ReadEvents(Socket socket)
=> Interop.Sys.ReadEvents(socket.SafeHandle, &ProcessEvent);
}
[UnmanagedCallersOnly]
private static void ProcessEvent(IntPtr socket, Interop.Sys.NetworkChangeKind kind)
{
if (kind != Interop.Sys.NetworkChangeKind.None)
{
lock (s_gate)
{
// It's safe to compare raw handle values because ProcessEvents gets
// called from ReadEvents which holds a reference on the SafeHandle.
if (Socket != null && socket == Socket.Handle)
{
OnSocketEvent(kind);
}
}
}
}
private static void OnSocketEvent(Interop.Sys.NetworkChangeKind kind)
{
switch (kind)
{
case Interop.Sys.NetworkChangeKind.AddressAdded:
case Interop.Sys.NetworkChangeKind.AddressRemoved:
OnAddressChanged();
break;
case Interop.Sys.NetworkChangeKind.AvailabilityChanged:
lock (s_gate)
{
if (s_availabilityTimer != null)
{
if (!s_availabilityHasChanged)
{
s_availabilityTimer.Change(AvailabilityTimerWindowMilliseconds, -1);
}
s_availabilityHasChanged = true;
}
}
break;
}
}
private static void OnAddressChanged()
{
Dictionary<NetworkAddressChangedEventHandler, ExecutionContext?>? addressChangedSubscribers = null;
lock (s_gate)
{
if (s_addressChangedSubscribers.Count > 0)
{
addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext?>(s_addressChangedSubscribers);
}
}
if (addressChangedSubscribers != null)
{
foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext?>
subscriber in addressChangedSubscribers)
{
NetworkAddressChangedEventHandler handler = subscriber.Key;
ExecutionContext? ec = subscriber.Value;
if (ec == null) // Flow suppressed
{
handler(null, EventArgs.Empty);
}
else
{
ExecutionContext.Run(ec, s_runAddressChangedHandler, handler);
}
}
}
}
private static void OnAvailabilityTimerFired(object? state)
{
Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext?>? availabilityChangedSubscribers = null;
lock (s_gate)
{
if (s_availabilityHasChanged)
{
s_availabilityHasChanged = false;
if (s_availabilityChangedSubscribers.Count > 0)
{
availabilityChangedSubscribers =
new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext?>(
s_availabilityChangedSubscribers);
}
}
}
if (availabilityChangedSubscribers != null)
{
bool isAvailable = NetworkInterface.GetIsNetworkAvailable();
NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs;
ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable;
foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext?>
subscriber in availabilityChangedSubscribers)
{
NetworkAvailabilityChangedEventHandler handler = subscriber.Key;
ExecutionContext? ec = subscriber.Value;
if (ec == null) // Flow suppressed
{
handler(null, args);
}
else
{
ExecutionContext.Run(ec, callbackContext, handler);
}
}
}
}
}
}