-
Notifications
You must be signed in to change notification settings - Fork 78
/
MulticastService.cs
572 lines (519 loc) · 18.7 KB
/
MulticastService.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
using Common.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Makaretu.Dns
{
/// <summary>
/// Muticast Domain Name Service.
/// </summary>
/// <remarks>
/// Sends and receives DNS queries and answers via the multicast mechachism
/// defined in <see href="https://tools.ietf.org/html/rfc6762"/>.
/// <para>
/// Use <see cref="Start"/> to start listening for multicast messages.
/// One of the events, <see cref="QueryReceived"/> or <see cref="AnswerReceived"/>, is
/// raised when a <see cref="Message"/> is received.
/// </para>
/// </remarks>
public class MulticastService : IResolver, IDisposable
{
static readonly ILog log = LogManager.GetLogger(typeof(MulticastService));
static readonly IPAddress MulticastAddressIp4 = IPAddress.Parse("224.0.0.251");
static readonly IPAddress MulticastAddressIp6 = IPAddress.Parse("FF02::FB");
static readonly IPNetwork[] linkLocalNetworks = new IPNetwork[]
{
IPNetwork.Parse("169.254.0.0/16"),
IPNetwork.Parse("fe80::/10")
};
const int MulticastPort = 5353;
// IP header (20 bytes for IPv4; 40 bytes for IPv6) and the UDP header(8 bytes).
const int packetOverhead = 48;
const int maxDatagramSize = Message.MaxLength;
CancellationTokenSource serviceCancellation;
CancellationTokenSource listenerCancellation;
List<NetworkInterface> knownNics = new List<NetworkInterface>();
readonly bool ip6;
IPEndPoint mdnsEndpoint;
int maxPacketSize;
/// <summary>
/// Set the default TTLs.
/// </summary>
/// <seealso cref="ResourceRecord.DefaultTTL"/>
/// <seealso cref="ResourceRecord.DefaultHostTTL"/>
static MulticastService()
{
// https://tools.ietf.org/html/rfc6762 section 10
ResourceRecord.DefaultTTL = TimeSpan.FromMinutes(75);
ResourceRecord.DefaultHostTTL = TimeSpan.FromSeconds(120);
}
/// <summary>
/// The multicast sender.
/// </summary>
/// <remarks>
/// Always use socketLock to gain access.
/// </remarks>
UdpClient sender;
readonly Object senderLock = new object();
/// <summary>
/// Raised when any local MDNS service sends a query.
/// </summary>
/// <value>
/// Contains the query <see cref="Message"/>.
/// </value>
/// <seealso cref="SendQuery(Message)"/>
/// <see cref="SendAnswer"/>
public event EventHandler<MessageEventArgs> QueryReceived;
/// <summary>
/// Raised when any local MDNS service responds to a query.
/// </summary>
/// <value>
/// Contains the answer <see cref="Message"/>.
/// </value>
public event EventHandler<MessageEventArgs> AnswerReceived;
/// <summary>
/// Raised when one or more network interfaces are discovered.
/// </summary>
/// <value>
/// Contains the network interface(s).
/// </value>
public event EventHandler<NetworkInterfaceEventArgs> NetworkInterfaceDiscovered;
/// <summary>
/// Create a new instance of the <see cref="MulticastService"/> class.
/// </summary>
public MulticastService()
{
if (Socket.OSSupportsIPv4)
ip6 = false;
else if (Socket.OSSupportsIPv6)
ip6 = true;
else
throw new InvalidOperationException("No OS support for IPv4 nor IPv6");
mdnsEndpoint = new IPEndPoint(
ip6 ? MulticastAddressIp6 : MulticastAddressIp4,
MulticastPort);
}
/// <summary>
/// The interval for discovering network interfaces.
/// </summary>
/// <value>
/// Default is 2 minutes.
/// </value>
/// <remarks>
/// When the interval is reached a task is started to discover any
/// new network interfaces.
/// </remarks>
/// <seealso cref="NetworkInterfaceDiscovered"/>
public TimeSpan NetworkInterfaceDiscoveryInterval { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// Get the network interfaces that are useable.
/// </summary>
/// <returns>
/// A sequence of <see cref="NetworkInterface"/>.
/// </returns>
/// <remarks>
/// The following filters are applied
/// <list type="bullet">
/// <item><description>is enabled</description></item>
/// <item><description>not a loopback</description></item>
/// </list>
/// </remarks>
public static IEnumerable<NetworkInterface> GetNetworkInterfaces()
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(nic => nic.OperationalStatus == OperationalStatus.Up)
.Where(nic => nic.NetworkInterfaceType != NetworkInterfaceType.Loopback);
}
/// <summary>
/// Get the IP addresses of the local machine.
/// </summary>
/// <returns>
/// A sequence of IP addresses of the local machine.
/// </returns>
public static IEnumerable<IPAddress> GetIPAddresses()
{
return GetNetworkInterfaces()
.SelectMany(nic => nic.GetIPProperties().UnicastAddresses)
.Select(u => u.Address);
}
/// <summary>
/// Get the link local IP addresses of the local machine.
/// </summary>
/// <returns>
/// A sequence of IP addresses.
/// </returns>
/// <remarks>
/// All IPv4 addresses are considered link local.
/// </remarks>
/// <seealso href="https://en.wikipedia.org/wiki/Link-local_address"/>
public static IEnumerable<IPAddress> GetLinkLocalAddresses()
{
return GetIPAddresses()
.Where(a => a.AddressFamily == AddressFamily.InterNetwork ||
(a.AddressFamily == AddressFamily.InterNetworkV6 && a.IsIPv6LinkLocal));
}
/// <summary>
/// Start the service.
/// </summary>
public void Start()
{
serviceCancellation = new CancellationTokenSource();
maxPacketSize = maxDatagramSize - packetOverhead;
knownNics.Clear();
// Start a task to find the network interfaces.
PollNetworkInterfaces();
}
/// <summary>
/// Stop the service.
/// </summary>
/// <remarks>
/// Clears all the event handlers.
/// </remarks>
public void Stop()
{
// All event handlers are cleared.
QueryReceived = null;
AnswerReceived = null;
NetworkInterfaceDiscovered = null;
// Stop any long runnings tasks.
using (var sc = serviceCancellation)
{
serviceCancellation = null;
sc?.Cancel();
}
using (var lc = listenerCancellation)
{
listenerCancellation = null;
lc?.Cancel();
}
if (sender != null)
{
sender.Dispose();
sender = null;
}
}
async void PollNetworkInterfaces()
{
var cancel = serviceCancellation.Token;
try
{
while (!cancel.IsCancellationRequested)
{
FindNetworkInterfaces();
await Task.Delay(NetworkInterfaceDiscoveryInterval, cancel);
}
}
catch (TaskCanceledException)
{
// eat it
}
catch (Exception e)
{
log.Error(e);
// eat it.
}
}
void FindNetworkInterfaces()
{
var currentNics = GetNetworkInterfaces().ToList();
var newNics = new List<NetworkInterface>();
var oldNics = new List<NetworkInterface>();
lock (senderLock)
{
foreach (var nic in knownNics.Where(k => !currentNics.Any(n => k.Id == n.Id)))
{
oldNics.Add(nic);
if (log.IsDebugEnabled)
{
log.Debug($"Removed nic '{nic.Name}'.");
}
}
foreach (var nic in currentNics.Where(nic => !knownNics.Any(k => k.Id == nic.Id)))
{
newNics.Add(nic);
if (log.IsDebugEnabled)
{
log.Debug($"Found nic '{nic.Name}'.");
}
}
}
knownNics = currentNics;
// If any NIC change, then get new sockets.
if (newNics.Any() || oldNics.Any())
{
// Recreate the sender
if (sender != null)
{
sender.Dispose();
}
sender = new UdpClient(mdnsEndpoint.AddressFamily);
sender.JoinMulticastGroup(mdnsEndpoint.Address);
sender.MulticastLoopback = true;
// Start a task to listen for MDNS messages.
Listener();
}
// Tell others.
if (newNics.Any())
{
NetworkInterfaceDiscovered?.Invoke(this, new NetworkInterfaceEventArgs
{
NetworkInterfaces = newNics
});
}
}
/// <inheritdoc />
public Task<Message> ResolveAsync(Message request, CancellationToken cancel = default(CancellationToken))
{
var tsc = new TaskCompletionSource<Message>();
void checkResponse(object s, MessageEventArgs e)
{
var response = e.Message;
if (request.Questions.All(q => response.Answers.Any(a => a.Name == q.Name)))
{
AnswerReceived -= checkResponse;
tsc.SetResult(response);
}
}
cancel.Register(() =>
{
AnswerReceived -= checkResponse;
tsc.SetCanceled();
});
AnswerReceived += checkResponse;
SendQuery(request);
return tsc.Task;
}
private void MulticastService_AnswerReceived(object sender, MessageEventArgs e)
{
throw new NotImplementedException();
}
/// <summary>
/// Ask for answers about a name.
/// </summary>
/// <param name="name">
/// A domain name that should end with ".local", e.g. "myservice.local".
/// </param>
/// <param name="klass">
/// The class, defaults to <see cref="Class.IN"/>.
/// </param>
/// <param name="type">
/// The question type, defaults to <see cref="DnsType.ANY"/>.
/// </param>
/// <remarks>
/// Answers to any query are obtained on the <see cref="AnswerReceived"/>
/// event.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// When the service has not started.
/// </exception>
public void SendQuery(string name, Class klass = Class.IN, DnsType type = DnsType.ANY)
{
var msg = new Message
{
Opcode = MessageOperation.Query,
QR = false
};
msg.Questions.Add(new Question
{
Name = name,
Class = klass,
Type = type
});
SendQuery(msg);
}
/// <summary>
/// Ask for answers.
/// </summary>
/// <param name="msg">
/// A query message.
/// </param>
/// <remarks>
/// Answers to any query are obtained on the <see cref="AnswerReceived"/>
/// event.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// When the service has not started.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// When the serialised <paramref name="msg"/> is too large.
/// </exception>
public void SendQuery(Message msg)
{
Send(msg);
}
/// <summary>
/// Send an answer to a query.
/// </summary>
/// <param name="answer">
/// The answer message.
/// </param>
/// <exception cref="InvalidOperationException">
/// When the service has not started.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// When the serialised <paramref name="answer"/> is too large.
/// </exception>
/// <remarks>
/// The <see cref="Message.AA"/> flag is set to true,
/// the <see cref="Message.Id"/> set to zero and any questions are removed.
/// <para>
/// The <paramref name="answer"/> is <see cref="Message.Truncate">truncated</see>
/// if exceeds the maximum packet length.
/// </para>
/// </remarks>
/// <see cref="QueryReceived"/>
/// <seealso cref="Message.CreateResponse"/>
public void SendAnswer(Message answer)
{
// All MDNS answers are authoritative and have a transaction
// ID of zero.
answer.AA = true;
answer.Id = 0;
// All MDNS answers must not contain any questions.
answer.Questions.Clear();
answer.Truncate(maxPacketSize);
Send(answer);
}
void Send(Message msg)
{
var packet = msg.ToByteArray();
if (packet.Length > maxPacketSize)
{
throw new ArgumentOutOfRangeException($"Exceeds max packet size of {maxPacketSize}.");
}
lock (senderLock)
{
if (sender == null)
throw new InvalidOperationException("MDNS is not started");
sender.SendAsync(packet, packet.Length, mdnsEndpoint).Wait();
}
}
/// <summary>
/// Called by the listener when a DNS message is received.
/// </summary>
/// <param name="datagram">
/// The received message.
/// </param>
/// <param name="length">
/// The length of the messages.
/// </param>
/// <remarks>
/// Decodes the <paramref name="datagram"/> and then raises
/// either the <see cref="QueryReceived"/> or <see cref="AnswerReceived"/> event.
/// <para>
/// Multicast DNS messages received with an OPCODE or RCODE other than zero
/// are silently ignored.
/// </para>
/// </remarks>
void OnDnsMessage(byte[] datagram, int length)
{
var msg = new Message();
try
{
msg.Read(datagram, 0, length);
}
catch (Exception e)
{
log.Warn("Received malformed message", e);
return; // eat the exception
}
if (msg.Opcode != MessageOperation.Query || msg.Status != MessageStatus.NoError)
{
return;
}
// Dispatch the message.
try
{
if (msg.IsQuery && msg.Questions.Count > 0)
{
QueryReceived?.Invoke(this, new MessageEventArgs { Message = msg });
}
else if (msg.IsResponse && msg.Answers.Count > 0)
{
AnswerReceived?.Invoke(this, new MessageEventArgs { Message = msg });
}
}
catch (Exception e)
{
log.Error("Receive handler failed", e);
// eat the exception
}
}
/// <summary>
/// Listens for DNS messages.
/// </summary>
/// <remarks>
/// A background task to receive DNS messages from this and other MDNS services. It is
/// cancelled via <see cref="Stop"/>. All messages are forwarded to <see cref="OnDnsMessage"/>.
/// </remarks>
async void Listener()
{
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
// Stop the previous listener.
if (listenerCancellation != null)
{
listenerCancellation.Cancel();
}
listenerCancellation = new CancellationTokenSource();
UdpClient receiver = new UdpClient(mdnsEndpoint.AddressFamily);
if (isWindows)
{
receiver.ExclusiveAddressUse = false;
}
receiver.Client.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress,
true);
if (isWindows)
{
receiver.ExclusiveAddressUse = false;
}
var endpoint = new IPEndPoint(ip6 ? IPAddress.IPv6Any : IPAddress.Any, MulticastPort);
receiver.Client.Bind(endpoint);
receiver.JoinMulticastGroup(mdnsEndpoint.Address);
var cancel = listenerCancellation.Token;
cancel.Register(() => receiver.Dispose());
try
{
while (!cancel.IsCancellationRequested)
{
var result = await receiver.ReceiveAsync();
OnDnsMessage(result.Buffer, result.Buffer.Length);
}
}
catch (Exception e)
{
if (!cancel.IsCancellationRequested)
log.Error("Listener failed", e);
// eat the exception
}
receiver.Dispose();
if (listenerCancellation != null)
{
listenerCancellation.Dispose();
listenerCancellation = null;
}
}
#region IDisposable Support
/// <inheritdoc />
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Stop();
}
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
}
#endregion
}
}