forked from jellyfin/jellyfin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SsdpCommunicationsServer.cs
511 lines (422 loc) · 20.1 KB
/
SsdpCommunicationsServer.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
namespace Rssdp.Infrastructure
{
/// <summary>
/// Provides the platform independent logic for publishing device existence and responding to search requests.
/// </summary>
public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
{
#region Fields
/*
We could technically use one socket listening on port 1900 for everything.
This should get both multicast (notifications) and unicast (search response) messages, however
this often doesn't work under Windows because the MS SSDP service is running. If that service
is running then it will steal the unicast messages and we will never see search responses.
Since stopping the service would be a bad idea (might not be allowed security wise and might
break other apps running on the system) the only other work around is to use two sockets.
We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket).
We use a second socket, bound to a different local port, to send search requests and listen for
responses (_SendSocket). The responses are sent to the local port this socket is bound to,
which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local
port to use, we will default to 0 which allows the underlying system to auto-assign a free port.
*/
private object _BroadcastListenSocketSynchroniser = new object();
private ISocket _BroadcastListenSocket;
private object _SendSocketSynchroniser = new object();
private List<ISocket> _sendSockets;
private HttpRequestParser _RequestParser;
private HttpResponseParser _ResponseParser;
private readonly ILogger _logger;
private ISocketFactory _SocketFactory;
private readonly INetworkManager _networkManager;
private int _LocalPort;
private int _MulticastTtl;
private bool _IsShared;
private readonly bool _enableMultiSocketBinding;
#endregion
#region Events
/// <summary>
/// Raised when a HTTPU request message is received by a socket (unicast or multicast).
/// </summary>
public event EventHandler<RequestReceivedEventArgs> RequestReceived;
/// <summary>
/// Raised when an HTTPU response message is received by a socket (unicast or multicast).
/// </summary>
public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
#endregion
#region Constructors
/// <summary>
/// Minimum constructor.
/// </summary>
/// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
public SsdpCommunicationsServer(ISocketFactory socketFactory, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
: this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive, networkManager, logger, enableMultiSocketBinding)
{
}
/// <summary>
/// Full constructor.
/// </summary>
/// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
{
if (socketFactory == null) throw new ArgumentNullException("socketFactory");
if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException("multicastTimeToLive", "multicastTimeToLive must be greater than zero.");
_BroadcastListenSocketSynchroniser = new object();
_SendSocketSynchroniser = new object();
_LocalPort = localPort;
_SocketFactory = socketFactory;
_RequestParser = new HttpRequestParser();
_ResponseParser = new HttpResponseParser();
_MulticastTtl = multicastTimeToLive;
_networkManager = networkManager;
_logger = logger;
_enableMultiSocketBinding = enableMultiSocketBinding;
}
#endregion
#region Public Methods
/// <summary>
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
/// </summary>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void BeginListeningForBroadcasts()
{
ThrowIfDisposed();
if (_BroadcastListenSocket == null)
{
lock (_BroadcastListenSocketSynchroniser)
{
if (_BroadcastListenSocket == null)
{
try
{
_BroadcastListenSocket = ListenForBroadcastsAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in BeginListeningForBroadcasts");
}
}
}
}
}
/// <summary>
/// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
/// </summary>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void StopListeningForBroadcasts()
{
lock (_BroadcastListenSocketSynchroniser)
{
if (_BroadcastListenSocket != null)
{
_logger.LogInformation("{0} disposing _BroadcastListenSocket.", GetType().Name);
_BroadcastListenSocket.Dispose();
_BroadcastListenSocket = null;
}
}
}
/// <summary>
/// Sends a message to a particular address (uni or multicast) and port.
/// </summary>
public async Task SendMessage(byte[] messageData, IpEndPointInfo destination, IpAddressInfo fromLocalIpAddress, CancellationToken cancellationToken)
{
if (messageData == null) throw new ArgumentNullException("messageData");
ThrowIfDisposed();
var sockets = GetSendSockets(fromLocalIpAddress, destination);
if (sockets.Count == 0)
{
return;
}
// SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
for (var i = 0; i < SsdpConstants.UdpResendCount; i++)
{
var tasks = sockets.Select(s => SendFromSocket(s, messageData, destination, cancellationToken)).ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
}
private async Task SendFromSocket(ISocket socket, byte[] messageData, IpEndPointInfo destination, CancellationToken cancellationToken)
{
try
{
await socket.SendToAsync(messageData, 0, messageData.Length, destination, cancellationToken).ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString());
}
}
private List<ISocket> GetSendSockets(IpAddressInfo fromLocalIpAddress, IpEndPointInfo destination)
{
EnsureSendSocketCreated();
lock (_SendSocketSynchroniser)
{
var sockets = _sendSockets.Where(i => i.LocalIPAddress.AddressFamily == fromLocalIpAddress.AddressFamily);
// Send from the Any socket and the socket with the matching address
if (fromLocalIpAddress.AddressFamily == IpAddressFamily.InterNetwork)
{
sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
// If sending to the loopback address, filter the socket list as well
if (destination.IpAddress.Equals(IpAddressInfo.Loopback))
{
sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.Any) || i.LocalIPAddress.Equals(IpAddressInfo.Loopback));
}
}
else if (fromLocalIpAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
{
sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
// If sending to the loopback address, filter the socket list as well
if (destination.IpAddress.Equals(IpAddressInfo.IPv6Loopback))
{
sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.IPv6Any) || i.LocalIPAddress.Equals(IpAddressInfo.IPv6Loopback));
}
}
return sockets.ToList();
}
}
public Task SendMulticastMessage(string message, CancellationToken cancellationToken)
{
return SendMulticastMessage(message, SsdpConstants.UdpResendCount, cancellationToken);
}
/// <summary>
/// Sends a message to the SSDP multicast address and port.
/// </summary>
public async Task SendMulticastMessage(string message, int sendCount, CancellationToken cancellationToken)
{
if (message == null) throw new ArgumentNullException("messageData");
byte[] messageData = Encoding.UTF8.GetBytes(message);
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
EnsureSendSocketCreated();
// SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
for (var i = 0; i < sendCount; i++)
{
await SendMessageIfSocketNotDisposed(messageData, new IpEndPointInfo
{
IpAddress = new IpAddressInfo(SsdpConstants.MulticastLocalAdminAddress, IpAddressFamily.InterNetwork),
Port = SsdpConstants.MulticastPort
}, cancellationToken).ConfigureAwait(false);
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Stops listening for search responses on the local, unicast socket.
/// </summary>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void StopListeningForResponses()
{
lock (_SendSocketSynchroniser)
{
if (_sendSockets != null)
{
var sockets = _sendSockets.ToList();
_sendSockets = null;
_logger.LogInformation("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count);
foreach (var socket in sockets)
{
_logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress);
socket.Dispose();
}
}
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
/// </summary>
/// <remarks>
/// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocatorBase"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para>
/// </remarks>
public bool IsShared
{
get { return _IsShared; }
set { _IsShared = value; }
}
#endregion
#region Overrides
/// <summary>
/// Stops listening for requests, disposes this instance and all internal resources.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
StopListeningForBroadcasts();
StopListeningForResponses();
}
}
#endregion
#region Private Methods
private Task SendMessageIfSocketNotDisposed(byte[] messageData, IpEndPointInfo destination, CancellationToken cancellationToken)
{
var sockets = _sendSockets;
if (sockets != null)
{
sockets = sockets.ToList();
var tasks = sockets.Select(s => SendFromSocket(s, messageData, destination, cancellationToken));
return Task.WhenAll(tasks);
}
return Task.CompletedTask;
}
private ISocket ListenForBroadcastsAsync()
{
var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort);
ListenToSocket(socket);
return socket;
}
private List<ISocket> CreateSocketAndListenForResponsesAsync()
{
var sockets = new List<ISocket>();
sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IpAddressInfo.Any, _LocalPort));
if (_enableMultiSocketBinding)
{
foreach (var address in _networkManager.GetLocalIpAddresses())
{
if (address.AddressFamily == IpAddressFamily.InterNetworkV6)
{
// Not supported ?
continue;
}
try
{
sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address, _LocalPort));
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address);
}
}
}
foreach (var socket in sockets)
{
ListenToSocket(socket);
}
return sockets;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable removes compiler warning, task is not otherwise required.")]
private void ListenToSocket(ISocket socket)
{
// Tasks are captured to local variables even if we don't use them just to avoid compiler warnings.
var t = Task.Run(() => ListenToSocketInternal(socket));
}
private async Task ListenToSocketInternal(ISocket socket)
{
var cancelled = false;
var receiveBuffer = new byte[8192];
while (!cancelled && !IsDisposed)
{
try
{
var result = await socket.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false);
if (result.ReceivedBytes > 0)
{
// Strange cannot convert compiler error here if I don't explicitly
// assign or cast to Action first. Assignment is easier to read,
// so went with that.
ProcessMessage(System.Text.UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress);
}
}
catch (ObjectDisposedException)
{
cancelled = true;
}
catch (TaskCanceledException)
{
cancelled = true;
}
}
}
private void EnsureSendSocketCreated()
{
if (_sendSockets == null)
{
lock (_SendSocketSynchroniser)
{
if (_sendSockets == null)
{
_sendSockets = CreateSocketAndListenForResponsesAsync();
}
}
}
}
private void ProcessMessage(string data, IpEndPointInfo endPoint, IpAddressInfo receivedOnLocalIpAddress)
{
//Responses start with the HTTP version, prefixed with HTTP/ while
//requests start with a method which can vary and might be one we haven't
//seen/don't know. We'll check if this message is a request or a response
//by checking for the HTTP/ prefix on the start of the message.
if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{
HttpResponseMessage responseMessage = null;
try
{
responseMessage = _ResponseParser.Parse(data);
}
catch (ArgumentException)
{
// Ignore invalid packets.
}
if (responseMessage != null)
OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress);
}
else
{
HttpRequestMessage requestMessage = null;
try
{
requestMessage = _RequestParser.Parse(data);
}
catch (ArgumentException)
{
// Ignore invalid packets.
}
if (requestMessage != null)
{
OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress);
}
}
}
private void OnRequestReceived(HttpRequestMessage data, IpEndPointInfo remoteEndPoint, IpAddressInfo receivedOnLocalIpAddress)
{
//SSDP specification says only * is currently used but other uri's might
//be implemented in the future and should be ignored unless understood.
//Section 4.2 - http://tools.ietf.org/html/draft-cai-ssdp-v1-03#page-11
if (data.RequestUri.ToString() != "*")
{
return;
}
var handlers = this.RequestReceived;
if (handlers != null)
handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
}
private void OnResponseReceived(HttpResponseMessage data, IpEndPointInfo endPoint, IpAddressInfo localIpAddress)
{
var handlers = this.ResponseReceived;
if (handlers != null)
handlers(this, new ResponseReceivedEventArgs(data, endPoint)
{
LocalIpAddress = localIpAddress
});
}
#endregion
}
}