SsdpHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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, false, sendCount);
  102. }
  103. public void SendDatagram(string header,
  104. Dictionary<string, string> values,
  105. EndPoint endpoint,
  106. EndPoint localAddress,
  107. bool ignoreBindFailure,
  108. int sendCount = 1)
  109. {
  110. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  111. var dgram = new Datagram(endpoint, localAddress, _logger, msg, sendCount, ignoreBindFailure);
  112. if (_messageQueue.Count == 0)
  113. {
  114. dgram.Send();
  115. return;
  116. }
  117. _messageQueue.Enqueue(dgram);
  118. StartQueueTimer();
  119. }
  120. private void RespondToSearch(EndPoint endpoint, string deviceType)
  121. {
  122. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  123. {
  124. _logger.Debug("RespondToSearch");
  125. }
  126. const string header = "HTTP/1.1 200 OK";
  127. foreach (var d in RegisteredDevices)
  128. {
  129. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  130. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  131. {
  132. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  133. values["CACHE-CONTROL"] = "max-age = 600";
  134. values["DATE"] = DateTime.Now.ToString("R");
  135. values["EXT"] = "";
  136. values["LOCATION"] = d.Descriptor.ToString();
  137. values["SERVER"] = _serverSignature;
  138. values["ST"] = d.Type;
  139. values["USN"] = d.USN;
  140. SendDatagram(header, values, endpoint, null, true);
  141. SendDatagram(header, values, endpoint, new IPEndPoint(d.Address, 0), true);
  142. //SendDatagram(header, values, endpoint, null, true);
  143. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  144. {
  145. _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
  146. }
  147. }
  148. }
  149. }
  150. private readonly object _queueTimerSyncLock = new object();
  151. private void StartQueueTimer()
  152. {
  153. lock (_queueTimerSyncLock)
  154. {
  155. if (_queueTimer == null)
  156. {
  157. _queueTimer = new Timer(QueueTimerCallback, null, 1000, Timeout.Infinite);
  158. }
  159. else
  160. {
  161. _queueTimer.Change(1000, Timeout.Infinite);
  162. }
  163. }
  164. }
  165. private void QueueTimerCallback(object state)
  166. {
  167. while (_messageQueue.Count != 0)
  168. {
  169. Datagram msg;
  170. if (!_messageQueue.TryPeek(out msg))
  171. {
  172. continue;
  173. }
  174. if (msg != null && (!_isDisposed || msg.TotalSendCount > 1))
  175. {
  176. msg.Send();
  177. if (msg.SendCount > msg.TotalSendCount)
  178. {
  179. _messageQueue.TryDequeue(out msg);
  180. }
  181. break;
  182. }
  183. _messageQueue.TryDequeue(out msg);
  184. }
  185. _datagramPosted.Set();
  186. if (_messageQueue.Count > 0)
  187. {
  188. StartQueueTimer();
  189. }
  190. else
  191. {
  192. DisposeQueueTimer();
  193. }
  194. }
  195. private void Receive()
  196. {
  197. try
  198. {
  199. var buffer = new byte[1024];
  200. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  201. _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
  202. }
  203. catch (ObjectDisposedException)
  204. {
  205. }
  206. }
  207. private void ReceiveCallback(IAsyncResult result)
  208. {
  209. if (_isDisposed)
  210. {
  211. return;
  212. }
  213. try
  214. {
  215. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  216. var length = _socket.EndReceiveFrom(result, ref endpoint);
  217. var received = (byte[])result.AsyncState;
  218. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  219. {
  220. _logger.Debug(Encoding.ASCII.GetString(received));
  221. }
  222. var args = SsdpHelper.ParseSsdpResponse(received);
  223. args.EndPoint = endpoint;
  224. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  225. {
  226. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  227. var headerText = string.Join(",", headerTexts.ToArray());
  228. _logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _socket.LocalEndPoint);
  229. }
  230. OnMessageReceived(args);
  231. }
  232. catch (Exception ex)
  233. {
  234. _logger.ErrorException("Failed to read SSDP message", ex);
  235. }
  236. if (_socket != null)
  237. {
  238. Receive();
  239. }
  240. }
  241. public void Dispose()
  242. {
  243. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  244. _isDisposed = true;
  245. while (_messageQueue.Count != 0)
  246. {
  247. _datagramPosted.WaitOne();
  248. }
  249. DisposeSocket();
  250. DisposeQueueTimer();
  251. DisposeNotificationTimer();
  252. _datagramPosted.Dispose();
  253. }
  254. private void DisposeSocket()
  255. {
  256. if (_socket != null)
  257. {
  258. _socket.Close();
  259. _socket.Dispose();
  260. _socket = null;
  261. }
  262. }
  263. private void DisposeQueueTimer()
  264. {
  265. lock (_queueTimerSyncLock)
  266. {
  267. if (_queueTimer != null)
  268. {
  269. _queueTimer.Dispose();
  270. _queueTimer = null;
  271. }
  272. }
  273. }
  274. private Socket CreateMulticastSocket()
  275. {
  276. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  277. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  278. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  279. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  280. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  281. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  282. return socket;
  283. }
  284. private void NotifyAll()
  285. {
  286. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  287. {
  288. _logger.Debug("Sending alive notifications");
  289. }
  290. foreach (var d in RegisteredDevices)
  291. {
  292. NotifyDevice(d, "alive");
  293. }
  294. }
  295. private void NotifyDevice(UpnpDevice dev, string type, int sendCount = 1)
  296. {
  297. const string header = "NOTIFY * HTTP/1.1";
  298. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  299. // If needed later for non-server devices, these headers will need to be dynamic
  300. values["HOST"] = "239.255.255.250:1900";
  301. values["CACHE-CONTROL"] = "max-age = 600";
  302. values["LOCATION"] = dev.Descriptor.ToString();
  303. values["SERVER"] = _serverSignature;
  304. values["NTS"] = "ssdp:" + type;
  305. values["NT"] = dev.Type;
  306. values["USN"] = dev.USN;
  307. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  308. {
  309. _logger.Debug("{0} said {1}", dev.USN, type);
  310. }
  311. SendDatagram(header, values, new IPEndPoint(dev.Address, 0), sendCount);
  312. }
  313. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  314. {
  315. List<UpnpDevice> list;
  316. lock (_devices)
  317. {
  318. if (!_devices.TryGetValue(uuid, out list))
  319. {
  320. _devices.TryAdd(uuid, list = new List<UpnpDevice>());
  321. }
  322. }
  323. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  324. NotifyAll();
  325. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  326. }
  327. public void UnregisterNotification(Guid uuid)
  328. {
  329. List<UpnpDevice> dl;
  330. if (_devices.TryRemove(uuid, out dl))
  331. {
  332. foreach (var d in dl.ToList())
  333. {
  334. NotifyDevice(d, "byebye", 2);
  335. }
  336. _logger.Debug("Unregistered mount {0}", uuid);
  337. }
  338. }
  339. private readonly object _notificationTimerSyncLock = new object();
  340. private int _aliveNotifierIntervalMs;
  341. private void ReloadAliveNotifier()
  342. {
  343. if (!_config.GetDlnaConfiguration().BlastAliveMessages)
  344. {
  345. DisposeNotificationTimer();
  346. return;
  347. }
  348. var intervalMs = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds * 1000;
  349. if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
  350. {
  351. lock (_notificationTimerSyncLock)
  352. {
  353. if (_notificationTimer == null)
  354. {
  355. _logger.Debug("Starting alive notifier");
  356. const int initialDelayMs = 3000;
  357. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  358. }
  359. else
  360. {
  361. _logger.Debug("Updating alive notifier");
  362. _notificationTimer.Change(intervalMs, intervalMs);
  363. }
  364. _aliveNotifierIntervalMs = intervalMs;
  365. }
  366. }
  367. }
  368. private void DisposeNotificationTimer()
  369. {
  370. lock (_notificationTimerSyncLock)
  371. {
  372. if (_notificationTimer != null)
  373. {
  374. _logger.Debug("Stopping alive notifier");
  375. _notificationTimer.Dispose();
  376. _notificationTimer = null;
  377. }
  378. }
  379. }
  380. }
  381. }