activate unicast listener

This commit is contained in:
Luke Pulverenti 2016-02-16 23:44:31 -05:00
parent 1f004c978a
commit ffbe92e51e
2 changed files with 100 additions and 60 deletions

View File

@ -127,10 +127,12 @@ namespace MediaBrowser.Dlna.Ssdp
args.EndPoint = endPoint; args.EndPoint = endPoint;
args.LocalEndPoint = new IPEndPoint(localIp, 0); args.LocalEndPoint = new IPEndPoint(localIp, 0);
if (!_ssdpHandler.IsSelfNotification(args)) if (_ssdpHandler.IgnoreMessage(args, true))
{ {
TryCreateDevice(args); return;
} }
TryCreateDevice(args);
} }
} }

View File

@ -86,8 +86,25 @@ namespace MediaBrowser.Dlna.Ssdp
public event EventHandler<SsdpMessageEventArgs> MessageReceived; public event EventHandler<SsdpMessageEventArgs> MessageReceived;
private async void OnMessageReceived(SsdpMessageEventArgs args) private async void OnMessageReceived(SsdpMessageEventArgs args, bool isMulticast)
{ {
if (IgnoreMessage(args, isMulticast))
{
return;
}
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);
}
var headers = args.Headers; var headers = args.Headers;
string st; string st;
@ -108,6 +125,44 @@ namespace MediaBrowser.Dlna.Ssdp
EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger); EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger);
} }
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);
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;
}
}
return false;
}
public IEnumerable<UpnpDevice> RegisteredDevices public IEnumerable<UpnpDevice> RegisteredDevices
{ {
get get
@ -126,7 +181,7 @@ namespace MediaBrowser.Dlna.Ssdp
RestartSocketListener(); RestartSocketListener();
ReloadAliveNotifier(); ReloadAliveNotifier();
//CreateUnicastClient(); CreateUnicastClient();
SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged; SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
@ -146,6 +201,7 @@ namespace MediaBrowser.Dlna.Ssdp
values["HOST"] = "239.255.255.250:1900"; values["HOST"] = "239.255.255.250:1900";
values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2"; values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
values["X-EMBY-SERVERID"] = _appHost.SystemId;
values["MAN"] = "\"ssdp:discover\""; values["MAN"] = "\"ssdp:discover\"";
@ -162,7 +218,7 @@ namespace MediaBrowser.Dlna.Ssdp
// UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2) // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
SendDatagram(msg, _ssdpEndp, localIp, true); SendDatagram(msg, _ssdpEndp, localIp, true);
//SendUnicastRequest(msg); SendUnicastRequest(msg);
} }
public async void SendDatagram(string msg, public async void SendDatagram(string msg,
@ -324,20 +380,7 @@ namespace MediaBrowser.Dlna.Ssdp
var args = SsdpHelper.ParseSsdpResponse(received); var args = SsdpHelper.ParseSsdpResponse(received);
args.EndPoint = endpoint; args.EndPoint = endpoint;
if (IsSelfNotification(args)) OnMessageReceived(args, true);
{
return;
}
if (enableDebugLogging)
{
var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
var headerText = string.Join(",", headerTexts.ToArray());
_logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _multicastSocket.LocalEndPoint);
}
OnMessageReceived(args);
} }
catch (ObjectDisposedException) catch (ObjectDisposedException)
{ {
@ -357,26 +400,6 @@ namespace MediaBrowser.Dlna.Ssdp
} }
} }
internal bool IsSelfNotification(SsdpMessageEventArgs args)
{
// Avoid responding to self search messages
//string serverId;
//if (args.Headers.TryGetValue("X-EMBYSERVERID", out serverId) &&
// string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase))
//{
// return true;
//}
string server;
args.Headers.TryGetValue("SERVER", out server);
if (string.Equals(server, _serverSignature, StringComparison.OrdinalIgnoreCase))
{
//return true;
}
return false;
}
public void Dispose() public void Dispose()
{ {
_config.NamedConfigurationUpdated -= _config_ConfigurationUpdated; _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
@ -440,6 +463,7 @@ namespace MediaBrowser.Dlna.Ssdp
values["NTS"] = "ssdp:" + type; values["NTS"] = "ssdp:" + type;
values["NT"] = dev.Type; values["NT"] = dev.Type;
values["USN"] = dev.USN; values["USN"] = dev.USN;
values["X-EMBY-SERVERID"] = _appHost.SystemId;
if (logMessage) if (logMessage)
{ {
@ -489,15 +513,8 @@ namespace MediaBrowser.Dlna.Ssdp
_logger.ErrorException("Error creating unicast client", ex); _logger.ErrorException("Error creating unicast client", ex);
} }
try
{
UnicastSetBeginReceive(); UnicastSetBeginReceive();
} }
catch (Exception ex)
{
_logger.ErrorException("Error in UnicastSetBeginReceive", ex);
}
}
} }
private void DisposeUnicastClient() private void DisposeUnicastClient()
@ -521,6 +538,8 @@ namespace MediaBrowser.Dlna.Ssdp
/// Listen for Unicast SSDP Responses /// Listen for Unicast SSDP Responses
/// </summary> /// </summary>
private void UnicastSetBeginReceive() private void UnicastSetBeginReceive()
{
try
{ {
var ipRxEnd = new IPEndPoint(IPAddress.Any, _unicastPort); var ipRxEnd = new IPEndPoint(IPAddress.Any, _unicastPort);
var udpListener = new UdpState { EndPoint = ipRxEnd }; var udpListener = new UdpState { EndPoint = ipRxEnd };
@ -528,6 +547,11 @@ namespace MediaBrowser.Dlna.Ssdp
udpListener.UdpClient = _unicastClient; udpListener.UdpClient = _unicastClient;
_unicastClient.BeginReceive(UnicastReceiveCallback, udpListener); _unicastClient.BeginReceive(UnicastReceiveCallback, udpListener);
} }
catch (Exception ex)
{
_logger.ErrorException("Error in UnicastSetBeginReceive", ex);
}
}
/// <summary> /// <summary>
/// The UnicastReceiveCallback receives Http Responses /// The UnicastReceiveCallback receives Http Responses
@ -539,16 +563,23 @@ namespace MediaBrowser.Dlna.Ssdp
var udpClient = ((UdpState)(ar.AsyncState)).UdpClient; var udpClient = ((UdpState)(ar.AsyncState)).UdpClient;
var endpoint = ((UdpState)(ar.AsyncState)).EndPoint; var endpoint = ((UdpState)(ar.AsyncState)).EndPoint;
if (udpClient.Client != null) if (udpClient.Client != null)
{
try
{ {
var responseBytes = udpClient.EndReceive(ar, ref endpoint); var responseBytes = udpClient.EndReceive(ar, ref endpoint);
var args = SsdpHelper.ParseSsdpResponse(responseBytes); var args = SsdpHelper.ParseSsdpResponse(responseBytes);
args.EndPoint = endpoint; args.EndPoint = endpoint;
OnMessageReceived(args); OnMessageReceived(args, false);
UnicastSetBeginReceive(); UnicastSetBeginReceive();
} }
catch (ObjectDisposedException)
{
}
}
} }
private async void SendUnicastRequest(string request) private async void SendUnicastRequest(string request)
@ -564,6 +595,8 @@ namespace MediaBrowser.Dlna.Ssdp
var ipSsdp = IPAddress.Parse(SSDPAddr); var ipSsdp = IPAddress.Parse(SSDPAddr);
var ipTxEnd = new IPEndPoint(ipSsdp, SSDPPort); var ipTxEnd = new IPEndPoint(ipSsdp, SSDPPort);
try
{
for (var i = 0; i < 3; i++) for (var i = 0; i < 3; i++)
{ {
if (i > 0) if (i > 0)
@ -573,6 +606,11 @@ namespace MediaBrowser.Dlna.Ssdp
_unicastClient.Send(req, req.Length, ipTxEnd); _unicastClient.Send(req, req.Length, ipTxEnd);
} }
} }
catch (Exception ex)
{
_logger.ErrorException("Error in SendUnicastRequest", ex);
}
}
private readonly object _notificationTimerSyncLock = new object(); private readonly object _notificationTimerSyncLock = new object();
private int _aliveNotifierIntervalMs; private int _aliveNotifierIntervalMs;