SsdpHandler.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 Emby/{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. var headers = args.Headers;
  77. string st;
  78. if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase) && headers.TryGetValue("st", out st))
  79. {
  80. TimeSpan delay = GetSearchDelay(headers);
  81. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  82. {
  83. _logger.Debug("Delaying search response by {0} seconds", delay.TotalSeconds);
  84. }
  85. await Task.Delay(delay).ConfigureAwait(false);
  86. RespondToSearch(args.EndPoint, st);
  87. }
  88. EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger);
  89. }
  90. public IEnumerable<UpnpDevice> RegisteredDevices
  91. {
  92. get
  93. {
  94. return _devices.Values.SelectMany(i => i).ToList();
  95. }
  96. }
  97. public void Start()
  98. {
  99. RestartSocketListener();
  100. ReloadAliveNotifier();
  101. }
  102. public void SendSearchMessage(EndPoint localIp)
  103. {
  104. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  105. values["HOST"] = "239.255.255.250:1900";
  106. values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
  107. values["MAN"] = "\"ssdp:discover\"";
  108. // Search target
  109. values["ST"] = "ssdp:all";
  110. // Seconds to delay response
  111. values["MX"] = "3";
  112. // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
  113. SendDatagram("M-SEARCH * HTTP/1.1", values, _ssdpEndp, localIp, false, 2);
  114. }
  115. public void SendDatagram(string header,
  116. Dictionary<string, string> values,
  117. EndPoint endpoint,
  118. EndPoint localAddress,
  119. bool ignoreBindFailure,
  120. int sendCount)
  121. {
  122. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  123. var queued = false;
  124. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  125. for (var i = 0; i < sendCount; i++)
  126. {
  127. var dgram = new Datagram(endpoint, localAddress, _logger, msg, ignoreBindFailure, enableDebugLogging);
  128. if (_messageQueue.Count == 0)
  129. {
  130. dgram.Send();
  131. }
  132. else
  133. {
  134. _messageQueue.Enqueue(dgram);
  135. queued = true;
  136. }
  137. }
  138. if (queued)
  139. {
  140. StartQueueTimer();
  141. }
  142. }
  143. /// <summary>
  144. /// According to the spec: http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf
  145. /// Device responses should be delayed a random duration between 0 and this many seconds to balance
  146. /// load for the control point when it processes responses. In my testing kodi times out after mx
  147. /// so we will generate from mx - 1
  148. /// </summary>
  149. /// <param name="headers">The mx headers</param>
  150. /// <returns>A timepsan for the amount to delay before returning search result.</returns>
  151. private TimeSpan GetSearchDelay(Dictionary<string, string> headers)
  152. {
  153. string mx;
  154. headers.TryGetValue("mx", out mx);
  155. int delaySeconds = 0;
  156. if (!string.IsNullOrWhiteSpace(mx)
  157. && int.TryParse(mx, NumberStyles.Any, CultureInfo.InvariantCulture, out delaySeconds)
  158. && delaySeconds > 1)
  159. {
  160. delaySeconds = new Random().Next(delaySeconds - 1);
  161. }
  162. return TimeSpan.FromSeconds(delaySeconds);
  163. }
  164. private void RespondToSearch(EndPoint endpoint, string deviceType)
  165. {
  166. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  167. var isLogged = false;
  168. const string header = "HTTP/1.1 200 OK";
  169. foreach (var d in RegisteredDevices)
  170. {
  171. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  172. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  173. {
  174. if (!isLogged)
  175. {
  176. if (enableDebugLogging)
  177. {
  178. _logger.Debug("Responding to search from {0} for {1}", endpoint, deviceType);
  179. }
  180. isLogged = true;
  181. }
  182. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  183. values["CACHE-CONTROL"] = "max-age = 600";
  184. values["DATE"] = DateTime.Now.ToString("R");
  185. values["EXT"] = "";
  186. values["LOCATION"] = d.Descriptor.ToString();
  187. values["SERVER"] = _serverSignature;
  188. values["ST"] = d.Type;
  189. values["USN"] = d.USN;
  190. SendDatagram(header, values, endpoint, null, true, 1);
  191. SendDatagram(header, values, endpoint, new IPEndPoint(d.Address, 0), true, 1);
  192. //SendDatagram(header, values, endpoint, null, true);
  193. if (enableDebugLogging)
  194. {
  195. _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
  196. }
  197. }
  198. }
  199. }
  200. private readonly object _queueTimerSyncLock = new object();
  201. private void StartQueueTimer()
  202. {
  203. lock (_queueTimerSyncLock)
  204. {
  205. if (_queueTimer == null)
  206. {
  207. _queueTimer = new Timer(QueueTimerCallback, null, 500, Timeout.Infinite);
  208. }
  209. else
  210. {
  211. _queueTimer.Change(500, Timeout.Infinite);
  212. }
  213. }
  214. }
  215. private void QueueTimerCallback(object state)
  216. {
  217. Datagram msg;
  218. while (_messageQueue.TryDequeue(out msg))
  219. {
  220. msg.Send();
  221. }
  222. _datagramPosted.Set();
  223. if (_messageQueue.Count > 0)
  224. {
  225. StartQueueTimer();
  226. }
  227. else
  228. {
  229. DisposeQueueTimer();
  230. }
  231. }
  232. private void RestartSocketListener()
  233. {
  234. if (_isDisposed)
  235. {
  236. StopSocketRetryTimer();
  237. return;
  238. }
  239. try
  240. {
  241. _socket = CreateMulticastSocket();
  242. _logger.Info("MultiCast socket created");
  243. StopSocketRetryTimer();
  244. Receive();
  245. }
  246. catch (Exception ex)
  247. {
  248. _logger.ErrorException("Error creating MultiCast socket", ex);
  249. //StartSocketRetryTimer();
  250. }
  251. }
  252. private Timer _socketRetryTimer;
  253. private readonly object _socketRetryLock = new object();
  254. private void StartSocketRetryTimer()
  255. {
  256. lock (_socketRetryLock)
  257. {
  258. if (_socketRetryTimer == null)
  259. {
  260. _socketRetryTimer = new Timer(s => RestartSocketListener(), null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
  261. }
  262. }
  263. }
  264. private void StopSocketRetryTimer()
  265. {
  266. lock (_socketRetryLock)
  267. {
  268. if (_socketRetryTimer != null)
  269. {
  270. _socketRetryTimer.Dispose();
  271. _socketRetryTimer = null;
  272. }
  273. }
  274. }
  275. private void Receive()
  276. {
  277. try
  278. {
  279. var buffer = new byte[1024];
  280. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  281. _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback,
  282. buffer);
  283. }
  284. catch (ObjectDisposedException)
  285. {
  286. if (!_isDisposed)
  287. {
  288. //StartSocketRetryTimer();
  289. }
  290. }
  291. catch (Exception ex)
  292. {
  293. _logger.Debug("Error in BeginReceiveFrom", ex);
  294. }
  295. }
  296. private void ReceiveCallback(IAsyncResult result)
  297. {
  298. if (_isDisposed)
  299. {
  300. return;
  301. }
  302. try
  303. {
  304. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  305. var length = _socket.EndReceiveFrom(result, ref endpoint);
  306. var received = (byte[])result.AsyncState;
  307. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  308. if (enableDebugLogging)
  309. {
  310. _logger.Debug(Encoding.ASCII.GetString(received));
  311. }
  312. var args = SsdpHelper.ParseSsdpResponse(received);
  313. args.EndPoint = endpoint;
  314. if (IsSelfNotification(args))
  315. {
  316. return;
  317. }
  318. if (enableDebugLogging)
  319. {
  320. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  321. var headerText = string.Join(",", headerTexts.ToArray());
  322. _logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _socket.LocalEndPoint);
  323. }
  324. OnMessageReceived(args);
  325. }
  326. catch (ObjectDisposedException)
  327. {
  328. if (!_isDisposed)
  329. {
  330. //StartSocketRetryTimer();
  331. }
  332. }
  333. catch (Exception ex)
  334. {
  335. _logger.ErrorException("Failed to read SSDP message", ex);
  336. }
  337. if (_socket != null)
  338. {
  339. Receive();
  340. }
  341. }
  342. internal bool IsSelfNotification(SsdpMessageEventArgs args)
  343. {
  344. // Avoid responding to self search messages
  345. //string serverId;
  346. //if (args.Headers.TryGetValue("X-EMBYSERVERID", out serverId) &&
  347. // string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase))
  348. //{
  349. // return true;
  350. //}
  351. string server;
  352. args.Headers.TryGetValue("SERVER", out server);
  353. if (string.Equals(server, _serverSignature, StringComparison.OrdinalIgnoreCase))
  354. {
  355. //return true;
  356. }
  357. return false;
  358. }
  359. public void Dispose()
  360. {
  361. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  362. _isDisposed = true;
  363. while (_messageQueue.Count != 0)
  364. {
  365. _datagramPosted.WaitOne();
  366. }
  367. DisposeSocket();
  368. DisposeQueueTimer();
  369. DisposeNotificationTimer();
  370. _datagramPosted.Dispose();
  371. }
  372. private void DisposeSocket()
  373. {
  374. if (_socket != null)
  375. {
  376. _socket.Close();
  377. _socket.Dispose();
  378. _socket = null;
  379. }
  380. }
  381. private void DisposeQueueTimer()
  382. {
  383. lock (_queueTimerSyncLock)
  384. {
  385. if (_queueTimer != null)
  386. {
  387. _queueTimer.Dispose();
  388. _queueTimer = null;
  389. }
  390. }
  391. }
  392. private Socket CreateMulticastSocket()
  393. {
  394. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  395. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  396. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  397. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  398. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  399. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  400. return socket;
  401. }
  402. private void NotifyAll()
  403. {
  404. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  405. if (enableDebugLogging)
  406. {
  407. _logger.Debug("Sending alive notifications");
  408. }
  409. foreach (var d in RegisteredDevices)
  410. {
  411. NotifyDevice(d, "alive", 1, enableDebugLogging);
  412. }
  413. }
  414. private void NotifyDevice(UpnpDevice dev, string type, int sendCount, bool logMessage)
  415. {
  416. const string header = "NOTIFY * HTTP/1.1";
  417. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  418. // If needed later for non-server devices, these headers will need to be dynamic
  419. values["HOST"] = "239.255.255.250:1900";
  420. values["CACHE-CONTROL"] = "max-age = 600";
  421. values["LOCATION"] = dev.Descriptor.ToString();
  422. values["SERVER"] = _serverSignature;
  423. values["NTS"] = "ssdp:" + type;
  424. values["NT"] = dev.Type;
  425. values["USN"] = dev.USN;
  426. if (logMessage)
  427. {
  428. _logger.Debug("{0} said {1}", dev.USN, type);
  429. }
  430. SendDatagram(header, values, _ssdpEndp, new IPEndPoint(dev.Address, 0), false, sendCount);
  431. }
  432. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  433. {
  434. List<UpnpDevice> list;
  435. lock (_devices)
  436. {
  437. if (!_devices.TryGetValue(uuid, out list))
  438. {
  439. _devices.TryAdd(uuid, list = new List<UpnpDevice>());
  440. }
  441. }
  442. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  443. NotifyAll();
  444. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  445. }
  446. public void UnregisterNotification(Guid uuid)
  447. {
  448. List<UpnpDevice> dl;
  449. if (_devices.TryRemove(uuid, out dl))
  450. {
  451. foreach (var d in dl.ToList())
  452. {
  453. NotifyDevice(d, "byebye", 2, true);
  454. }
  455. _logger.Debug("Unregistered mount {0}", uuid);
  456. }
  457. }
  458. private readonly object _notificationTimerSyncLock = new object();
  459. private int _aliveNotifierIntervalMs;
  460. private void ReloadAliveNotifier()
  461. {
  462. var config = _config.GetDlnaConfiguration();
  463. if (!config.BlastAliveMessages)
  464. {
  465. DisposeNotificationTimer();
  466. return;
  467. }
  468. var intervalMs = config.BlastAliveMessageIntervalSeconds * 1000;
  469. if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
  470. {
  471. lock (_notificationTimerSyncLock)
  472. {
  473. if (_notificationTimer == null)
  474. {
  475. _logger.Debug("Starting alive notifier");
  476. const int initialDelayMs = 3000;
  477. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  478. }
  479. else
  480. {
  481. _logger.Debug("Updating alive notifier");
  482. _notificationTimer.Change(intervalMs, intervalMs);
  483. }
  484. _aliveNotifierIntervalMs = intervalMs;
  485. }
  486. }
  487. }
  488. private void DisposeNotificationTimer()
  489. {
  490. lock (_notificationTimerSyncLock)
  491. {
  492. if (_notificationTimer != null)
  493. {
  494. _logger.Debug("Stopping alive notifier");
  495. _notificationTimer.Dispose();
  496. _notificationTimer = null;
  497. }
  498. }
  499. }
  500. }
  501. }