SsdpHandler.cs 17 KB

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