SsdpHandler.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Dlna.Server;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Threading;
  12. namespace MediaBrowser.Dlna.Ssdp
  13. {
  14. public class SsdpHandler : IDisposable
  15. {
  16. private Socket _socket;
  17. private readonly ILogger _logger;
  18. private readonly IServerConfigurationManager _config;
  19. const string SSDPAddr = "239.255.255.250";
  20. const int SSDPPort = 1900;
  21. private readonly string _serverSignature;
  22. private readonly IPAddress _ssdpIp = IPAddress.Parse(SSDPAddr);
  23. private readonly IPEndPoint _ssdpEndp = new IPEndPoint(IPAddress.Parse(SSDPAddr), SSDPPort);
  24. private Timer _queueTimer;
  25. private Timer _notificationTimer;
  26. private readonly AutoResetEvent _datagramPosted = new AutoResetEvent(false);
  27. private readonly ConcurrentQueue<Datagram> _messageQueue = new ConcurrentQueue<Datagram>();
  28. private bool _isDisposed;
  29. private readonly ConcurrentDictionary<Guid, List<UpnpDevice>> _devices = new ConcurrentDictionary<Guid, List<UpnpDevice>>();
  30. public SsdpHandler(ILogger logger, IServerConfigurationManager config, string serverSignature)
  31. {
  32. _logger = logger;
  33. _config = config;
  34. _serverSignature = serverSignature;
  35. }
  36. public event EventHandler<SsdpMessageEventArgs> MessageReceived;
  37. private void OnMessageReceived(SsdpMessageEventArgs args)
  38. {
  39. if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase))
  40. {
  41. RespondToSearch(args.EndPoint, args.Headers["st"]);
  42. }
  43. EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger);
  44. }
  45. public IEnumerable<UpnpDevice> RegisteredDevices
  46. {
  47. get
  48. {
  49. return _devices.Values.SelectMany(i => i).ToList();
  50. }
  51. }
  52. public void Start()
  53. {
  54. _socket = CreateMulticastSocket();
  55. _logger.Info("SSDP service started");
  56. Receive();
  57. StartNotificationTimer();
  58. }
  59. public void SendDatagram(string header,
  60. Dictionary<string, string> values,
  61. IPAddress localAddress,
  62. int sendCount = 1)
  63. {
  64. SendDatagram(header, values, _ssdpEndp, localAddress, sendCount);
  65. }
  66. public void SendDatagram(string header,
  67. Dictionary<string, string> values,
  68. IPEndPoint endpoint,
  69. IPAddress localAddress,
  70. int sendCount = 1)
  71. {
  72. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  73. var dgram = new Datagram(endpoint, localAddress, _logger, msg, sendCount);
  74. if (_messageQueue.Count == 0)
  75. {
  76. dgram.Send();
  77. return;
  78. }
  79. _messageQueue.Enqueue(dgram);
  80. StartQueueTimer();
  81. }
  82. public void SendDatagramFromDevices(string header,
  83. Dictionary<string, string> values,
  84. IPEndPoint endpoint,
  85. string deviceType)
  86. {
  87. foreach (var d in RegisteredDevices)
  88. {
  89. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  90. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  91. {
  92. SendDatagram(header, values, endpoint, d.Address);
  93. }
  94. }
  95. }
  96. private void RespondToSearch(IPEndPoint endpoint, string deviceType)
  97. {
  98. if (_config.Configuration.DlnaOptions.EnableDebugLogging)
  99. {
  100. _logger.Debug("RespondToSearch");
  101. }
  102. const string header = "HTTP/1.1 200 OK";
  103. foreach (var d in RegisteredDevices)
  104. {
  105. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  106. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  107. {
  108. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  109. values["CACHE-CONTROL"] = "max-age = 600";
  110. values["DATE"] = DateTime.Now.ToString("R");
  111. values["EXT"] = "";
  112. values["LOCATION"] = d.Descriptor.ToString();
  113. values["SERVER"] = _serverSignature;
  114. values["ST"] = d.Type;
  115. values["USN"] = d.USN;
  116. SendDatagram(header, values, endpoint, d.Address);
  117. _logger.Info("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
  118. }
  119. }
  120. }
  121. private readonly object _queueTimerSyncLock = new object();
  122. private void StartQueueTimer()
  123. {
  124. lock (_queueTimerSyncLock)
  125. {
  126. if (_queueTimer == null)
  127. {
  128. _queueTimer = new Timer(QueueTimerCallback, null, 1000, Timeout.Infinite);
  129. }
  130. else
  131. {
  132. _queueTimer.Change(1000, Timeout.Infinite);
  133. }
  134. }
  135. }
  136. private void QueueTimerCallback(object state)
  137. {
  138. while (_messageQueue.Count != 0)
  139. {
  140. Datagram msg;
  141. if (!_messageQueue.TryPeek(out msg))
  142. {
  143. continue;
  144. }
  145. if (msg != null && (!_isDisposed || msg.TotalSendCount > 1))
  146. {
  147. msg.Send();
  148. if (msg.SendCount > msg.TotalSendCount)
  149. {
  150. _messageQueue.TryDequeue(out msg);
  151. }
  152. break;
  153. }
  154. _messageQueue.TryDequeue(out msg);
  155. }
  156. _datagramPosted.Set();
  157. if (_messageQueue.Count > 0)
  158. {
  159. StartQueueTimer();
  160. }
  161. else
  162. {
  163. DisposeQueueTimer();
  164. }
  165. }
  166. private void Receive()
  167. {
  168. try
  169. {
  170. var buffer = new byte[1024];
  171. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  172. _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
  173. }
  174. catch (ObjectDisposedException)
  175. {
  176. }
  177. }
  178. private void ReceiveCallback(IAsyncResult result)
  179. {
  180. if (_isDisposed)
  181. {
  182. return;
  183. }
  184. try
  185. {
  186. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  187. var receivedCount = _socket.EndReceiveFrom(result, ref endpoint);
  188. var received = (byte[])result.AsyncState;
  189. var args = SsdpHelper.ParseSsdpResponse(received, (IPEndPoint)endpoint);
  190. if (_config.Configuration.DlnaOptions.EnableDebugLogging)
  191. {
  192. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  193. var headerText = string.Join(",", headerTexts.ToArray());
  194. _logger.Debug("{0} message received from {1}. Headers: {2}", args.Method, args.EndPoint, headerText);
  195. }
  196. OnMessageReceived(args);
  197. }
  198. catch (Exception ex)
  199. {
  200. _logger.ErrorException("Failed to read SSDP message", ex);
  201. }
  202. if (_socket != null)
  203. {
  204. Receive();
  205. }
  206. }
  207. public void Dispose()
  208. {
  209. _isDisposed = true;
  210. while (_messageQueue.Count != 0)
  211. {
  212. _datagramPosted.WaitOne();
  213. }
  214. DisposeSocket();
  215. DisposeQueueTimer();
  216. DisposeNotificationTimer();
  217. _datagramPosted.Dispose();
  218. }
  219. private void DisposeSocket()
  220. {
  221. if (_socket != null)
  222. {
  223. _socket.Close();
  224. _socket.Dispose();
  225. _socket = null;
  226. }
  227. }
  228. private void DisposeQueueTimer()
  229. {
  230. lock (_queueTimerSyncLock)
  231. {
  232. if (_queueTimer != null)
  233. {
  234. _queueTimer.Dispose();
  235. _queueTimer = null;
  236. }
  237. }
  238. }
  239. private Socket CreateMulticastSocket()
  240. {
  241. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  242. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  243. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  244. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  245. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  246. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  247. return socket;
  248. }
  249. private void NotifyAll()
  250. {
  251. if (_config.Configuration.DlnaOptions.EnableDebugLogging)
  252. {
  253. _logger.Debug("Sending alive notifications");
  254. }
  255. foreach (var d in RegisteredDevices)
  256. {
  257. NotifyDevice(d, "alive");
  258. }
  259. }
  260. private void NotifyDevice(UpnpDevice dev, string type, int sendCount = 1)
  261. {
  262. const string header = "NOTIFY * HTTP/1.1";
  263. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  264. // If needed later for non-server devices, these headers will need to be dynamic
  265. values["HOST"] = "239.255.255.250:1900";
  266. values["CACHE-CONTROL"] = "max-age = 600";
  267. values["LOCATION"] = dev.Descriptor.ToString();
  268. values["SERVER"] = _serverSignature;
  269. values["NTS"] = "ssdp:" + type;
  270. values["NT"] = dev.Type;
  271. values["USN"] = dev.USN;
  272. if (_config.Configuration.DlnaOptions.EnableDebugLogging)
  273. {
  274. _logger.Debug("{0} said {1}", dev.USN, type);
  275. }
  276. SendDatagram(header, values, dev.Address, sendCount);
  277. }
  278. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  279. {
  280. List<UpnpDevice> list;
  281. lock (_devices)
  282. {
  283. if (!_devices.TryGetValue(uuid, out list))
  284. {
  285. _devices.TryAdd(uuid, list = new List<UpnpDevice>());
  286. }
  287. }
  288. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  289. NotifyAll();
  290. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  291. }
  292. public void UnregisterNotification(Guid uuid)
  293. {
  294. List<UpnpDevice> dl;
  295. if (_devices.TryRemove(uuid, out dl))
  296. {
  297. foreach (var d in dl.ToList())
  298. {
  299. NotifyDevice(d, "byebye", 2);
  300. }
  301. _logger.Debug("Unregistered mount {0}", uuid);
  302. }
  303. }
  304. private readonly object _notificationTimerSyncLock = new object();
  305. private void StartNotificationTimer()
  306. {
  307. if (!_config.Configuration.DlnaOptions.BlastAliveMessages)
  308. {
  309. return;
  310. }
  311. const int initialDelayMs = 3000;
  312. var intervalMs = _config.Configuration.DlnaOptions.BlastAliveMessageIntervalSeconds * 1000;
  313. lock (_notificationTimerSyncLock)
  314. {
  315. if (_notificationTimer == null)
  316. {
  317. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  318. }
  319. else
  320. {
  321. _notificationTimer.Change(initialDelayMs, intervalMs);
  322. }
  323. }
  324. }
  325. private void DisposeNotificationTimer()
  326. {
  327. lock (_notificationTimerSyncLock)
  328. {
  329. if (_notificationTimer != null)
  330. {
  331. _notificationTimer.Dispose();
  332. _notificationTimer = null;
  333. }
  334. }
  335. }
  336. }
  337. }