diff options
Diffstat (limited to 'RSSDP/SsdpCommunicationsServer.cs')
| -rw-r--r-- | RSSDP/SsdpCommunicationsServer.cs | 265 |
1 files changed, 147 insertions, 118 deletions
diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 6e4f5634d..42563e2ed 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -25,18 +25,18 @@ namespace Rssdp.Infrastructure * 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 + * We use one group of sockets to listen for/receive notifications and search requests (_MulticastListenSockets). + * We use a second group, bound to a different local port, to send search requests and listen for + * responses (_SendSockets). The responses are sent to the local ports these sockets are bound to, + * which aren'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 _BroadcastListenSocketSynchroniser = new(); + private List<Socket> _MulticastListenSockets; - private object _SendSocketSynchroniser = new object(); - private List<ISocket> _sendSockets; + private object _SendSocketSynchroniser = new(); + private List<Socket> _sendSockets; private HttpRequestParser _RequestParser; private HttpResponseParser _ResponseParser; @@ -48,7 +48,6 @@ namespace Rssdp.Infrastructure private int _MulticastTtl; private bool _IsShared; - private readonly bool _enableMultiSocketBinding; /// <summary> /// Raised when a HTTPU request message is received by a socket (unicast or multicast). @@ -64,9 +63,11 @@ namespace Rssdp.Infrastructure /// Minimum constructor. /// </summary> /// <exception cref="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) + public SsdpCommunicationsServer( + ISocketFactory socketFactory, + INetworkManager networkManager, + ILogger logger) + : this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive, networkManager, logger) { } @@ -76,9 +77,14 @@ namespace Rssdp.Infrastructure /// </summary> /// <exception cref="ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception> /// <exception cref="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) + public SsdpCommunicationsServer( + ISocketFactory socketFactory, + int localPort, + int multicastTimeToLive, + INetworkManager networkManager, + ILogger logger) { - if (socketFactory == null) + if (socketFactory is null) { throw new ArgumentNullException(nameof(socketFactory)); } @@ -88,47 +94,43 @@ namespace Rssdp.Infrastructure throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero."); } - _BroadcastListenSocketSynchroniser = new object(); - _SendSocketSynchroniser = new object(); + _BroadcastListenSocketSynchroniser = new(); + _SendSocketSynchroniser = new(); _LocalPort = localPort; _SocketFactory = socketFactory; - _RequestParser = new HttpRequestParser(); - _ResponseParser = new HttpResponseParser(); + _RequestParser = new(); + _ResponseParser = new(); _MulticastTtl = multicastTimeToLive; _networkManager = networkManager; _logger = logger; - _enableMultiSocketBinding = enableMultiSocketBinding; } /// <summary> /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// </summary> /// <exception cref="ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception> - public void BeginListeningForBroadcasts() + public void BeginListeningForMulticast() { ThrowIfDisposed(); - if (_BroadcastListenSocket == null) + lock (_BroadcastListenSocketSynchroniser) { - lock (_BroadcastListenSocketSynchroniser) + if (_MulticastListenSockets is null) { - if (_BroadcastListenSocket == null) + try + { + _MulticastListenSockets = CreateMulticastSocketsAndListen(); + } + catch (SocketException ex) { - try - { - _BroadcastListenSocket = ListenForBroadcastsAsync(); - } - catch (SocketException ex) - { - _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); - } + _logger.LogError("Failed to bind to multicast address: {Message}. DLNA will be unavailable", ex.Message); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error in BeginListeningForMulticast"); } } } @@ -138,15 +140,19 @@ namespace Rssdp.Infrastructure /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications. /// </summary> /// <exception cref="ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception> - public void StopListeningForBroadcasts() + public void StopListeningForMulticast() { lock (_BroadcastListenSocketSynchroniser) { - if (_BroadcastListenSocket != null) + if (_MulticastListenSockets is not null) { _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name); - _BroadcastListenSocket.Dispose(); - _BroadcastListenSocket = null; + foreach (var socket in _MulticastListenSockets) + { + socket.Dispose(); + } + + _MulticastListenSockets = null; } } } @@ -154,16 +160,16 @@ namespace Rssdp.Infrastructure /// <summary> /// Sends a message to a particular address (uni or multicast) and port. /// </summary> - public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { - if (messageData == null) + if (messageData is null) { throw new ArgumentNullException(nameof(messageData)); } ThrowIfDisposed(); - var sockets = GetSendSockets(fromLocalIpAddress, destination); + var sockets = GetSendSockets(fromlocalIPAddress, destination); if (sockets.Count == 0) { @@ -180,11 +186,11 @@ namespace Rssdp.Infrastructure } } - private async Task SendFromSocket(ISocket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken) + private async Task SendFromSocket(Socket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken) { try { - await socket.SendToAsync(messageData, 0, messageData.Length, destination, cancellationToken).ConfigureAwait(false); + await socket.SendToAsync(messageData, destination, cancellationToken).ConfigureAwait(false); } catch (ObjectDisposedException) { @@ -194,37 +200,42 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString()); + var localIP = ((IPEndPoint)socket.LocalEndPoint).Address; + _logger.LogError(ex, "Error sending socket message from {0} to {1}", localIP.ToString(), destination.ToString()); } } - private List<ISocket> GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) + private List<Socket> GetSendSockets(IPAddress fromlocalIPAddress, IPEndPoint destination) { EnsureSendSocketCreated(); lock (_SendSocketSynchroniser) { - var sockets = _sendSockets.Where(i => i.LocalIPAddress.AddressFamily == fromLocalIpAddress.AddressFamily); + var sockets = _sendSockets.Where(s => s.AddressFamily == fromlocalIPAddress.AddressFamily); // Send from the Any socket and the socket with the matching address - if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetwork) + if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetwork) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.Loopback)) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || i.LocalIPAddress.Equals(IPAddress.Loopback)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback)); } } - else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6) + else if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetworkV6) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.IPv6Loopback)) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || i.LocalIPAddress.Equals(IPAddress.IPv6Loopback)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Loopback)); } } @@ -232,17 +243,17 @@ namespace Rssdp.Infrastructure } } - public Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public Task SendMulticastMessage(string message, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { - return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromLocalIpAddress, cancellationToken); + return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromlocalIPAddress, cancellationToken); } /// <summary> /// Sends a message to the SSDP multicast address and port. /// </summary> - public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { - if (message == null) + if (message is null) { throw new ArgumentNullException(nameof(message)); } @@ -263,7 +274,7 @@ namespace Rssdp.Infrastructure new IPEndPoint( IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), SsdpConstants.MulticastPort), - fromLocalIpAddress, + fromlocalIPAddress, cancellationToken).ConfigureAwait(false); await Task.Delay(100, cancellationToken).ConfigureAwait(false); @@ -278,7 +289,7 @@ namespace Rssdp.Infrastructure { lock (_SendSocketSynchroniser) { - if (_sendSockets != null) + if (_sendSockets is not null) { var sockets = _sendSockets.ToList(); _sendSockets = null; @@ -287,7 +298,8 @@ namespace Rssdp.Infrastructure foreach (var socket in sockets) { - _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); + var socketAddress = ((IPEndPoint)socket.LocalEndPoint).Address; + _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socketAddress); socket.Dispose(); } } @@ -315,20 +327,20 @@ namespace Rssdp.Infrastructure { if (disposing) { - StopListeningForBroadcasts(); + StopListeningForMulticast(); StopListeningForResponses(); } } - private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { var sockets = _sendSockets; - if (sockets != null) + if (sockets is not null) { sockets = sockets.ToList(); - var tasks = sockets.Where(s => (fromLocalIpAddress == null || fromLocalIpAddress.Equals(s.LocalIPAddress))) + var tasks = sockets.Where(s => fromlocalIPAddress is null || fromlocalIPAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address)) .Select(s => SendFromSocket(s, messageData, destination, cancellationToken)); return Task.WhenAll(tasks); } @@ -336,50 +348,69 @@ namespace Rssdp.Infrastructure return Task.CompletedTask; } - private ISocket ListenForBroadcastsAsync() + private List<Socket> CreateMulticastSocketsAndListen() { - var socket = _SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), _MulticastTtl, SsdpConstants.MulticastPort); - _ = ListenToSocketInternal(socket); + var sockets = new List<Socket>(); + var multicastGroupAddress = IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress); - return socket; + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.SupportsMulticast) + .Where(x => x.AddressFamily == AddressFamily.InterNetwork) + .DistinctBy(x => x.Index); + + foreach (var intf in validInterfaces) + { + try + { + var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, intf, _MulticastTtl, SsdpConstants.MulticastPort); + _ = ListenToSocketInternal(socket); + sockets.Add(socket); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create SSDP UDP multicast socket for {0} on interface {1} (index {2})", intf.Address, intf.Name, intf.Index); + } + } + + return sockets; } - private List<ISocket> CreateSocketAndListenForResponsesAsync() + private List<Socket> CreateSendSockets() { - var sockets = new List<ISocket>(); + var sockets = new List<Socket>(); - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort)); + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.SupportsMulticast) + .Where(x => x.AddressFamily == AddressFamily.InterNetwork); - if (_enableMultiSocketBinding) + if (OperatingSystem.IsMacOS()) { - foreach (var address in _networkManager.GetInternalBindAddresses()) - { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not support IPv6 right now - continue; - } - - try - { - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort)); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address); - } - } + // Manually remove loopback on macOS due to https://github.com/dotnet/runtime/issues/24340 + validInterfaces = validInterfaces.Where(x => !x.Address.Equals(IPAddress.Loopback)); } - foreach (var socket in sockets) + foreach (var intf in validInterfaces) { - _ = ListenToSocketInternal(socket); + try + { + var socket = _SocketFactory.CreateSsdpUdpSocket(intf, _LocalPort); + _ = ListenToSocketInternal(socket); + sockets.Add(socket); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create SSDP UDP sender socket for {0} on interface {1} (index {2})", intf.Address, intf.Name, intf.Index); + } } return sockets; } - private async Task ListenToSocketInternal(ISocket socket) + private async Task ListenToSocketInternal(Socket socket) { var cancelled = false; var receiveBuffer = new byte[8192]; @@ -388,14 +419,17 @@ namespace Rssdp.Infrastructure { try { - var result = await socket.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false); + var result = await socket.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, _LocalPort), 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(UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress); + var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint; + var localEndpointAdapter = _networkManager.GetAllBindInterfaces().First(a => a.Index == result.PacketInformation.Interface); + + ProcessMessage( + Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes), + remoteEndpoint, + localEndpointAdapter.Address); } } catch (ObjectDisposedException) @@ -411,21 +445,22 @@ namespace Rssdp.Infrastructure private void EnsureSendSocketCreated() { - if (_sendSockets == null) + if (_sendSockets is null) { lock (_SendSocketSynchroniser) { - _sendSockets ??= CreateSocketAndListenForResponsesAsync(); + _sendSockets ??= CreateSendSockets(); } } } - private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnLocalIpAddress) + private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress 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. + _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnlocalIPAddress, data); if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase)) { HttpResponseMessage responseMessage = null; @@ -438,9 +473,9 @@ namespace Rssdp.Infrastructure // Ignore invalid packets. } - if (responseMessage != null) + if (responseMessage is not null) { - OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); + OnResponseReceived(responseMessage, endPoint, receivedOnlocalIPAddress); } } else @@ -455,14 +490,14 @@ namespace Rssdp.Infrastructure // Ignore invalid packets. } - if (requestMessage != null) + if (requestMessage is not null) { - OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress); + OnRequestReceived(requestMessage, endPoint, receivedOnlocalIPAddress); } } } - private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnLocalIpAddress) + private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnlocalIPAddress) { // SSDP specification says only * is currently used but other uri's might // be implemented in the future and should be ignored unless understood. @@ -472,23 +507,17 @@ namespace Rssdp.Infrastructure return; } - var handlers = this.RequestReceived; - if (handlers != null) - { - handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress)); - } + var handlers = RequestReceived; + handlers?.Invoke(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnlocalIPAddress)); } - private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress) + private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIPAddress) { - var handlers = this.ResponseReceived; - if (handlers != null) + var handlers = ResponseReceived; + handlers?.Invoke(this, new ResponseReceivedEventArgs(data, endPoint) { - handlers(this, new ResponseReceivedEventArgs(data, endPoint) - { - LocalIpAddress = localIpAddress - }); - } + LocalIPAddress = localIPAddress + }); } } } |
