SsdpHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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(IPEndPoint 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. IPEndPoint 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. IPEndPoint endpoint,
  106. IPEndPoint 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(IPEndPoint 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, null);
  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, (IPEndPoint)endpoint);
  220. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  221. {
  222. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  223. var headerText = string.Join(",", headerTexts.ToArray());
  224. _logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _socket.LocalEndPoint);
  225. }
  226. OnMessageReceived(args);
  227. }
  228. catch (Exception ex)
  229. {
  230. _logger.ErrorException("Failed to read SSDP message", ex);
  231. }
  232. if (_socket != null)
  233. {
  234. Receive();
  235. }
  236. }
  237. public void Dispose()
  238. {
  239. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  240. _isDisposed = true;
  241. while (_messageQueue.Count != 0)
  242. {
  243. _datagramPosted.WaitOne();
  244. }
  245. DisposeSocket();
  246. DisposeQueueTimer();
  247. DisposeNotificationTimer();
  248. _datagramPosted.Dispose();
  249. }
  250. private void DisposeSocket()
  251. {
  252. if (_socket != null)
  253. {
  254. _socket.Close();
  255. _socket.Dispose();
  256. _socket = null;
  257. }
  258. }
  259. private void DisposeQueueTimer()
  260. {
  261. lock (_queueTimerSyncLock)
  262. {
  263. if (_queueTimer != null)
  264. {
  265. _queueTimer.Dispose();
  266. _queueTimer = null;
  267. }
  268. }
  269. }
  270. private Socket CreateMulticastSocket()
  271. {
  272. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  273. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  274. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  275. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  276. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  277. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  278. return socket;
  279. }
  280. private void NotifyAll()
  281. {
  282. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  283. {
  284. _logger.Debug("Sending alive notifications");
  285. }
  286. foreach (var d in RegisteredDevices)
  287. {
  288. NotifyDevice(d, "alive");
  289. }
  290. }
  291. private void NotifyDevice(UpnpDevice dev, string type, int sendCount = 1)
  292. {
  293. const string header = "NOTIFY * HTTP/1.1";
  294. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  295. // If needed later for non-server devices, these headers will need to be dynamic
  296. values["HOST"] = "239.255.255.250:1900";
  297. values["CACHE-CONTROL"] = "max-age = 600";
  298. values["LOCATION"] = dev.Descriptor.ToString();
  299. values["SERVER"] = _serverSignature;
  300. values["NTS"] = "ssdp:" + type;
  301. values["NT"] = dev.Type;
  302. values["USN"] = dev.USN;
  303. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  304. {
  305. _logger.Debug("{0} said {1}", dev.USN, type);
  306. }
  307. SendDatagram(header, values, new IPEndPoint(dev.Address, 0), sendCount);
  308. }
  309. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  310. {
  311. List<UpnpDevice> list;
  312. lock (_devices)
  313. {
  314. if (!_devices.TryGetValue(uuid, out list))
  315. {
  316. _devices.TryAdd(uuid, list = new List<UpnpDevice>());
  317. }
  318. }
  319. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  320. NotifyAll();
  321. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  322. }
  323. public void UnregisterNotification(Guid uuid)
  324. {
  325. List<UpnpDevice> dl;
  326. if (_devices.TryRemove(uuid, out dl))
  327. {
  328. foreach (var d in dl.ToList())
  329. {
  330. NotifyDevice(d, "byebye", 2);
  331. }
  332. _logger.Debug("Unregistered mount {0}", uuid);
  333. }
  334. }
  335. private readonly object _notificationTimerSyncLock = new object();
  336. private int _aliveNotifierIntervalMs;
  337. private void ReloadAliveNotifier()
  338. {
  339. if (!_config.GetDlnaConfiguration().BlastAliveMessages)
  340. {
  341. DisposeNotificationTimer();
  342. return;
  343. }
  344. var intervalMs = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds * 1000;
  345. if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
  346. {
  347. lock (_notificationTimerSyncLock)
  348. {
  349. if (_notificationTimer == null)
  350. {
  351. _logger.Debug("Starting alive notifier");
  352. const int initialDelayMs = 3000;
  353. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  354. }
  355. else
  356. {
  357. _logger.Debug("Updating alive notifier");
  358. _notificationTimer.Change(intervalMs, intervalMs);
  359. }
  360. _aliveNotifierIntervalMs = intervalMs;
  361. }
  362. }
  363. }
  364. private void DisposeNotificationTimer()
  365. {
  366. lock (_notificationTimerSyncLock)
  367. {
  368. if (_notificationTimer != null)
  369. {
  370. _logger.Debug("Stopping alive notifier");
  371. _notificationTimer.Dispose();
  372. _notificationTimer = null;
  373. }
  374. }
  375. }
  376. }
  377. }