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

428 lines
14 KiB
C#
Raw Normal View History

2014-03-24 12:47:39 +00:00
using MediaBrowser.Controller.Configuration;
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;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
2014-04-10 15:06:54 +00:00
using System.Threading;
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
{
public class SsdpHandler : IDisposable
{
2014-04-25 17:30:41 +00:00
private Socket _socket;
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 _queueTimer;
private Timer _notificationTimer;
2014-04-25 17:30:41 +00:00
private readonly AutoResetEvent _datagramPosted = new AutoResetEvent(false);
private readonly ConcurrentQueue<Datagram> _messageQueue = new ConcurrentQueue<Datagram>();
2014-04-10 15:06:54 +00:00
2014-04-25 17:30:41 +00:00
private bool _isDisposed;
private readonly ConcurrentDictionary<Guid, List<UpnpDevice>> _devices = new ConcurrentDictionary<Guid, List<UpnpDevice>>();
2014-03-24 12:47:39 +00:00
public SsdpHandler(ILogger logger, IServerConfigurationManager config, string serverSignature)
{
_logger = logger;
_config = config;
_serverSignature = serverSignature;
2014-04-25 17:30:41 +00:00
}
public event EventHandler<SsdpMessageEventArgs> MessageReceived;
2014-03-24 12:47:39 +00:00
2014-04-25 17:30:41 +00:00
private void OnMessageReceived(SsdpMessageEventArgs args)
{
if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase))
{
RespondToSearch(args.EndPoint, args.Headers["st"]);
}
2014-03-24 12:47:39 +00:00
}
2014-04-25 17:30:41 +00:00
public IEnumerable<UpnpDevice> RegisteredDevices
2014-03-24 12:47:39 +00:00
{
get
{
2014-04-25 17:30:41 +00:00
return _devices.Values.SelectMany(i => i).ToList();
2014-03-24 12:47:39 +00:00
}
}
2014-04-25 17:30:41 +00:00
public void Start()
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
_socket = CreateMulticastSocket();
2014-03-24 12:47:39 +00:00
_logger.Info("SSDP service started");
Receive();
2014-04-10 15:06:54 +00:00
StartNotificationTimer();
2014-03-24 12:47:39 +00:00
}
2014-04-25 17:30:41 +00:00
public void SendDatagram(string header,
Dictionary<string, string> values,
IPAddress localAddress,
int sendCount = 1)
{
SendDatagram(header, values, _ssdpEndp, localAddress, sendCount);
}
public void SendDatagram(string header,
Dictionary<string, string> values,
IPEndPoint endpoint,
IPAddress localAddress,
int sendCount = 1)
{
var msg = new SsdpMessageBuilder().BuildMessage(header, values);
var dgram = new Datagram(endpoint, localAddress, _logger, msg, sendCount);
if (_messageQueue.Count == 0)
{
dgram.Send();
return;
}
_messageQueue.Enqueue(dgram);
StartQueueTimer();
}
public void SendDatagramFromDevices(string header,
Dictionary<string, string> values,
IPEndPoint endpoint,
string deviceType)
{
foreach (var d in RegisteredDevices)
{
if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
{
SendDatagram(header, values, endpoint, d.Address);
}
}
}
private void RespondToSearch(IPEndPoint endpoint, string deviceType)
{
if (_config.Configuration.DlnaOptions.EnableDebugLogging)
{
_logger.Debug("RespondToSearch");
}
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))
{
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;
SendDatagram(header, values, endpoint, d.Address);
_logger.Info("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
}
}
}
private readonly object _queueTimerSyncLock = new object();
private void StartQueueTimer()
{
lock (_queueTimerSyncLock)
{
if (_queueTimer == null)
{
_queueTimer = new Timer(QueueTimerCallback, null, 1000, Timeout.Infinite);
}
else
{
_queueTimer.Change(1000, Timeout.Infinite);
}
}
}
private void QueueTimerCallback(object state)
{
while (_messageQueue.Count != 0)
{
Datagram msg;
if (!_messageQueue.TryPeek(out msg))
{
continue;
}
if (msg != null && (!_isDisposed || msg.TotalSendCount > 1))
{
msg.Send();
if (msg.SendCount > msg.TotalSendCount)
{
_messageQueue.TryDequeue(out msg);
}
break;
}
_messageQueue.TryDequeue(out msg);
}
_datagramPosted.Set();
if (_messageQueue.Count > 0)
{
StartQueueTimer();
}
else
{
DisposeQueueTimer();
}
}
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);
_socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
2014-03-24 12:47:39 +00:00
}
catch (ObjectDisposedException)
{
}
}
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);
var receivedCount = _socket.EndReceiveFrom(result, ref endpoint);
var received = (byte[])result.AsyncState;
2014-03-24 12:47:39 +00:00
if (_config.Configuration.DlnaOptions.EnableDebugLogging)
{
_logger.Debug("{0} - SSDP Received a datagram", endpoint);
}
using (var reader = new StreamReader(new MemoryStream(received), Encoding.ASCII))
{
var proto = (reader.ReadLine() ?? string.Empty).Trim();
var method = proto.Split(new[] { ' ' }, 2)[0];
2014-04-25 17:30:41 +00:00
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
2014-03-24 12:47:39 +00:00
for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
line = line.Trim();
if (string.IsNullOrEmpty(line))
{
break;
}
2014-03-25 05:25:03 +00:00
var parts = line.Split(new[] { ':' }, 2);
2014-04-20 05:21:08 +00:00
if (parts.Length >= 2)
{
headers[parts[0]] = parts[1].Trim();
}
2014-03-24 12:47:39 +00:00
}
if (_config.Configuration.DlnaOptions.EnableDebugLogging)
{
_logger.Debug("{0} - Datagram method: {1}", endpoint, method);
}
2014-04-25 17:30:41 +00:00
OnMessageReceived(new SsdpMessageEventArgs
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
Method = method,
Headers = headers,
EndPoint = (IPEndPoint)endpoint
});
2014-03-24 12:47:39 +00:00
}
}
catch (Exception ex)
{
_logger.ErrorException("Failed to read SSDP message", ex);
}
2014-04-25 17:30:41 +00:00
if (_socket != 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-04-25 17:30:41 +00:00
_isDisposed = true;
while (_messageQueue.Count != 0)
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
_datagramPosted.WaitOne();
2014-03-24 12:47:39 +00:00
}
2014-04-10 15:06:54 +00:00
2014-04-25 17:30:41 +00:00
DisposeSocket();
DisposeQueueTimer();
DisposeNotificationTimer();
2014-04-10 15:06:54 +00:00
2014-04-25 17:30:41 +00:00
_datagramPosted.Dispose();
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
{
2014-04-25 17:30:41 +00:00
if (_socket != null)
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
_socket.Close();
_socket.Dispose();
_socket = 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 void DisposeQueueTimer()
2014-04-10 15:06:54 +00:00
{
2014-04-25 17:30:41 +00:00
lock (_queueTimerSyncLock)
2014-04-10 15:06:54 +00:00
{
2014-04-25 17:30:41 +00:00
if (_queueTimer != null)
2014-04-10 15:06:54 +00:00
{
2014-04-25 17:30:41 +00:00
_queueTimer.Dispose();
_queueTimer = null;
2014-04-10 15:06:54 +00:00
}
}
2014-04-25 17:30:41 +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()
{
2014-04-21 16:02:30 +00:00
if (_config.Configuration.DlnaOptions.EnableDebugLogging)
{
_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
{
2014-04-25 17:30:41 +00:00
NotifyDevice(d, "alive");
2014-03-24 12:47:39 +00:00
}
}
2014-04-25 17:30:41 +00:00
private void NotifyDevice(UpnpDevice dev, string type, int sendCount = 1)
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;
2014-04-10 15:06:54 +00:00
2014-04-21 16:02:30 +00:00
if (_config.Configuration.DlnaOptions.EnableDebugLogging)
{
_logger.Debug("{0} said {1}", dev.USN, type);
}
2014-04-25 17:30:41 +00:00
SendDatagram(header, values, dev.Address, sendCount);
2014-03-24 12:47:39 +00:00
}
2014-04-25 17:30:41 +00:00
public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
2014-03-24 12:47:39 +00:00
{
List<UpnpDevice> list;
lock (_devices)
{
2014-04-10 15:06:54 +00:00
if (!_devices.TryGetValue(uuid, out list))
2014-03-24 12:47:39 +00:00
{
2014-04-25 17:30:41 +00:00
_devices.TryAdd(uuid, list = 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
}
2014-04-25 17:30:41 +00:00
public void UnregisterNotification(Guid 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
{
2014-04-25 17:30:41 +00:00
NotifyDevice(d, "byebye", 2);
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
}
}
private readonly object _notificationTimerSyncLock = new object();
private void StartNotificationTimer()
{
2014-04-20 05:21:08 +00:00
if (!_config.Configuration.DlnaOptions.BlastAliveMessages)
{
return;
}
var intervalMs = _config.Configuration.DlnaOptions.BlastAliveMessageIntervalSeconds * 1000;
2014-04-10 15:06:54 +00:00
lock (_notificationTimerSyncLock)
{
if (_notificationTimer == null)
{
_notificationTimer = new Timer(state => NotifyAll(), null, intervalMs, intervalMs);
}
else
{
_notificationTimer.Change(intervalMs, intervalMs);
}
}
}
private void DisposeNotificationTimer()
{
lock (_notificationTimerSyncLock)
{
if (_notificationTimer != null)
{
_notificationTimer.Dispose();
_notificationTimer = null;
}
}
2014-03-24 12:47:39 +00:00
}
}
}