SsdpHandler.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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 _multicastSocket;
  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. private readonly int _unicastPort = 1901;
  36. private UdpClient _unicastClient;
  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().EnableDebugLog)
  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. var devices = _devices.Values.ToList();
  95. return devices.SelectMany(i => i).ToList();
  96. }
  97. }
  98. public void Start()
  99. {
  100. DisposeSocket();
  101. StopAliveNotifier();
  102. RestartSocketListener();
  103. ReloadAliveNotifier();
  104. //CreateUnicastClient();
  105. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  106. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  107. }
  108. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  109. {
  110. if (e.Mode == PowerModes.Resume)
  111. {
  112. Start();
  113. }
  114. }
  115. public void SendSearchMessage(EndPoint localIp)
  116. {
  117. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  118. values["HOST"] = "239.255.255.250:1900";
  119. values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
  120. values["MAN"] = "\"ssdp:discover\"";
  121. // Search target
  122. values["ST"] = "ssdp:all";
  123. // Seconds to delay response
  124. values["MX"] = "3";
  125. var header = "M-SEARCH * HTTP/1.1";
  126. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  127. // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
  128. SendDatagram(msg, _ssdpEndp, localIp, true);
  129. //SendUnicastRequest(msg);
  130. }
  131. public async void SendDatagram(string msg,
  132. EndPoint endpoint,
  133. EndPoint localAddress,
  134. bool isBroadcast,
  135. int sendCount = 3)
  136. {
  137. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
  138. for (var i = 0; i < sendCount; i++)
  139. {
  140. if (i > 0)
  141. {
  142. await Task.Delay(500).ConfigureAwait(false);
  143. }
  144. var dgram = new Datagram(endpoint, localAddress, _logger, msg, isBroadcast, enableDebugLogging);
  145. dgram.Send();
  146. }
  147. }
  148. /// <summary>
  149. /// According to the spec: http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf
  150. /// Device responses should be delayed a random duration between 0 and this many seconds to balance
  151. /// load for the control point when it processes responses. In my testing kodi times out after mx
  152. /// so we will generate from mx - 1
  153. /// </summary>
  154. /// <param name="headers">The mx headers</param>
  155. /// <returns>A timepsan for the amount to delay before returning search result.</returns>
  156. private TimeSpan GetSearchDelay(Dictionary<string, string> headers)
  157. {
  158. string mx;
  159. headers.TryGetValue("mx", out mx);
  160. int delaySeconds = 0;
  161. if (!string.IsNullOrWhiteSpace(mx)
  162. && int.TryParse(mx, NumberStyles.Any, CultureInfo.InvariantCulture, out delaySeconds)
  163. && delaySeconds > 1)
  164. {
  165. delaySeconds = new Random().Next(delaySeconds - 1);
  166. }
  167. return TimeSpan.FromSeconds(delaySeconds);
  168. }
  169. private void RespondToSearch(EndPoint endpoint, string deviceType)
  170. {
  171. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
  172. var isLogged = false;
  173. const string header = "HTTP/1.1 200 OK";
  174. foreach (var d in RegisteredDevices)
  175. {
  176. if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
  177. string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
  178. {
  179. if (!isLogged)
  180. {
  181. if (enableDebugLogging)
  182. {
  183. _logger.Debug("Responding to search from {0} for {1}", endpoint, deviceType);
  184. }
  185. isLogged = true;
  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. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  196. SendDatagram(msg, endpoint, null, false, 1);
  197. SendDatagram(msg, endpoint, new IPEndPoint(d.Address, 0), false, 1);
  198. //SendDatagram(header, values, endpoint, null, true);
  199. if (enableDebugLogging)
  200. {
  201. _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
  202. }
  203. }
  204. }
  205. }
  206. private void RestartSocketListener()
  207. {
  208. if (_isDisposed)
  209. {
  210. return;
  211. }
  212. try
  213. {
  214. _multicastSocket = CreateMulticastSocket();
  215. _logger.Info("MultiCast socket created");
  216. Receive();
  217. }
  218. catch (Exception ex)
  219. {
  220. _logger.ErrorException("Error creating MultiCast socket", ex);
  221. //StartSocketRetryTimer();
  222. }
  223. }
  224. private void Receive()
  225. {
  226. try
  227. {
  228. var buffer = new byte[1024];
  229. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  230. _multicastSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
  231. }
  232. catch (ObjectDisposedException)
  233. {
  234. if (!_isDisposed)
  235. {
  236. //StartSocketRetryTimer();
  237. }
  238. }
  239. catch (Exception ex)
  240. {
  241. _logger.Debug("Error in BeginReceiveFrom", ex);
  242. }
  243. }
  244. private void ReceiveCallback(IAsyncResult result)
  245. {
  246. if (_isDisposed)
  247. {
  248. return;
  249. }
  250. try
  251. {
  252. EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
  253. var length = _multicastSocket.EndReceiveFrom(result, ref endpoint);
  254. var received = (byte[])result.AsyncState;
  255. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
  256. if (enableDebugLogging)
  257. {
  258. _logger.Debug(Encoding.ASCII.GetString(received));
  259. }
  260. var args = SsdpHelper.ParseSsdpResponse(received);
  261. args.EndPoint = endpoint;
  262. if (IsSelfNotification(args))
  263. {
  264. return;
  265. }
  266. if (enableDebugLogging)
  267. {
  268. var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
  269. var headerText = string.Join(",", headerTexts.ToArray());
  270. _logger.Debug("{0} message received from {1} on {3}. Headers: {2}", args.Method, args.EndPoint, headerText, _multicastSocket.LocalEndPoint);
  271. }
  272. OnMessageReceived(args);
  273. }
  274. catch (ObjectDisposedException)
  275. {
  276. if (!_isDisposed)
  277. {
  278. //StartSocketRetryTimer();
  279. }
  280. }
  281. catch (Exception ex)
  282. {
  283. _logger.ErrorException("Failed to read SSDP message", ex);
  284. }
  285. if (_multicastSocket != null)
  286. {
  287. Receive();
  288. }
  289. }
  290. internal bool IsSelfNotification(SsdpMessageEventArgs args)
  291. {
  292. // Avoid responding to self search messages
  293. //string serverId;
  294. //if (args.Headers.TryGetValue("X-EMBYSERVERID", out serverId) &&
  295. // string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase))
  296. //{
  297. // return true;
  298. //}
  299. string server;
  300. args.Headers.TryGetValue("SERVER", out server);
  301. if (string.Equals(server, _serverSignature, StringComparison.OrdinalIgnoreCase))
  302. {
  303. //return true;
  304. }
  305. return false;
  306. }
  307. public void Dispose()
  308. {
  309. _config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
  310. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  311. _isDisposed = true;
  312. DisposeUnicastClient();
  313. DisposeSocket();
  314. StopAliveNotifier();
  315. }
  316. private void DisposeSocket()
  317. {
  318. if (_multicastSocket != null)
  319. {
  320. _multicastSocket.Close();
  321. _multicastSocket.Dispose();
  322. _multicastSocket = null;
  323. }
  324. }
  325. private Socket CreateMulticastSocket()
  326. {
  327. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  328. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  329. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  330. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  331. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_ssdpIp, 0));
  332. socket.Bind(new IPEndPoint(IPAddress.Any, SSDPPort));
  333. return socket;
  334. }
  335. private void NotifyAll()
  336. {
  337. var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
  338. if (enableDebugLogging)
  339. {
  340. _logger.Debug("Sending alive notifications");
  341. }
  342. foreach (var d in RegisteredDevices)
  343. {
  344. NotifyDevice(d, "alive", enableDebugLogging);
  345. }
  346. }
  347. private void NotifyDevice(UpnpDevice dev, string type, bool logMessage)
  348. {
  349. const string header = "NOTIFY * HTTP/1.1";
  350. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  351. // If needed later for non-server devices, these headers will need to be dynamic
  352. values["HOST"] = "239.255.255.250:1900";
  353. values["CACHE-CONTROL"] = "max-age = 600";
  354. values["LOCATION"] = dev.Descriptor.ToString();
  355. values["SERVER"] = _serverSignature;
  356. values["NTS"] = "ssdp:" + type;
  357. values["NT"] = dev.Type;
  358. values["USN"] = dev.USN;
  359. if (logMessage)
  360. {
  361. _logger.Debug("{0} said {1}", dev.USN, type);
  362. }
  363. var msg = new SsdpMessageBuilder().BuildMessage(header, values);
  364. SendDatagram(msg, _ssdpEndp, new IPEndPoint(dev.Address, 0), true);
  365. }
  366. public void RegisterNotification(Guid uuid, Uri descriptionUri, IPAddress address, IEnumerable<string> services)
  367. {
  368. var list = _devices.GetOrAdd(uuid, new List<UpnpDevice>());
  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", true);
  381. }
  382. _logger.Debug("Unregistered mount {0}", uuid);
  383. }
  384. }
  385. private void CreateUnicastClient()
  386. {
  387. if (_unicastClient == null)
  388. {
  389. try
  390. {
  391. _unicastClient = new UdpClient(_unicastPort);
  392. }
  393. catch (Exception ex)
  394. {
  395. _logger.ErrorException("Error creating unicast client", ex);
  396. }
  397. try
  398. {
  399. UnicastSetBeginReceive();
  400. }
  401. catch (Exception ex)
  402. {
  403. _logger.ErrorException("Error in UnicastSetBeginReceive", ex);
  404. }
  405. }
  406. }
  407. private void DisposeUnicastClient()
  408. {
  409. if (_unicastClient != null)
  410. {
  411. try
  412. {
  413. _unicastClient.Close();
  414. }
  415. catch (Exception ex)
  416. {
  417. _logger.ErrorException("Error closing unicast client", ex);
  418. }
  419. _unicastClient = null;
  420. }
  421. }
  422. /// <summary>
  423. /// Listen for Unicast SSDP Responses
  424. /// </summary>
  425. private void UnicastSetBeginReceive()
  426. {
  427. var ipRxEnd = new IPEndPoint(IPAddress.Any, _unicastPort);
  428. var udpListener = new UdpState { EndPoint = ipRxEnd };
  429. udpListener.UdpClient = _unicastClient;
  430. _unicastClient.BeginReceive(UnicastReceiveCallback, udpListener);
  431. }
  432. /// <summary>
  433. /// The UnicastReceiveCallback receives Http Responses
  434. /// and Fired the SatIpDeviceFound Event for adding the SatIpDevice
  435. /// </summary>
  436. /// <param name="ar"></param>
  437. private void UnicastReceiveCallback(IAsyncResult ar)
  438. {
  439. var udpClient = ((UdpState)(ar.AsyncState)).UdpClient;
  440. var endpoint = ((UdpState)(ar.AsyncState)).EndPoint;
  441. if (udpClient.Client != null)
  442. {
  443. var responseBytes = udpClient.EndReceive(ar, ref endpoint);
  444. var args = SsdpHelper.ParseSsdpResponse(responseBytes);
  445. args.EndPoint = endpoint;
  446. OnMessageReceived(args);
  447. UnicastSetBeginReceive();
  448. }
  449. }
  450. private async void SendUnicastRequest(string request)
  451. {
  452. if (_unicastClient == null)
  453. {
  454. return;
  455. }
  456. _logger.Debug("Sending unicast search request");
  457. byte[] req = Encoding.ASCII.GetBytes(request);
  458. var ipSsdp = IPAddress.Parse(SSDPAddr);
  459. var ipTxEnd = new IPEndPoint(ipSsdp, SSDPPort);
  460. for (var i = 0; i < 3; i++)
  461. {
  462. if (i > 0)
  463. {
  464. await Task.Delay(50).ConfigureAwait(false);
  465. }
  466. _unicastClient.Send(req, req.Length, ipTxEnd);
  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. StopAliveNotifier();
  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 StopAliveNotifier()
  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. public class UdpState
  512. {
  513. public UdpClient UdpClient;
  514. public IPEndPoint EndPoint;
  515. }
  516. }
  517. }