SsdpHandler.cs 23 KB

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