SsdpHandler.cs 12 KB

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