SsdpHandler.cs 15 KB

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