SsdpHandler.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  178. {
  179. _logger.Debug("RespondToSearch");
  180. }
  181. const string header = "HTTP/1.1 200 OK";
  182. foreach (var d in RegisteredDevices)
  183. {
  184. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  185. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  186. {
  187. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  188. values["CACHE-CONTROL"] = "max-age = 600";
  189. values["DATE"] = DateTime.Now.ToString("R");
  190. values["EXT"] = "";
  191. values["LOCATION"] = d.Descriptor.ToString();
  192. values["SERVER"] = _serverSignature;
  193. values["ST"] = d.Type;
  194. values["USN"] = d.USN;
  195. SendDatagram(header, values, endpoint, null, true, 1);
  196. SendDatagram(header, values, endpoint, new IPEndPoint(d.Address, 0), true, 1);
  197. //SendDatagram(header, values, endpoint, null, true);
  198. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  199. {
  200. _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
  201. }
  202. }
  203. }
  204. }
  205. private readonly object _queueTimerSyncLock = new object();
  206. private void StartQueueTimer()
  207. {
  208. lock (_queueTimerSyncLock)
  209. {
  210. if (_queueTimer == null)
  211. {
  212. _queueTimer = new Timer(QueueTimerCallback, null, 500, Timeout.Infinite);
  213. }
  214. else
  215. {
  216. _queueTimer.Change(500, Timeout.Infinite);
  217. }
  218. }
  219. }
  220. private void QueueTimerCallback(object state)
  221. {
  222. Datagram msg;
  223. while (_messageQueue.TryDequeue(out msg))
  224. {
  225. msg.Send();
  226. }
  227. _datagramPosted.Set();
  228. if (_messageQueue.Count > 0)
  229. {
  230. StartQueueTimer();
  231. }
  232. else
  233. {
  234. DisposeQueueTimer();
  235. }
  236. }
  237. private void Receive()
  238. {
  239. try
  240. {
  241. var buffer = new byte[1024];
  242. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  243. _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
  244. }
  245. catch (ObjectDisposedException)
  246. {
  247. }
  248. catch (Exception ex)
  249. {
  250. _logger.Debug("Error in BeginReceiveFrom", ex);
  251. }
  252. }
  253. private void ReceiveCallback(IAsyncResult result)
  254. {
  255. if (_isDisposed)
  256. {
  257. return;
  258. }
  259. try
  260. {
  261. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  262. var length = _socket.EndReceiveFrom(result, ref endpoint);
  263. var received = (byte[])result.AsyncState;
  264. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  265. {
  266. _logger.Debug(Encoding.ASCII.GetString(received));
  267. }
  268. var args = SsdpHelper.ParseSsdpResponse(received);
  269. args.EndPoint = endpoint;
  270. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  271. {
  272. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  273. var headerText = string.Join(",", headerTexts.ToArray());
  274. _logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _socket.LocalEndPoint);
  275. }
  276. OnMessageReceived(args);
  277. }
  278. catch (Exception ex)
  279. {
  280. _logger.ErrorException("Failed to read SSDP message", ex);
  281. }
  282. if (_socket != null)
  283. {
  284. Receive();
  285. }
  286. }
  287. public void Dispose()
  288. {
  289. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  290. _isDisposed = true;
  291. while (_messageQueue.Count != 0)
  292. {
  293. _datagramPosted.WaitOne();
  294. }
  295. DisposeSocket();
  296. DisposeQueueTimer();
  297. DisposeNotificationTimer();
  298. _datagramPosted.Dispose();
  299. }
  300. private void DisposeSocket()
  301. {
  302. if (_socket != null)
  303. {
  304. _socket.Close();
  305. _socket.Dispose();
  306. _socket = null;
  307. }
  308. }
  309. private void DisposeQueueTimer()
  310. {
  311. lock (_queueTimerSyncLock)
  312. {
  313. if (_queueTimer != null)
  314. {
  315. _queueTimer.Dispose();
  316. _queueTimer = null;
  317. }
  318. }
  319. }
  320. private Socket CreateMulticastSocket()
  321. {
  322. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  323. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  324. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  325. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  326. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  327. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  328. return socket;
  329. }
  330. private void NotifyAll()
  331. {
  332. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  333. {
  334. _logger.Debug("Sending alive notifications");
  335. }
  336. foreach (var d in RegisteredDevices)
  337. {
  338. NotifyDevice(d, "alive", 1);
  339. }
  340. }
  341. private void NotifyDevice(UpnpDevice dev, string type, int sendCount)
  342. {
  343. const string header = "NOTIFY * HTTP/1.1";
  344. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  345. // If needed later for non-server devices, these headers will need to be dynamic
  346. values["HOST"] = "239.255.255.250:1900";
  347. values["CACHE-CONTROL"] = "max-age = 600";
  348. values["LOCATION"] = dev.Descriptor.ToString();
  349. values["SERVER"] = _serverSignature;
  350. values["NTS"] = "ssdp:" + type;
  351. values["NT"] = dev.Type;
  352. values["USN"] = dev.USN;
  353. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  354. {
  355. _logger.Debug("{0} said {1}", dev.USN, type);
  356. }
  357. SendDatagram(header, values, new IPEndPoint(dev.Address, 0), sendCount);
  358. }
  359. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  360. {
  361. List<UpnpDevice> list;
  362. lock (_devices)
  363. {
  364. if (!_devices.TryGetValue(uuid, out list))
  365. {
  366. _devices.TryAdd(uuid, list = new List<UpnpDevice>());
  367. }
  368. }
  369. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  370. NotifyAll();
  371. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  372. }
  373. public void UnregisterNotification(Guid uuid)
  374. {
  375. List<UpnpDevice> dl;
  376. if (_devices.TryRemove(uuid, out dl))
  377. {
  378. foreach (var d in dl.ToList())
  379. {
  380. NotifyDevice(d, "byebye", 2);
  381. }
  382. _logger.Debug("Unregistered mount {0}", uuid);
  383. }
  384. }
  385. private readonly object _notificationTimerSyncLock = new object();
  386. private int _aliveNotifierIntervalMs;
  387. private void ReloadAliveNotifier()
  388. {
  389. if (!_config.GetDlnaConfiguration().BlastAliveMessages)
  390. {
  391. DisposeNotificationTimer();
  392. return;
  393. }
  394. var intervalMs = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds * 1000;
  395. if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
  396. {
  397. lock (_notificationTimerSyncLock)
  398. {
  399. if (_notificationTimer == null)
  400. {
  401. _logger.Debug("Starting alive notifier");
  402. const int initialDelayMs = 3000;
  403. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  404. }
  405. else
  406. {
  407. _logger.Debug("Updating alive notifier");
  408. _notificationTimer.Change(intervalMs, intervalMs);
  409. }
  410. _aliveNotifierIntervalMs = intervalMs;
  411. }
  412. }
  413. }
  414. private void DisposeNotificationTimer()
  415. {
  416. lock (_notificationTimerSyncLock)
  417. {
  418. if (_notificationTimer != null)
  419. {
  420. _logger.Debug("Stopping alive notifier");
  421. _notificationTimer.Dispose();
  422. _notificationTimer = null;
  423. }
  424. }
  425. }
  426. }
  427. }