SsdpHandler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. headers[parts[0]] = parts[1].Trim();
  95. }
  96. if (_config.Configuration.DlnaOptions.EnableDebugLogging)
  97. {
  98. _logger.Debug("{0} - Datagram method: {1}", endpoint, method);
  99. //_logger.Debug(headers);
  100. }
  101. if (string.Equals(method, "M-SEARCH", StringComparison.OrdinalIgnoreCase))
  102. {
  103. RespondToSearch(endpoint, headers["st"]);
  104. }
  105. }
  106. }
  107. catch (Exception ex)
  108. {
  109. _logger.ErrorException("Failed to read SSDP message", ex);
  110. }
  111. if (!_isDisposed)
  112. {
  113. Receive();
  114. }
  115. }
  116. private void RespondToSearch(IPEndPoint endpoint, string req)
  117. {
  118. if (req == "ssdp:all")
  119. {
  120. req = null;
  121. }
  122. if (_config.Configuration.DlnaOptions.EnableDebugLogging)
  123. {
  124. _logger.Debug("RespondToSearch");
  125. }
  126. foreach (var d in Devices)
  127. {
  128. if (!string.IsNullOrEmpty(req) && !string.Equals(req, d.Type, StringComparison.OrdinalIgnoreCase))
  129. {
  130. continue;
  131. }
  132. SendSearchResponse(endpoint, d);
  133. }
  134. }
  135. private void SendSearchResponse(IPEndPoint endpoint, UpnpDevice dev)
  136. {
  137. var headers = new Headers(true);
  138. headers.Add("CACHE-CONTROL", "max-age = 600");
  139. headers.Add("DATE", DateTime.Now.ToString("R"));
  140. headers.Add("EXT", "");
  141. headers.Add("LOCATION", dev.Descriptor.ToString());
  142. headers.Add("SERVER", _serverSignature);
  143. headers.Add("ST", dev.Type);
  144. headers.Add("USN", dev.USN);
  145. var msg = String.Format("HTTP/1.1 200 OK\r\n{0}\r\n", headers.HeaderBlock);
  146. SendDatagram(endpoint, dev.Address, msg, false);
  147. _logger.Info("{1} - Responded to a {0} request", dev.Type, endpoint);
  148. }
  149. private void SendDatagram(IPEndPoint endpoint, IPAddress localAddress, string msg, bool sticky)
  150. {
  151. if (_isDisposed)
  152. {
  153. return;
  154. }
  155. var dgram = new Datagram(endpoint, localAddress, _logger, msg, sticky);
  156. if (_messageQueue.Count == 0)
  157. {
  158. dgram.Send();
  159. }
  160. _messageQueue.Enqueue(dgram);
  161. StartQueueTimer();
  162. }
  163. private void QueueTimerCallback(object state)
  164. {
  165. while (_messageQueue.Count != 0)
  166. {
  167. Datagram msg;
  168. if (!_messageQueue.TryPeek(out msg))
  169. {
  170. continue;
  171. }
  172. if (msg != null && (!_isDisposed || msg.Sticky))
  173. {
  174. msg.Send();
  175. if (msg.SendCount > 2)
  176. {
  177. _messageQueue.TryDequeue(out msg);
  178. }
  179. break;
  180. }
  181. _messageQueue.TryDequeue(out msg);
  182. }
  183. _datagramPosted.Set();
  184. if (_messageQueue.Count > 0)
  185. {
  186. StartQueueTimer();
  187. }
  188. else
  189. {
  190. DisposeQueueTimer();
  191. }
  192. }
  193. private void NotifyAll()
  194. {
  195. _logger.Debug("Sending alive notifications");
  196. foreach (var d in Devices)
  197. {
  198. NotifyDevice(d, "alive", false);
  199. }
  200. }
  201. private void NotifyDevice(UpnpDevice dev, string type, bool sticky)
  202. {
  203. _logger.Debug("NotifyDevice");
  204. var headers = new Headers(true);
  205. headers.Add("HOST", "239.255.255.250:1900");
  206. headers.Add("CACHE-CONTROL", "max-age = 600");
  207. headers.Add("LOCATION", dev.Descriptor.ToString());
  208. headers.Add("SERVER", _serverSignature);
  209. headers.Add("NTS", "ssdp:" + type);
  210. headers.Add("NT", dev.Type);
  211. headers.Add("USN", dev.USN);
  212. var msg = String.Format("NOTIFY * HTTP/1.1\r\n{0}\r\n", headers.HeaderBlock);
  213. _logger.Debug("{0} said {1}", dev.USN, type);
  214. SendDatagram(_ssdpEndp, dev.Address, msg, sticky);
  215. }
  216. public void RegisterNotification(Guid uuid, Uri descriptor, IPAddress address)
  217. {
  218. List<UpnpDevice> list;
  219. lock (_devices)
  220. {
  221. if (!_devices.TryGetValue(uuid, out list))
  222. {
  223. _devices.Add(uuid, list = new List<UpnpDevice>());
  224. }
  225. }
  226. foreach (var t in new[]
  227. {
  228. "upnp:rootdevice",
  229. "urn:schemas-upnp-org:device:MediaServer:1",
  230. "urn:schemas-upnp-org:service:ContentDirectory:1",
  231. "uuid:" + uuid
  232. })
  233. {
  234. list.Add(new UpnpDevice(uuid, t, descriptor, address));
  235. }
  236. NotifyAll();
  237. _logger.Debug("Registered mount {0} at {1}", uuid, descriptor);
  238. }
  239. private void UnregisterNotification(Guid uuid)
  240. {
  241. List<UpnpDevice> dl;
  242. lock (_devices)
  243. {
  244. if (!_devices.TryGetValue(uuid, out dl))
  245. {
  246. return;
  247. }
  248. _devices.Remove(uuid);
  249. }
  250. foreach (var d in dl)
  251. {
  252. NotifyDevice(d, "byebye", true);
  253. }
  254. _logger.Debug("Unregistered mount {0}", uuid);
  255. }
  256. public void Dispose()
  257. {
  258. _isDisposed = true;
  259. while (_messageQueue.Count != 0)
  260. {
  261. _datagramPosted.WaitOne();
  262. }
  263. _udpClient.DropMulticastGroup(_ssdpIp);
  264. _udpClient.Close();
  265. DisposeNotificationTimer();
  266. DisposeQueueTimer();
  267. _datagramPosted.Dispose();
  268. }
  269. private readonly object _queueTimerSyncLock = new object();
  270. private void StartQueueTimer()
  271. {
  272. lock (_queueTimerSyncLock)
  273. {
  274. if (_queueTimer == null)
  275. {
  276. _queueTimer = new Timer(QueueTimerCallback, null, 1000, Timeout.Infinite);
  277. }
  278. else
  279. {
  280. _queueTimer.Change(1000, Timeout.Infinite);
  281. }
  282. }
  283. }
  284. private void DisposeQueueTimer()
  285. {
  286. lock (_queueTimerSyncLock)
  287. {
  288. if (_queueTimer != null)
  289. {
  290. _queueTimer.Dispose();
  291. _queueTimer = null;
  292. }
  293. }
  294. }
  295. private readonly object _notificationTimerSyncLock = new object();
  296. private void StartNotificationTimer()
  297. {
  298. const int intervalMs = 60000;
  299. lock (_notificationTimerSyncLock)
  300. {
  301. if (_notificationTimer == null)
  302. {
  303. _notificationTimer = new Timer(state => NotifyAll(), null, intervalMs, intervalMs);
  304. }
  305. else
  306. {
  307. _notificationTimer.Change(intervalMs, intervalMs);
  308. }
  309. }
  310. }
  311. private void DisposeNotificationTimer()
  312. {
  313. lock (_notificationTimerSyncLock)
  314. {
  315. if (_notificationTimer != null)
  316. {
  317. _notificationTimer.Dispose();
  318. _notificationTimer = null;
  319. }
  320. }
  321. }
  322. }
  323. }