-
Notifications
You must be signed in to change notification settings - Fork 78
/
ServiceDiscovery.cs
251 lines (226 loc) · 8.43 KB
/
ServiceDiscovery.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
using Common.Logging;
using Makaretu.Dns.Resolving;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Makaretu.Dns
{
/// <summary>
/// DNS based Service Discovery is a way of using standard DNS programming interfaces, servers,
/// and packet formats to browse the network for services.
/// </summary>
/// <seealso href="https://tools.ietf.org/html/rfc6763">RFC 6763 DNS-Based Service Discovery</seealso>
public class ServiceDiscovery : IDisposable
{
static readonly ILog log = LogManager.GetLogger(typeof(ServiceDiscovery));
/// <summary>
/// The service discovery service name.
/// </summary>
/// <value>
/// The service name used to enumerate other services.
/// </value>
public const string ServiceName = "_services._dns-sd._udp.local";
readonly bool ownsMdns;
List<ServiceProfile> profiles = new List<ServiceProfile>();
/// <summary>
/// Creates a new instance of the <see cref="ServiceDiscovery"/> class.
/// </summary>
public ServiceDiscovery()
: this(new MulticastService())
{
ownsMdns = true;
// Auto start.
Mdns.Start();
}
/// <summary>
/// Creates a new instance of the <see cref="ServiceDiscovery"/> class with
/// the specified <see cref="MulticastService"/>.
/// </summary>
/// <param name="mdns">
/// The underlaying <see cref="MulticastService"/> to use.
/// </param>
public ServiceDiscovery(MulticastService mdns)
{
this.Mdns = mdns;
mdns.QueryReceived += OnQuery;
mdns.AnswerReceived += OnAnswer;
}
/// <summary>
/// Gets the multicasting service.
/// </summary>
/// <value>
/// Is used to send and recieve multicast <see cref="Message">DNS messages</see>.
/// </value>
public MulticastService Mdns { get; private set; }
/// <summary>
/// Add the additional records into the answers.
/// </summary>
/// <value>
/// Defaults to <b>false</b>.
/// </value>
/// <remarks>
/// Some malformed systems, such as js-ipfs and go-ipfs, only examine
/// the <see cref="Message.Answers"/> and not the <see cref="Message.AdditionalRecords"/>.
/// Setting this to <b>true</b>, will move the additional records
/// into the answers.
/// </remarks>
public bool AnswersContainsAdditionalRecords { get; set; }
/// <summary>
/// Gets the name server.
/// </summary>
/// <value>
/// Is used to answer questions.
/// </value>
public NameServer NameServer { get; } = new NameServer {
Catalog = new Catalog(),
AnswerAllQuestions = true
};
/// <summary>
/// Raised when a DNS-SD response is received.
/// </summary>
/// <value>
/// Contains the service name.
/// </value>
/// <remarks>
/// <b>ServiceDiscovery</b> passively monitors the network for any answers
/// to a DNS-SD query. When an anwser is received this event is raised.
/// <para>
/// Use <see cref="QueryAllServices"/> to initiate a DNS-SD question.
/// </para>
/// </remarks>
public event EventHandler<string> ServiceDiscovered;
/// <summary>
/// Raised when a servive instance is discovered.
/// </summary>
/// <value>
/// Contains the service instance name.
/// </value>
/// <remarks>
/// <b>ServiceDiscovery</b> passively monitors the network for any answers.
/// When an answer containing a PTR to a service instance is received
/// this event is raised.
/// </remarks>
public event EventHandler<ServiceInstanceDiscoveryEventArgs> ServiceInstanceDiscovered;
/// <summary>
/// Asks other MDNS services to send their service names.
/// </summary>
/// <remarks>
/// When an answer is received the <see cref="ServiceDiscovered"/> event is raised.
/// </remarks>
public void QueryAllServices()
{
Mdns.SendQuery(ServiceName, type: DnsType.PTR);
}
/// <summary>
/// Asks instances of the specified service to send details.
/// </summary>
/// <param name="service">
/// The service name to query. Typically of the form "_<i>service</i>._tcp".
/// </param>
/// <remarks>
/// When an answer is received the <see cref="ServiceInstanceDiscovered"/> event is raised.
/// </remarks>
/// <seealso cref="ServiceProfile.ServiceName"/>
public void QueryServiceInstances(string service)
{
Mdns.SendQuery(service + ".local", type: DnsType.PTR);
}
/// <summary>
/// Advertise a service profile.
/// </summary>
/// <param name="service">
/// The service profile.
/// </param>
/// <remarks>
/// Any queries for the service or service instance will be answered with
/// information from the profile.
/// </remarks>
public void Advertise(ServiceProfile service)
{
profiles.Add(service);
var catalog = NameServer.Catalog;
catalog.Add(
new PTRRecord { Name = ServiceName, DomainName = service.QualifiedServiceName },
authoritative: true);
catalog.Add(
new PTRRecord { Name = service.QualifiedServiceName, DomainName = service.FullyQualifiedName },
authoritative: true);
foreach (var r in service.Resources)
{
catalog.Add(r, authoritative: true);
}
}
void OnAnswer(object sender, MessageEventArgs e)
{
var msg = e.Message;
// Any DNS-SD answers?
var sd = msg.Answers.OfType<PTRRecord>();
foreach (var ptr in sd)
{
if (ptr.Name == ServiceName)
{
ServiceDiscovered?.Invoke(this, ptr.DomainName);
}
else
{
var args = new ServiceInstanceDiscoveryEventArgs
{
ServiceInstanceName = ptr.DomainName,
Message = msg
};
ServiceInstanceDiscovered?.Invoke(this, args);
}
}
}
void OnQuery(object sender, MessageEventArgs e)
{
var request = e.Message;
if (log.IsDebugEnabled)
log.Debug($"got query for {request.Questions[0].Name} {request.Questions[0].Type}");
var response = NameServer.ResolveAsync(request).Result;
if (response.Status == MessageStatus.NoError)
{
// Many bonjour browsers don't like DNS-SD response
// with additional records.
if (response.Answers.Any(a => a.Name == ServiceName))
{
response.AdditionalRecords.Clear();
}
if (AnswersContainsAdditionalRecords)
{
response.Answers.AddRange(response.AdditionalRecords);
response.AdditionalRecords.Clear();
}
Mdns.SendAnswer(response);
if (log.IsDebugEnabled)
log.Debug($"sent answer {response.Answers[0]}");
//Console.WriteLine($"Response time {(DateTime.Now - request.CreationTime).TotalMilliseconds}ms");
}
}
#region IDisposable Support
/// <inheritdoc />
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Mdns != null)
{
Mdns.QueryReceived -= OnQuery;
Mdns.AnswerReceived -= OnAnswer;
if (ownsMdns)
{
Mdns.Dispose();
}
Mdns = null;
}
}
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
}
#endregion
}
}