jellyfin-server/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs

701 lines
23 KiB
C#
Raw Normal View History

2015-04-29 18:48:34 +00:00
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
2014-06-22 05:52:31 +00:00
using MediaBrowser.Common.Events;
2014-04-27 03:42:05 +00:00
using MediaBrowser.Controller.Configuration;
2015-04-29 18:48:34 +00:00
using MediaBrowser.Controller.Dlna;
2014-04-25 17:30:41 +00:00
using MediaBrowser.Dlna.Server;
2014-03-24 12:47:39 +00:00
using MediaBrowser.Model.Logging;
using System;
2014-04-10 15:06:54 +00:00
using System.Collections.Concurrent;
2014-03-24 12:47:39 +00:00
using System.Collections.Generic;
2014-11-07 00:16:16 +00:00
using System.Globalization;
2014-03-24 12:47:39 +00:00
using System.Linq;
using System.Net;
using System.Net.Sockets;
2014-06-29 17:35:05 +00:00
using System.Text;
2014-04-10 15:06:54 +00:00
using System.Threading;
2014-11-07 00:16:16 +00:00
using System.Threading.Tasks;
using Microsoft.Win32;
2014-03-24 12:47:39 +00:00
2014-04-25 17:30:41 +00:00
namespace MediaBrowser.Dlna.Ssdp
2014-03-24 12:47:39 +00:00
{
2015-04-29 18:48:34 +00:00
public class SsdpHandler : IDisposable, ISsdpHandler
2014-03-24 12:47:39 +00:00
{
2016-02-13 19:41:19 +00:00
private Socket _multicastSocket;
2014-04-10 15:06:54 +00:00
2014-03-24 12:47:39 +00:00
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
const string SSDPAddr = "239.255.255.250";
const int SSDPPort = 1900;
2014-04-25 17:30:41 +00:00
private readonly string _serverSignature;
2014-03-24 12:47:39 +00:00
private readonly IPAddress _ssdpIp = IPAddress.Parse(SSDPAddr);
2014-04-25 17:30:41 +00:00
private readonly IPEndPoint _ssdpEndp = new IPEndPoint(IPAddress.Parse(SSDPAddr), SSDPPort);
2014-03-24 12:47:39 +00:00
2014-04-10 15:06:54 +00:00
private Timer _notificationTimer;
2014-04-27 03:42:05 +00:00
2014-04-25 17:30:41 +00:00
private bool _isDisposed;
private readonly ConcurrentDictionary<string, List<UpnpDevice>> _devices = new ConcurrentDictionary<string, List<UpnpDevice>>();
2014-04-27 03:42:05 +00:00
2015-04-29 18:48:34 +00:00
private readonly IApplicationHost _appHost;
2016-02-13 19:41:19 +00:00
private readonly int _unicastPort = 1901;
private UdpClient _unicastClient;
2015-04-29 18:48:34 +00:00
public SsdpHandler(ILogger logger, IServerConfigurationManager config, IApplicationHost appHost)
2014-03-24 12:47:39 +00:00
{
_logger = logger;
_config = config;
2015-04-29 18:48:34 +00:00
_appHost = appHost;
2014-04-28 15:05:28 +00:00
2014-06-29 17:35:05 +00:00
_config.NamedConfigurationUpdated += _config_ConfigurationUpdated;
2015-04-29 18:48:34 +00:00
_serverSignature = GenerateServerSignature();
}
private string GenerateServerSignature()
{
var os = Environment.OSVersion;
var pstring = os.Platform.ToString();
switch (os.Platform)
{
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
pstring = "WIN";
break;
}
return String.Format(
2015-05-04 17:46:44 +00:00
"{0}{1}/{2}.{3} UPnP/1.0 DLNADOC/1.5 Emby/{4}",
2015-04-29 18:48:34 +00:00
pstring,
IntPtr.Size * 8,
os.Version.Major,
os.Version.Minor,
_appHost.ApplicationVersion
);
2014-04-28 15:05:28 +00:00
}
2014-06-29 17:35:05 +00:00
void _config_ConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
2014-04-28 15:05:28 +00:00
{
2014-06-29 17:35:05 +00:00
if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
{
ReloadAliveNotifier();
}
2014-04-25 17:30:41 +00:00
}
public event EventHandler<SsdpMessageEventArgs> MessageReceived;
2014-03-24 12:47:39 +00:00
2016-02-17 04:44:31 +00:00
private async void OnMessageReceived(SsdpMessageEventArgs args, bool isMulticast)
2014-04-25 17:30:41 +00:00
{
2016-02-17 04:44:31 +00:00
if (IgnoreMessage(args, isMulticast))
{
return;
}
2016-02-17 21:24:01 +00:00
LogMessageReceived(args, isMulticast);
2016-02-17 04:44:31 +00:00
2015-05-04 17:53:45 +00:00
var headers = args.Headers;
string st;
2015-04-11 17:59:55 +00:00
2015-05-04 17:53:45 +00:00
if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase) && headers.TryGetValue("st", out st))
{
2015-04-11 17:59:55 +00:00
TimeSpan delay = GetSearchDelay(headers);
2015-05-04 17:53:45 +00:00
2016-02-12 04:33:14 +00:00
if (_config.GetDlnaConfiguration().EnableDebugLog)
2014-08-12 02:59:51 +00:00
{
_logger.Debug("Delaying search response by {0} seconds", delay.TotalSeconds);
2014-08-12 02:59:51 +00:00
}
2015-05-04 17:53:45 +00:00
2015-04-11 17:59:55 +00:00
await Task.Delay(delay).ConfigureAwait(false);
2014-08-12 02:59:51 +00:00
2015-05-04 17:53:45 +00:00
RespondToSearch(args.EndPoint, st);
2014-04-25 17:30:41 +00:00
}
2014-04-27 03:42:05 +00:00
EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger);
2014-03-24 12:47:39 +00:00
}
2016-02-17 21:24:01 +00:00
internal void LogMessageReceived(SsdpMessageEventArgs args, bool isMulticast)
{
var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
if (enableDebugLogging)
{
var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
var headerText = string.Join(",", headerTexts.ToArray());
var protocol = isMulticast ? "Multicast" : "Unicast";
var localEndPointString = args.LocalEndPoint == null ? "null" : args.LocalEndPoint.ToString();
_logger.Debug("{0} message received from {1} on {3}. Protocol: {4} Headers: {2}", args.Method, args.EndPoint, headerText, localEndPointString, protocol);
}
}
2016-02-17 04:44:31 +00:00
internal bool IgnoreMessage(SsdpMessageEventArgs args, bool isMulticast)
{
string usn;
if (args.Headers.TryGetValue("USN", out usn))
{
// USN=uuid:b67df29b5c379445fde78c3774ab518d::urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1
if (RegisteredDevices.Select(i => i.USN).Contains(usn, StringComparer.OrdinalIgnoreCase))
{
//var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
//var headerText = string.Join(",", headerTexts.ToArray());
//var protocol = isMulticast ? "Multicast" : "Unicast";
//var localEndPointString = args.LocalEndPoint == null ? "null" : args.LocalEndPoint.ToString();
//_logger.Debug("IGNORING {0} message received from {1} on {3}. Protocol: {4} Headers: {2}", args.Method, args.EndPoint, headerText, localEndPointString, protocol);
2016-02-17 21:40:17 +00:00
2016-02-17 04:44:31 +00:00
return true;
}
}
string serverId;
if (args.Headers.TryGetValue("X-EMBY-SERVERID", out serverId))
{
if (string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase))
{
//var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
//var headerText = string.Join(",", headerTexts.ToArray());
//var protocol = isMulticast ? "Multicast" : "Unicast";
//var localEndPointString = args.LocalEndPoint == null ? "null" : args.LocalEndPoint.ToString();
//_logger.Debug("IGNORING {0} message received from {1} on {3}. Protocol: {4} Headers: {2}", args.Method, args.EndPoint, headerText, localEndPointString, protocol);
return true;
}
}
2016-02-17 21:40:17 +00:00
2016-02-17 04:44:31 +00:00
return false;
}
2014-04-25 17:30:41 +00:00
public IEnumerable<UpnpDevice> RegisteredDevices
2014-03-24 12:47:39 +00:00
{
get
{
2015-12-08 16:10:27 +00:00
var devices = _devices.Values.ToList();
return devices.SelectMany(i => i).ToList();
2014-03-24 12:47:39 +00:00
}
}
2014-04-27 03:42:05 +00:00
2014-04-25 17:30:41 +00:00
public void Start()
2014-03-24 12:47:39 +00:00
{
DisposeSocket();
StopAliveNotifier();
2014-04-10 15:06:54 +00:00
RestartSocketListener();
2014-04-28 15:05:28 +00:00
ReloadAliveNotifier();
2016-02-17 04:44:31 +00:00
CreateUnicastClient();
2016-02-13 19:41:19 +00:00
SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
}
void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume)
{
Start();
}
2014-03-24 12:47:39 +00:00
}
public void SendSearchMessage(EndPoint localIp)
2014-06-22 05:52:31 +00:00
{
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
values["HOST"] = "239.255.255.250:1900";
values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
2016-02-17 04:44:31 +00:00
values["X-EMBY-SERVERID"] = _appHost.SystemId;
2014-07-30 03:31:35 +00:00
2014-06-22 05:52:31 +00:00
values["MAN"] = "\"ssdp:discover\"";
2014-07-30 03:31:35 +00:00
// Search target
values["ST"] = "ssdp:all";
// Seconds to delay response
values["MX"] = "3";
2014-06-22 05:52:31 +00:00
2016-02-13 19:41:19 +00:00
var header = "M-SEARCH * HTTP/1.1";
var msg = new SsdpMessageBuilder().BuildMessage(header, values);
2015-04-26 03:25:07 +00:00
// UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
2016-02-13 20:07:31 +00:00
SendDatagram(msg, _ssdpEndp, localIp, true);
2016-02-13 19:41:19 +00:00
2016-02-17 04:44:31 +00:00
SendUnicastRequest(msg);
2014-04-25 17:30:41 +00:00
}
2016-02-13 19:41:19 +00:00
public async void SendDatagram(string msg,
EndPoint endpoint,
EndPoint localAddress,
2015-10-18 01:18:29 +00:00
bool isBroadcast,
2016-02-13 20:07:31 +00:00
int sendCount = 3)
2014-04-25 17:30:41 +00:00
{
2016-02-12 04:33:14 +00:00
var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
2015-05-04 17:44:25 +00:00
2015-01-31 23:12:22 +00:00
for (var i = 0; i < sendCount; i++)
2014-04-25 17:30:41 +00:00
{
if (i > 0)
2015-01-31 23:12:22 +00:00
{
2016-02-14 02:27:13 +00:00
await Task.Delay(200).ConfigureAwait(false);
2015-01-31 23:12:22 +00:00
}
2014-04-25 17:30:41 +00:00
var dgram = new Datagram(endpoint, localAddress, _logger, msg, isBroadcast, enableDebugLogging);
dgram.Send();
2015-01-31 23:12:22 +00:00
}
2014-04-25 17:30:41 +00:00
}
/// <summary>
/// According to the spec: http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf
/// Device responses should be delayed a random duration between 0 and this many seconds to balance
/// load for the control point when it processes responses. In my testing kodi times out after mx
/// so we will generate from mx - 1
/// </summary>
/// <param name="headers">The mx headers</param>
/// <returns>A timepsan for the amount to delay before returning search result.</returns>
private TimeSpan GetSearchDelay(Dictionary<string, string> headers)
{
string mx;
headers.TryGetValue("mx", out mx);
int delaySeconds = 0;
if (!string.IsNullOrWhiteSpace(mx)
&& int.TryParse(mx, NumberStyles.Any, CultureInfo.InvariantCulture, out delaySeconds)
&& delaySeconds > 1)
{
delaySeconds = new Random().Next(delaySeconds - 1);
}
return TimeSpan.FromSeconds(delaySeconds);
}
private void RespondToSearch(EndPoint endpoint, string deviceType)
2014-04-25 17:30:41 +00:00
{
2016-02-12 04:33:14 +00:00
var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
2015-05-01 03:00:54 +00:00
2015-05-04 17:50:23 +00:00
var isLogged = false;
2014-04-25 17:30:41 +00:00
const string header = "HTTP/1.1 200 OK";
foreach (var d in RegisteredDevices)
{
if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
{
2015-05-04 17:50:23 +00:00
if (!isLogged)
{
if (enableDebugLogging)
{
_logger.Debug("Responding to search from {0} for {1}", endpoint, deviceType);
}
isLogged = true;
}
2014-04-25 17:30:41 +00:00
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
values["CACHE-CONTROL"] = "max-age = 600";
values["DATE"] = DateTime.Now.ToString("R");
values["EXT"] = "";
values["LOCATION"] = d.Descriptor.ToString();
values["SERVER"] = _serverSignature;
values["ST"] = d.Type;
values["USN"] = d.USN;
2016-02-13 19:41:19 +00:00
var msg = new SsdpMessageBuilder().BuildMessage(header, values);
2016-02-17 21:40:17 +00:00
var ipEndPoint = endpoint as IPEndPoint;
if (ipEndPoint != null)
{
SendUnicastRequest(msg, ipEndPoint);
}
else
{
SendDatagram(msg, endpoint, null, false, 2);
SendDatagram(msg, endpoint, new IPEndPoint(d.Address, 0), false, 2);
//SendDatagram(header, values, endpoint, null, true);
}
2014-04-25 17:30:41 +00:00
2015-05-01 03:00:54 +00:00
if (enableDebugLogging)
2014-06-04 03:34:36 +00:00
{
_logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
}
2014-04-25 17:30:41 +00:00
}
2014-04-27 03:42:05 +00:00
}
2014-04-25 17:30:41 +00:00
}
2015-05-10 04:29:04 +00:00
private void RestartSocketListener()
{
if (_isDisposed)
{
return;
}
try
{
2016-02-13 19:41:19 +00:00
_multicastSocket = CreateMulticastSocket();
2015-05-10 04:29:04 +00:00
_logger.Info("MultiCast socket created");
Receive();
}
catch (Exception ex)
{
_logger.ErrorException("Error creating MultiCast socket", ex);
//StartSocketRetryTimer();
}
}
2014-03-24 12:47:39 +00:00
private void Receive()
{
try
{
2014-04-25 17:30:41 +00:00
var buffer = new byte[1024];
EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
2016-02-13 19:41:19 +00:00
_multicastSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
2014-03-24 12:47:39 +00:00
}
catch (ObjectDisposedException)
{
2015-05-10 04:29:04 +00:00
if (!_isDisposed)
{
//StartSocketRetryTimer();
}
2014-03-24 12:47:39 +00:00
}
2014-11-07 00:16:16 +00:00
catch (Exception ex)
{
_logger.Debug("Error in BeginReceiveFrom", ex);
}
2014-03-24 12:47:39 +00:00
}
private void ReceiveCallback(IAsyncResult result)
{
2014-04-25 17:30:41 +00:00
if (_isDisposed)
{
return;
}
2014-03-24 12:47:39 +00:00
try
{
2014-04-25 17:30:41 +00:00
EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
2014-06-22 05:52:31 +00:00
2016-02-13 19:41:19 +00:00
var length = _multicastSocket.EndReceiveFrom(result, ref endpoint);
2014-06-22 05:52:31 +00:00
2014-04-25 17:30:41 +00:00
var received = (byte[])result.AsyncState;
2014-03-24 12:47:39 +00:00
2016-02-12 04:33:14 +00:00
var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
2015-05-01 03:00:54 +00:00
if (enableDebugLogging)
2014-06-22 05:52:31 +00:00
{
_logger.Debug(Encoding.ASCII.GetString(received));
}
var args = SsdpHelper.ParseSsdpResponse(received);
args.EndPoint = endpoint;
2014-03-24 12:47:39 +00:00
2016-02-17 04:44:31 +00:00
OnMessageReceived(args, true);
2014-03-24 12:47:39 +00:00
}
2015-05-10 04:29:04 +00:00
catch (ObjectDisposedException)
{
if (!_isDisposed)
{
//StartSocketRetryTimer();
}
}
2014-03-24 12:47:39 +00:00
catch (Exception ex)
{
_logger.ErrorException("Failed to read SSDP message", ex);
}
2016-02-13 19:41:19 +00:00
if (_multicastSocket != null)
2014-03-24 12:47:39 +00:00
{
Receive();
}
}
2014-04-25 17:30:41 +00:00
public void Dispose()
2014-03-24 12:47:39 +00:00
{
2014-06-29 17:35:05 +00:00
_config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
2014-04-28 15:05:28 +00:00
2014-04-25 17:30:41 +00:00
_isDisposed = true;
2014-04-10 15:06:54 +00:00
2016-02-13 19:41:19 +00:00
DisposeUnicastClient();
2014-04-25 17:30:41 +00:00
DisposeSocket();
StopAliveNotifier();
2014-03-24 12:47:39 +00:00
}
2014-04-25 17:30:41 +00:00
private void DisposeSocket()
2014-03-24 12:47:39 +00:00
{
2016-02-13 19:41:19 +00:00
if (_multicastSocket != null)
2014-03-24 12:47:39 +00:00
{
2016-02-13 19:41:19 +00:00
_multicastSocket.Close();
_multicastSocket.Dispose();
_multicastSocket = null;
2014-03-24 12:47:39 +00:00
}
2014-04-10 15:06:54 +00:00
}
2014-04-25 17:30:41 +00:00
private Socket CreateMulticastSocket()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
2014-04-10 15:06:54 +00:00
2014-04-25 17:30:41 +00:00
socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
return socket;
2014-03-24 12:47:39 +00:00
}
private void NotifyAll()
{
2016-02-12 04:33:14 +00:00
var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
2015-05-01 03:00:54 +00:00
if (enableDebugLogging)
2014-04-21 16:02:30 +00:00
{
_logger.Debug("Sending alive notifications");
}
2014-04-25 17:30:41 +00:00
foreach (var d in RegisteredDevices)
2014-03-24 12:47:39 +00:00
{
2016-02-13 20:07:31 +00:00
NotifyDevice(d, "alive", enableDebugLogging);
2014-03-24 12:47:39 +00:00
}
}
2016-02-13 20:07:31 +00:00
private void NotifyDevice(UpnpDevice dev, string type, bool logMessage)
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
const string header = "NOTIFY * HTTP/1.1";
2014-04-20 05:21:08 +00:00
2014-04-25 17:30:41 +00:00
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
2014-03-24 12:47:39 +00:00
2014-04-25 17:30:41 +00:00
// If needed later for non-server devices, these headers will need to be dynamic
values["HOST"] = "239.255.255.250:1900";
values["CACHE-CONTROL"] = "max-age = 600";
values["LOCATION"] = dev.Descriptor.ToString();
values["SERVER"] = _serverSignature;
values["NTS"] = "ssdp:" + type;
values["NT"] = dev.Type;
values["USN"] = dev.USN;
2016-02-17 04:44:31 +00:00
values["X-EMBY-SERVERID"] = _appHost.SystemId;
2014-04-10 15:06:54 +00:00
2015-05-01 03:00:54 +00:00
if (logMessage)
2014-04-21 16:02:30 +00:00
{
_logger.Debug("{0} said {1}", dev.USN, type);
}
2016-02-13 19:41:19 +00:00
var msg = new SsdpMessageBuilder().BuildMessage(header, values);
2016-02-13 20:07:31 +00:00
SendDatagram(msg, _ssdpEndp, new IPEndPoint(dev.Address, 0), true);
2016-02-17 21:24:01 +00:00
//SendUnicastRequest(msg, 1);
2014-03-24 12:47:39 +00:00
}
public void RegisterNotification(string uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
2014-03-24 12:47:39 +00:00
{
var list = _devices.GetOrAdd(uuid, new List<UpnpDevice>());
2014-03-24 12:47:39 +00:00
2014-04-25 17:30:41 +00:00
list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
2014-03-24 12:47:39 +00:00
NotifyAll();
2014-04-25 17:30:41 +00:00
_logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
2014-03-24 12:47:39 +00:00
}
public void UnregisterNotification(string uuid)
2014-03-24 12:47:39 +00:00
{
List<UpnpDevice> dl;
2014-04-25 17:30:41 +00:00
if (_devices.TryRemove(uuid, out dl))
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
foreach (var d in dl.ToList())
2014-04-10 15:06:54 +00:00
{
2016-02-13 20:07:31 +00:00
NotifyDevice(d, "byebye", true);
2014-04-10 15:06:54 +00:00
}
2014-04-25 17:30:41 +00:00
_logger.Debug("Unregistered mount {0}", uuid);
2014-04-10 15:06:54 +00:00
}
}
2016-02-13 19:41:19 +00:00
private void CreateUnicastClient()
{
if (_unicastClient == null)
{
try
{
_unicastClient = new UdpClient(_unicastPort);
}
catch (Exception ex)
{
_logger.ErrorException("Error creating unicast client", ex);
}
2016-02-17 04:44:31 +00:00
UnicastSetBeginReceive();
2016-02-13 19:41:19 +00:00
}
}
private void DisposeUnicastClient()
{
if (_unicastClient != null)
{
try
{
_unicastClient.Close();
}
catch (Exception ex)
{
_logger.ErrorException("Error closing unicast client", ex);
}
_unicastClient = null;
}
}
/// <summary>
/// Listen for Unicast SSDP Responses
/// </summary>
private void UnicastSetBeginReceive()
{
2016-02-17 04:44:31 +00:00
try
{
var ipRxEnd = new IPEndPoint(IPAddress.Any, _unicastPort);
var udpListener = new UdpState { EndPoint = ipRxEnd };
2016-02-13 19:41:19 +00:00
2016-02-17 04:44:31 +00:00
udpListener.UdpClient = _unicastClient;
_unicastClient.BeginReceive(UnicastReceiveCallback, udpListener);
}
catch (Exception ex)
{
_logger.ErrorException("Error in UnicastSetBeginReceive", ex);
}
2016-02-13 19:41:19 +00:00
}
/// <summary>
/// The UnicastReceiveCallback receives Http Responses
/// and Fired the SatIpDeviceFound Event for adding the SatIpDevice
/// </summary>
/// <param name="ar"></param>
private void UnicastReceiveCallback(IAsyncResult ar)
{
var udpClient = ((UdpState)(ar.AsyncState)).UdpClient;
var endpoint = ((UdpState)(ar.AsyncState)).EndPoint;
if (udpClient.Client != null)
{
2016-02-17 04:44:31 +00:00
try
{
var responseBytes = udpClient.EndReceive(ar, ref endpoint);
var args = SsdpHelper.ParseSsdpResponse(responseBytes);
2016-02-13 19:41:19 +00:00
2016-02-17 04:44:31 +00:00
args.EndPoint = endpoint;
2016-02-13 19:41:19 +00:00
2016-02-17 04:44:31 +00:00
OnMessageReceived(args, false);
2016-02-13 19:41:19 +00:00
2016-02-17 04:44:31 +00:00
UnicastSetBeginReceive();
}
catch (ObjectDisposedException)
{
2016-02-23 04:20:58 +00:00
}
catch (SocketException)
{
2016-02-17 21:40:17 +00:00
2016-02-17 04:44:31 +00:00
}
2016-02-13 19:41:19 +00:00
}
}
2016-02-17 21:40:17 +00:00
private void SendUnicastRequest(string request, int sendCount = 3)
2016-02-13 19:41:19 +00:00
{
if (_unicastClient == null)
{
return;
}
_logger.Debug("Sending unicast search request");
var ipSsdp = IPAddress.Parse(SSDPAddr);
var ipTxEnd = new IPEndPoint(ipSsdp, SSDPPort);
2016-02-17 21:40:17 +00:00
SendUnicastRequest(request, ipTxEnd, sendCount);
}
private async void SendUnicastRequest(string request, IPEndPoint toEndPoint, int sendCount = 3)
{
if (_unicastClient == null)
{
return;
}
_logger.Debug("Sending unicast search request");
byte[] req = Encoding.ASCII.GetBytes(request);
2016-02-17 04:44:31 +00:00
try
2016-02-13 19:41:19 +00:00
{
2016-02-17 21:24:01 +00:00
for (var i = 0; i < sendCount; i++)
2016-02-13 19:41:19 +00:00
{
2016-02-17 04:44:31 +00:00
if (i > 0)
{
await Task.Delay(50).ConfigureAwait(false);
}
2016-02-17 21:40:17 +00:00
_unicastClient.Send(req, req.Length, toEndPoint);
2016-02-13 19:41:19 +00:00
}
2016-02-17 04:44:31 +00:00
}
catch (Exception ex)
{
_logger.ErrorException("Error in SendUnicastRequest", ex);
2016-02-13 19:41:19 +00:00
}
}
2014-04-10 15:06:54 +00:00
private readonly object _notificationTimerSyncLock = new object();
2014-04-28 15:05:28 +00:00
private int _aliveNotifierIntervalMs;
private void ReloadAliveNotifier()
2014-04-10 15:06:54 +00:00
{
2015-05-01 03:00:54 +00:00
var config = _config.GetDlnaConfiguration();
if (!config.BlastAliveMessages)
2014-04-20 05:21:08 +00:00
{
StopAliveNotifier();
2014-04-20 05:21:08 +00:00
return;
}
2015-05-01 03:00:54 +00:00
var intervalMs = config.BlastAliveMessageIntervalSeconds * 1000;
2014-04-10 15:06:54 +00:00
2014-04-28 15:05:28 +00:00
if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
2014-04-10 15:06:54 +00:00
{
2014-04-28 15:05:28 +00:00
lock (_notificationTimerSyncLock)
2014-04-10 15:06:54 +00:00
{
2014-04-28 15:05:28 +00:00
if (_notificationTimer == null)
{
_logger.Debug("Starting alive notifier");
const int initialDelayMs = 3000;
_notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
}
else
{
_logger.Debug("Updating alive notifier");
_notificationTimer.Change(intervalMs, intervalMs);
}
_aliveNotifierIntervalMs = intervalMs;
2014-04-10 15:06:54 +00:00
}
}
}
private void StopAliveNotifier()
2014-04-10 15:06:54 +00:00
{
lock (_notificationTimerSyncLock)
{
if (_notificationTimer != null)
{
2014-04-28 15:05:28 +00:00
_logger.Debug("Stopping alive notifier");
2014-04-10 15:06:54 +00:00
_notificationTimer.Dispose();
_notificationTimer = null;
}
}
2014-03-24 12:47:39 +00:00
}
2016-02-13 19:41:19 +00:00
public class UdpState
{
public UdpClient UdpClient;
public IPEndPoint EndPoint;
}
2014-03-24 12:47:39 +00:00
}
}