SsdpHandler.cs 19 KB

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