SsdpHandler.cs 13 KB

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