SsdpHandler.cs 20 KB

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