SsdpHandler.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 _notificationTimer;
  32. private bool _isDisposed;
  33. private readonly ConcurrentDictionary<Guid, List<UpnpDevice>> _devices = new ConcurrentDictionary<Guid, List<UpnpDevice>>();
  34. private readonly IApplicationHost _appHost;
  35. public SsdpHandler(ILogger logger, IServerConfigurationManager config, IApplicationHost appHost)
  36. {
  37. _logger = logger;
  38. _config = config;
  39. _appHost = appHost;
  40. _config.NamedConfigurationUpdated += _config_ConfigurationUpdated;
  41. _serverSignature = GenerateServerSignature();
  42. }
  43. private string GenerateServerSignature()
  44. {
  45. var os = Environment.OSVersion;
  46. var pstring = os.Platform.ToString();
  47. switch (os.Platform)
  48. {
  49. case PlatformID.Win32NT:
  50. case PlatformID.Win32S:
  51. case PlatformID.Win32Windows:
  52. pstring = "WIN";
  53. break;
  54. }
  55. return String.Format(
  56. "{0}{1}/{2}.{3} UPnP/1.0 DLNADOC/1.5 Emby/{4}",
  57. pstring,
  58. IntPtr.Size * 8,
  59. os.Version.Major,
  60. os.Version.Minor,
  61. _appHost.ApplicationVersion
  62. );
  63. }
  64. void _config_ConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  65. {
  66. if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
  67. {
  68. ReloadAliveNotifier();
  69. }
  70. }
  71. public event EventHandler<SsdpMessageEventArgs> MessageReceived;
  72. private async void OnMessageReceived(SsdpMessageEventArgs args)
  73. {
  74. var headers = args.Headers;
  75. string st;
  76. if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase) && headers.TryGetValue("st", out st))
  77. {
  78. TimeSpan delay = GetSearchDelay(headers);
  79. if (_config.GetDlnaConfiguration().EnableDebugLogging)
  80. {
  81. _logger.Debug("Delaying search response by {0} seconds", delay.TotalSeconds);
  82. }
  83. await Task.Delay(delay).ConfigureAwait(false);
  84. RespondToSearch(args.EndPoint, st);
  85. }
  86. EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger);
  87. }
  88. public IEnumerable<UpnpDevice> RegisteredDevices
  89. {
  90. get
  91. {
  92. var devices = _devices.Values.ToList();
  93. return devices.SelectMany(i => i).ToList();
  94. }
  95. }
  96. public void Start()
  97. {
  98. DisposeSocket();
  99. StopAliveNotifier();
  100. RestartSocketListener();
  101. ReloadAliveNotifier();
  102. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  103. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  104. }
  105. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  106. {
  107. if (e.Mode == PowerModes.Resume)
  108. {
  109. Start();
  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 async 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 enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  134. for (var i = 0; i < sendCount; i++)
  135. {
  136. if (i > 0)
  137. {
  138. await Task.Delay(500).ConfigureAwait(false);
  139. }
  140. var dgram = new Datagram(endpoint, localAddress, _logger, msg, isBroadcast, enableDebugLogging);
  141. dgram.Send();
  142. }
  143. }
  144. /// <summary>
  145. /// According to the spec: http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf
  146. /// Device responses should be delayed a random duration between 0 and this many seconds to balance
  147. /// load for the control point when it processes responses. In my testing kodi times out after mx
  148. /// so we will generate from mx - 1
  149. /// </summary>
  150. /// <param name="headers">The mx headers</param>
  151. /// <returns>A timepsan for the amount to delay before returning search result.</returns>
  152. private TimeSpan GetSearchDelay(Dictionary<string, string> headers)
  153. {
  154. string mx;
  155. headers.TryGetValue("mx", out mx);
  156. int delaySeconds = 0;
  157. if (!string.IsNullOrWhiteSpace(mx)
  158. && int.TryParse(mx, NumberStyles.Any, CultureInfo.InvariantCulture, out delaySeconds)
  159. && delaySeconds > 1)
  160. {
  161. delaySeconds = new Random().Next(delaySeconds - 1);
  162. }
  163. return TimeSpan.FromSeconds(delaySeconds);
  164. }
  165. private void RespondToSearch(EndPoint endpoint, string deviceType)
  166. {
  167. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  168. var isLogged = false;
  169. const string header = "HTTP/1.1 200 OK";
  170. foreach (var d in RegisteredDevices)
  171. {
  172. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  173. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  174. {
  175. if (!isLogged)
  176. {
  177. if (enableDebugLogging)
  178. {
  179. _logger.Debug("Responding to search from {0} for {1}", endpoint, deviceType);
  180. }
  181. isLogged = true;
  182. }
  183. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  184. values["CACHE-CONTROL"] = "max-age = 600";
  185. values["DATE"] = DateTime.Now.ToString("R");
  186. values["EXT"] = "";
  187. values["LOCATION"] = d.Descriptor.ToString();
  188. values["SERVER"] = _serverSignature;
  189. values["ST"] = d.Type;
  190. values["USN"] = d.USN;
  191. SendDatagram(header, values, endpoint, null, false, 1);
  192. SendDatagram(header, values, endpoint, new IPEndPoint(d.Address, 0), false, 1);
  193. //SendDatagram(header, values, endpoint, null, true);
  194. if (enableDebugLogging)
  195. {
  196. _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
  197. }
  198. }
  199. }
  200. }
  201. private void RestartSocketListener()
  202. {
  203. if (_isDisposed)
  204. {
  205. return;
  206. }
  207. try
  208. {
  209. _socket = CreateMulticastSocket();
  210. _logger.Info("MultiCast socket created");
  211. Receive();
  212. }
  213. catch (Exception ex)
  214. {
  215. _logger.ErrorException("Error creating MultiCast socket", ex);
  216. //StartSocketRetryTimer();
  217. }
  218. }
  219. private void Receive()
  220. {
  221. try
  222. {
  223. var buffer = new byte[1024];
  224. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  225. _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback,
  226. buffer);
  227. }
  228. catch (ObjectDisposedException)
  229. {
  230. if (!_isDisposed)
  231. {
  232. //StartSocketRetryTimer();
  233. }
  234. }
  235. catch (Exception ex)
  236. {
  237. _logger.Debug("Error in BeginReceiveFrom", ex);
  238. }
  239. }
  240. private void ReceiveCallback(IAsyncResult result)
  241. {
  242. if (_isDisposed)
  243. {
  244. return;
  245. }
  246. try
  247. {
  248. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  249. var length = _socket.EndReceiveFrom(result, ref endpoint);
  250. var received = (byte[])result.AsyncState;
  251. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  252. if (enableDebugLogging)
  253. {
  254. _logger.Debug(Encoding.ASCII.GetString(received));
  255. }
  256. var args = SsdpHelper.ParseSsdpResponse(received);
  257. args.EndPoint = endpoint;
  258. if (IsSelfNotification(args))
  259. {
  260. return;
  261. }
  262. if (enableDebugLogging)
  263. {
  264. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  265. var headerText = string.Join(",", headerTexts.ToArray());
  266. _logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _socket.LocalEndPoint);
  267. }
  268. OnMessageReceived(args);
  269. }
  270. catch (ObjectDisposedException)
  271. {
  272. if (!_isDisposed)
  273. {
  274. //StartSocketRetryTimer();
  275. }
  276. }
  277. catch (Exception ex)
  278. {
  279. _logger.ErrorException("Failed to read SSDP message", ex);
  280. }
  281. if (_socket != null)
  282. {
  283. Receive();
  284. }
  285. }
  286. internal bool IsSelfNotification(SsdpMessageEventArgs args)
  287. {
  288. // Avoid responding to self search messages
  289. //string serverId;
  290. //if (args.Headers.TryGetValue("X-EMBYSERVERID", out serverId) &&
  291. // string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase))
  292. //{
  293. // return true;
  294. //}
  295. string server;
  296. args.Headers.TryGetValue("SERVER", out server);
  297. if (string.Equals(server, _serverSignature, StringComparison.OrdinalIgnoreCase))
  298. {
  299. //return true;
  300. }
  301. return false;
  302. }
  303. public void Dispose()
  304. {
  305. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  306. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  307. _isDisposed = true;
  308. DisposeSocket();
  309. StopAliveNotifier();
  310. }
  311. private void DisposeSocket()
  312. {
  313. if (_socket != null)
  314. {
  315. _socket.Close();
  316. _socket.Dispose();
  317. _socket = null;
  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. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLogging;
  333. if (enableDebugLogging)
  334. {
  335. _logger.Debug("Sending alive notifications");
  336. }
  337. foreach (var d in RegisteredDevices)
  338. {
  339. NotifyDevice(d, "alive", 1, enableDebugLogging);
  340. }
  341. }
  342. private void NotifyDevice(UpnpDevice dev, string type, int sendCount, bool logMessage)
  343. {
  344. const string header = "NOTIFY * HTTP/1.1";
  345. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  346. // If needed later for non-server devices, these headers will need to be dynamic
  347. values["HOST"] = "239.255.255.250:1900";
  348. values["CACHE-CONTROL"] = "max-age = 600";
  349. values["LOCATION"] = dev.Descriptor.ToString();
  350. values["SERVER"] = _serverSignature;
  351. values["NTS"] = "ssdp:" + type;
  352. values["NT"] = dev.Type;
  353. values["USN"] = dev.USN;
  354. if (logMessage)
  355. {
  356. _logger.Debug("{0} said {1}", dev.USN, type);
  357. }
  358. SendDatagram(header, values, _ssdpEndp, new IPEndPoint(dev.Address, 0), true, sendCount);
  359. }
  360. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  361. {
  362. var list = _devices.GetOrAdd(uuid, new List<UpnpDevice>());
  363. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  364. NotifyAll();
  365. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  366. }
  367. public void UnregisterNotification(Guid uuid)
  368. {
  369. List<UpnpDevice> dl;
  370. if (_devices.TryRemove(uuid, out dl))
  371. {
  372. foreach (var d in dl.ToList())
  373. {
  374. NotifyDevice(d, "byebye", 2, true);
  375. }
  376. _logger.Debug("Unregistered mount {0}", uuid);
  377. }
  378. }
  379. private readonly object _notificationTimerSyncLock = new object();
  380. private int _aliveNotifierIntervalMs;
  381. private void ReloadAliveNotifier()
  382. {
  383. var config = _config.GetDlnaConfiguration();
  384. if (!config.BlastAliveMessages)
  385. {
  386. StopAliveNotifier();
  387. return;
  388. }
  389. var intervalMs = config.BlastAliveMessageIntervalSeconds * 1000;
  390. if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
  391. {
  392. lock (_notificationTimerSyncLock)
  393. {
  394. if (_notificationTimer == null)
  395. {
  396. _logger.Debug("Starting alive notifier");
  397. const int initialDelayMs = 3000;
  398. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  399. }
  400. else
  401. {
  402. _logger.Debug("Updating alive notifier");
  403. _notificationTimer.Change(intervalMs, intervalMs);
  404. }
  405. _aliveNotifierIntervalMs = intervalMs;
  406. }
  407. }
  408. }
  409. private void StopAliveNotifier()
  410. {
  411. lock (_notificationTimerSyncLock)
  412. {
  413. if (_notificationTimer != null)
  414. {
  415. _logger.Debug("Stopping alive notifier");
  416. _notificationTimer.Dispose();
  417. _notificationTimer = null;
  418. }
  419. }
  420. }
  421. }
  422. }