SsdpHandler.cs 15 KB

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