SsdpHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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.Generic;
  10. using System.Globalization;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Sockets;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using Microsoft.Win32;
  18. namespace MediaBrowser.Dlna.Ssdp
  19. {
  20. public class SsdpHandler : IDisposable, ISsdpHandler
  21. {
  22. private Socket _multicastSocket;
  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 _notificationTimer;
  31. private bool _isDisposed;
  32. private readonly Dictionary<string, List<UpnpDevice>> _devices = new Dictionary<string, List<UpnpDevice>>();
  33. private readonly IApplicationHost _appHost;
  34. private readonly int _unicastPort = 1901;
  35. private UdpClient _unicastClient;
  36. public SsdpHandler(ILogger logger, IServerConfigurationManager config, IApplicationHost appHost)
  37. {
  38. _logger = logger;
  39. _config = config;
  40. _appHost = appHost;
  41. _config.NamedConfigurationUpdated += _config_ConfigurationUpdated;
  42. _serverSignature = GenerateServerSignature();
  43. }
  44. private string GenerateServerSignature()
  45. {
  46. var os = Environment.OSVersion;
  47. var pstring = os.Platform.ToString();
  48. switch (os.Platform)
  49. {
  50. case PlatformID.Win32NT:
  51. case PlatformID.Win32S:
  52. case PlatformID.Win32Windows:
  53. pstring = "WIN";
  54. break;
  55. }
  56. return String.Format(
  57. "{0}{1}/{2}.{3} UPnP/1.0 DLNADOC/1.5 Emby/{4}",
  58. pstring,
  59. IntPtr.Size * 8,
  60. os.Version.Major,
  61. os.Version.Minor,
  62. _appHost.ApplicationVersion
  63. );
  64. }
  65. void _config_ConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  66. {
  67. if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
  68. {
  69. ReloadAliveNotifier();
  70. }
  71. }
  72. public IEnumerable<UpnpDevice> RegisteredDevices
  73. {
  74. get
  75. {
  76. lock (_devices)
  77. {
  78. var devices = _devices.ToList();
  79. return devices.SelectMany(i => i.Value).ToList();
  80. }
  81. }
  82. }
  83. public void Start()
  84. {
  85. DisposeSocket();
  86. StopAliveNotifier();
  87. RestartSocketListener();
  88. ReloadAliveNotifier();
  89. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  90. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  91. }
  92. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  93. {
  94. if (e.Mode == PowerModes.Resume)
  95. {
  96. Start();
  97. }
  98. }
  99. public async void SendDatagram(string msg,
  100. EndPoint endpoint,
  101. EndPoint localAddress,
  102. bool isBroadcast,
  103. int sendCount = 3)
  104. {
  105. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
  106. for (var i = 0; i < sendCount; i++)
  107. {
  108. if (i > 0)
  109. {
  110. await Task.Delay(500).ConfigureAwait(false);
  111. }
  112. var dgram = new Datagram(endpoint, localAddress, _logger, msg, isBroadcast, enableDebugLogging);
  113. dgram.Send();
  114. }
  115. }
  116. private void RestartSocketListener()
  117. {
  118. if (_isDisposed)
  119. {
  120. return;
  121. }
  122. try
  123. {
  124. _multicastSocket = CreateMulticastSocket();
  125. _logger.Info("MultiCast socket created");
  126. }
  127. catch (Exception ex)
  128. {
  129. _logger.ErrorException("Error creating MultiCast socket", ex);
  130. //StartSocketRetryTimer();
  131. }
  132. }
  133. public void Dispose()
  134. {
  135. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  136. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  137. _isDisposed = true;
  138. DisposeSocket();
  139. StopAliveNotifier();
  140. }
  141. private void DisposeSocket()
  142. {
  143. if (_multicastSocket != null)
  144. {
  145. _multicastSocket.Close();
  146. _multicastSocket.Dispose();
  147. _multicastSocket = null;
  148. }
  149. }
  150. private Socket CreateMulticastSocket()
  151. {
  152. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  153. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  154. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  155. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  156. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  157. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  158. return socket;
  159. }
  160. private void NotifyAll()
  161. {
  162. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
  163. if (enableDebugLogging)
  164. {
  165. _logger.Debug("Sending alive notifications");
  166. }
  167. foreach (var d in RegisteredDevices)
  168. {
  169. NotifyDevice(d, "alive", enableDebugLogging);
  170. }
  171. }
  172. private void NotifyDevice(UpnpDevice dev, string type, bool logMessage)
  173. {
  174. const string header = "NOTIFY * HTTP/1.1";
  175. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  176. // If needed later for non-server devices, these headers will need to be dynamic
  177. values["HOST"] = "239.255.255.250:1900";
  178. values["CACHE-CONTROL"] = "max-age = 600";
  179. values["LOCATION"] = dev.Descriptor.ToString();
  180. values["SERVER"] = _serverSignature;
  181. values["NTS"] = "ssdp:" + type;
  182. values["NT"] = dev.Type;
  183. values["USN"] = dev.USN;
  184. if (logMessage)
  185. {
  186. _logger.Debug("{0} said {1}", dev.USN, type);
  187. }
  188. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  189. SendDatagram(msg, _ssdpEndp, new IPEndPoint(dev.Address, 0), true, 2);
  190. //SendUnicastRequest(msg, 1);
  191. }
  192. public void RegisterNotification(string uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  193. {
  194. lock (_devices)
  195. {
  196. List<UpnpDevice> list;
  197. List<UpnpDevice> dl;
  198. if (_devices.TryGetValue(uuid, out dl))
  199. {
  200. list = dl;
  201. }
  202. else
  203. {
  204. list = new List<UpnpDevice>();
  205. _devices[uuid] = list;
  206. }
  207. list.AddRange(services.Select(i => new UpnpDevice(uuid, i, descriptionUri, address)));
  208. NotifyAll();
  209. _logger.Debug("Registered mount {0} at {1}", uuid, descriptionUri);
  210. }
  211. }
  212. public void UnregisterNotification(string uuid)
  213. {
  214. lock (_devices)
  215. {
  216. List<UpnpDevice> dl;
  217. if (_devices.TryGetValue(uuid, out dl))
  218. {
  219. _devices.Remove(uuid);
  220. foreach (var d in dl.ToList())
  221. {
  222. NotifyDevice(d, "byebye", true);
  223. }
  224. _logger.Debug("Unregistered mount {0}", uuid);
  225. }
  226. }
  227. }
  228. private readonly object _notificationTimerSyncLock = new object();
  229. private int _aliveNotifierIntervalMs;
  230. private void ReloadAliveNotifier()
  231. {
  232. var config = _config.GetDlnaConfiguration();
  233. if (!config.BlastAliveMessages)
  234. {
  235. StopAliveNotifier();
  236. return;
  237. }
  238. var intervalMs = config.BlastAliveMessageIntervalSeconds * 1000;
  239. if (_notificationTimer == null || _aliveNotifierIntervalMs != intervalMs)
  240. {
  241. lock (_notificationTimerSyncLock)
  242. {
  243. if (_notificationTimer == null)
  244. {
  245. _logger.Debug("Starting alive notifier");
  246. const int initialDelayMs = 3000;
  247. _notificationTimer = new Timer(state => NotifyAll(), null, initialDelayMs, intervalMs);
  248. }
  249. else
  250. {
  251. _logger.Debug("Updating alive notifier");
  252. _notificationTimer.Change(intervalMs, intervalMs);
  253. }
  254. _aliveNotifierIntervalMs = intervalMs;
  255. }
  256. }
  257. }
  258. private void StopAliveNotifier()
  259. {
  260. lock (_notificationTimerSyncLock)
  261. {
  262. if (_notificationTimer != null)
  263. {
  264. _logger.Debug("Stopping alive notifier");
  265. _notificationTimer.Dispose();
  266. _notificationTimer = null;
  267. }
  268. }
  269. }
  270. public class UdpState
  271. {
  272. public UdpClient UdpClient;
  273. public IPEndPoint EndPoint;
  274. }
  275. }
  276. }