SsdpDevicePublisherBase.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Model.Net;
  8. using MediaBrowser.Model.Threading;
  9. namespace Rssdp.Infrastructure
  10. {
  11. /// <summary>
  12. /// Provides the platform independent logic for publishing SSDP devices (notifications and search responses).
  13. /// </summary>
  14. public abstract class SsdpDevicePublisherBase : DisposableManagedObjectBase, ISsdpDevicePublisher
  15. {
  16. #region Fields & Constants
  17. private ISsdpCommunicationsServer _CommsServer;
  18. private string _OSName;
  19. private string _OSVersion;
  20. private bool _SupportPnpRootDevice;
  21. private IList<SsdpRootDevice> _Devices;
  22. private ReadOnlyEnumerable<SsdpRootDevice> _ReadOnlyDevices;
  23. private ITimer _RebroadcastAliveNotificationsTimer;
  24. private ITimerFactory _timerFactory;
  25. //private TimeSpan _RebroadcastAliveNotificationsTimeSpan;
  26. private DateTime _LastNotificationTime;
  27. private IDictionary<string, SearchRequest> _RecentSearchRequests;
  28. private IUpnpDeviceValidator _DeviceValidator;
  29. private Random _Random;
  30. //private TimeSpan _MinCacheTime;
  31. private const string ServerVersion = "1.0";
  32. #endregion
  33. #region Message Format Constants
  34. #endregion
  35. #region Constructors
  36. /// <summary>
  37. /// Default constructor.
  38. /// </summary>
  39. protected SsdpDevicePublisherBase(ISsdpCommunicationsServer communicationsServer, ITimerFactory timerFactory, string osName, string osVersion)
  40. {
  41. if (communicationsServer == null) throw new ArgumentNullException("communicationsServer");
  42. if (osName == null) throw new ArgumentNullException("osName");
  43. if (osName.Length == 0) throw new ArgumentException("osName cannot be an empty string.", "osName");
  44. if (osVersion == null) throw new ArgumentNullException("osVersion");
  45. if (osVersion.Length == 0) throw new ArgumentException("osVersion cannot be an empty string.", "osName");
  46. _SupportPnpRootDevice = true;
  47. _timerFactory = timerFactory;
  48. _Devices = new List<SsdpRootDevice>();
  49. _ReadOnlyDevices = new ReadOnlyEnumerable<SsdpRootDevice>(_Devices);
  50. _RecentSearchRequests = new Dictionary<string, SearchRequest>(StringComparer.OrdinalIgnoreCase);
  51. _Random = new Random();
  52. _DeviceValidator = new Upnp10DeviceValidator(); //Should probably inject this later, but for now we only support 1.0.
  53. _CommsServer = communicationsServer;
  54. _CommsServer.RequestReceived += CommsServer_RequestReceived;
  55. _OSName = osName;
  56. _OSVersion = osVersion;
  57. _CommsServer.BeginListeningForBroadcasts();
  58. }
  59. #endregion
  60. #region Public Methods
  61. /// <summary>
  62. /// Adds a device (and it's children) to the list of devices being published by this server, making them discoverable to SSDP clients.
  63. /// </summary>
  64. /// <remarks>
  65. /// <para>Adding a device causes "alive" notification messages to be sent immediately, or very soon after. Ensure your device/description service is running before adding the device object here.</para>
  66. /// <para>Devices added here with a non-zero cache life time will also have notifications broadcast periodically.</para>
  67. /// <para>This method ignores duplicate device adds (if the same device instance is added multiple times, the second and subsequent add calls do nothing).</para>
  68. /// </remarks>
  69. /// <param name="device">The <see cref="SsdpDevice"/> instance to add.</param>
  70. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
  71. /// <exception cref="System.InvalidOperationException">Thrown if the <paramref name="device"/> contains property values that are not acceptable to the UPnP 1.0 specification.</exception>
  72. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable supresses compiler warning, but task is not really needed.")]
  73. public void AddDevice(SsdpRootDevice device)
  74. {
  75. if (device == null) throw new ArgumentNullException("device");
  76. ThrowIfDisposed();
  77. _DeviceValidator.ThrowIfDeviceInvalid(device);
  78. TimeSpan minCacheTime = TimeSpan.Zero;
  79. bool wasAdded = false;
  80. lock (_Devices)
  81. {
  82. if (!_Devices.Contains(device))
  83. {
  84. _Devices.Add(device);
  85. wasAdded = true;
  86. minCacheTime = GetMinimumNonZeroCacheLifetime();
  87. }
  88. }
  89. if (wasAdded)
  90. {
  91. //_MinCacheTime = minCacheTime;
  92. ConnectToDeviceEvents(device);
  93. WriteTrace("Device Added", device);
  94. SetRebroadcastAliveNotificationsTimer(minCacheTime);
  95. SendAliveNotifications(device, true);
  96. }
  97. }
  98. /// <summary>
  99. /// Removes a device (and it's children) from the list of devices being published by this server, making them undiscoverable.
  100. /// </summary>
  101. /// <remarks>
  102. /// <para>Removing a device causes "byebye" notification messages to be sent immediately, advising clients of the device/service becoming unavailable. We recommend removing the device from the published list before shutting down the actual device/service, if possible.</para>
  103. /// <para>This method does nothing if the device was not found in the collection.</para>
  104. /// </remarks>
  105. /// <param name="device">The <see cref="SsdpDevice"/> instance to add.</param>
  106. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
  107. public async Task RemoveDevice(SsdpRootDevice device)
  108. {
  109. if (device == null) throw new ArgumentNullException("device");
  110. ThrowIfDisposed();
  111. bool wasRemoved = false;
  112. TimeSpan minCacheTime = TimeSpan.Zero;
  113. lock (_Devices)
  114. {
  115. if (_Devices.Contains(device))
  116. {
  117. _Devices.Remove(device);
  118. wasRemoved = true;
  119. minCacheTime = GetMinimumNonZeroCacheLifetime();
  120. }
  121. }
  122. if (wasRemoved)
  123. {
  124. //_MinCacheTime = minCacheTime;
  125. DisconnectFromDeviceEvents(device);
  126. WriteTrace("Device Removed", device);
  127. await SendByeByeNotifications(device, true).ConfigureAwait(false);
  128. SetRebroadcastAliveNotificationsTimer(minCacheTime);
  129. }
  130. }
  131. #endregion
  132. #region Public Properties
  133. /// <summary>
  134. /// Returns a read only list of devices being published by this instance.
  135. /// </summary>
  136. public IEnumerable<SsdpRootDevice> Devices
  137. {
  138. get
  139. {
  140. return _ReadOnlyDevices;
  141. }
  142. }
  143. /// <summary>
  144. /// If true (default) treats root devices as both upnp:rootdevice and pnp:rootdevice types.
  145. /// </summary>
  146. /// <remarks>
  147. /// <para>Enabling this option will cause devices to show up in Microsoft Windows Explorer's network screens (if discovery is enabled etc.). Windows Explorer appears to search only for pnp:rootdeivce and not upnp:rootdevice.</para>
  148. /// <para>If false, the system will only use upnp:rootdevice for notifiation broadcasts and and search responses, which is correct according to the UPnP/SSDP spec.</para>
  149. /// </remarks>
  150. public bool SupportPnpRootDevice
  151. {
  152. get { return _SupportPnpRootDevice; }
  153. set
  154. {
  155. _SupportPnpRootDevice = value;
  156. }
  157. }
  158. #endregion
  159. #region Overrides
  160. /// <summary>
  161. /// Stops listening for requests, stops sending periodic broadcasts, disposes all internal resources.
  162. /// </summary>
  163. /// <param name="disposing"></param>
  164. protected override void Dispose(bool disposing)
  165. {
  166. if (disposing)
  167. {
  168. var commsServer = _CommsServer;
  169. _CommsServer = null;
  170. if (commsServer != null)
  171. {
  172. commsServer.RequestReceived -= this.CommsServer_RequestReceived;
  173. if (!commsServer.IsShared)
  174. commsServer.Dispose();
  175. }
  176. DisposeRebroadcastTimer();
  177. foreach (var device in this.Devices)
  178. {
  179. DisconnectFromDeviceEvents(device);
  180. }
  181. _RecentSearchRequests = null;
  182. }
  183. }
  184. #endregion
  185. #region Private Methods
  186. #region Search Related Methods
  187. private void ProcessSearchRequest(string mx, string searchTarget, IpEndPointInfo endPoint)
  188. {
  189. if (String.IsNullOrEmpty(searchTarget))
  190. {
  191. WriteTrace(String.Format("Invalid search request received From {0}, Target is null/empty.", endPoint.ToString()));
  192. return;
  193. }
  194. WriteTrace(String.Format("Search Request Received From {0}, Target = {1}", endPoint.ToString(), searchTarget));
  195. if (IsDuplicateSearchRequest(searchTarget, endPoint))
  196. {
  197. WriteTrace("Search Request is Duplicate, ignoring.");
  198. return;
  199. }
  200. //Wait on random interval up to MX, as per SSDP spec.
  201. //Also, as per UPnP 1.1/SSDP spec ignore missing/bank MX header. If over 120, assume random value between 0 and 120.
  202. //Using 16 as minimum as that's often the minimum system clock frequency anyway.
  203. int maxWaitInterval = 0;
  204. if (String.IsNullOrEmpty(mx))
  205. {
  206. //Windows Explorer is poorly behaved and doesn't supply an MX header value.
  207. //if (this.SupportPnpRootDevice)
  208. mx = "1";
  209. //else
  210. //return;
  211. }
  212. if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0) return;
  213. if (maxWaitInterval > 120)
  214. maxWaitInterval = _Random.Next(0, 120);
  215. //Do not block synchronously as that may tie up a threadpool thread for several seconds.
  216. Task.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) =>
  217. {
  218. //Copying devices to local array here to avoid threading issues/enumerator exceptions.
  219. IEnumerable<SsdpDevice> devices = null;
  220. lock (_Devices)
  221. {
  222. if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)
  223. devices = GetAllDevicesAsFlatEnumerable().ToArray();
  224. else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (this.SupportPnpRootDevice && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0))
  225. devices = _Devices.ToArray();
  226. else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
  227. devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
  228. else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
  229. devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
  230. }
  231. if (devices != null)
  232. {
  233. var deviceList = devices.ToList();
  234. WriteTrace(String.Format("Sending {0} search responses", deviceList.Count));
  235. foreach (var device in deviceList)
  236. {
  237. SendDeviceSearchResponses(device, endPoint);
  238. }
  239. }
  240. else
  241. WriteTrace(String.Format("Sending 0 search responses."));
  242. });
  243. }
  244. private IEnumerable<SsdpDevice> GetAllDevicesAsFlatEnumerable()
  245. {
  246. return _Devices.Union(_Devices.SelectManyRecursive<SsdpDevice>((d) => d.Devices));
  247. }
  248. private void SendDeviceSearchResponses(SsdpDevice device, IpEndPointInfo endPoint)
  249. {
  250. bool isRootDevice = (device as SsdpRootDevice) != null;
  251. if (isRootDevice)
  252. {
  253. SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint);
  254. if (this.SupportPnpRootDevice)
  255. SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint);
  256. }
  257. SendSearchResponse(device.Udn, device, device.Udn, endPoint);
  258. SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint);
  259. }
  260. private static string GetUsn(string udn, string fullDeviceType)
  261. {
  262. return String.Format("{0}::{1}", udn, fullDeviceType);
  263. }
  264. private async void SendSearchResponse(string searchTarget, SsdpDevice device, string uniqueServiceName, IpEndPointInfo endPoint)
  265. {
  266. var rootDevice = device.ToRootDevice();
  267. //var additionalheaders = FormatCustomHeadersForResponse(device);
  268. const string header = "HTTP/1.1 200 OK";
  269. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  270. values["EXT"] = "";
  271. values["DATE"] = DateTime.UtcNow.ToString("r");
  272. values["CACHE-CONTROL"] = "max-age = 600";
  273. values["ST"] = searchTarget;
  274. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  275. values["USN"] = uniqueServiceName;
  276. values["LOCATION"] = rootDevice.Location.ToString();
  277. var message = BuildMessage(header, values);
  278. try
  279. {
  280. await _CommsServer.SendMessage(System.Text.Encoding.UTF8.GetBytes(message), endPoint).ConfigureAwait(false);
  281. }
  282. catch (Exception ex)
  283. {
  284. }
  285. WriteTrace(String.Format("Sent search response to " + endPoint.ToString()), device);
  286. }
  287. private bool IsDuplicateSearchRequest(string searchTarget, IpEndPointInfo endPoint)
  288. {
  289. var isDuplicateRequest = false;
  290. var newRequest = new SearchRequest() { EndPoint = endPoint, SearchTarget = searchTarget, Received = DateTime.UtcNow };
  291. lock (_RecentSearchRequests)
  292. {
  293. if (_RecentSearchRequests.ContainsKey(newRequest.Key))
  294. {
  295. var lastRequest = _RecentSearchRequests[newRequest.Key];
  296. if (lastRequest.IsOld())
  297. _RecentSearchRequests[newRequest.Key] = newRequest;
  298. else
  299. isDuplicateRequest = true;
  300. }
  301. else
  302. {
  303. _RecentSearchRequests.Add(newRequest.Key, newRequest);
  304. if (_RecentSearchRequests.Count > 10)
  305. CleanUpRecentSearchRequestsAsync();
  306. }
  307. }
  308. return isDuplicateRequest;
  309. }
  310. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable avoids compiler warning, but value is otherwise not required.")]
  311. private void CleanUpRecentSearchRequestsAsync()
  312. {
  313. var t = Task.Run(() =>
  314. {
  315. lock (_RecentSearchRequests)
  316. {
  317. foreach (var requestKey in (from r in _RecentSearchRequests where r.Value.IsOld() select r.Key).ToArray())
  318. {
  319. _RecentSearchRequests.Remove(requestKey);
  320. }
  321. }
  322. });
  323. }
  324. #endregion
  325. #region Notification Related Methods
  326. #region Alive
  327. private void SendAllAliveNotifications(object state)
  328. {
  329. try
  330. {
  331. if (IsDisposed) return;
  332. //DisposeRebroadcastTimer();
  333. WriteTrace("Begin Sending Alive Notifications For All Devices");
  334. _LastNotificationTime = DateTime.Now;
  335. IEnumerable<SsdpRootDevice> devices;
  336. lock (_Devices)
  337. {
  338. devices = _Devices.ToArray();
  339. }
  340. foreach (var device in devices)
  341. {
  342. if (IsDisposed) return;
  343. SendAliveNotifications(device, true);
  344. }
  345. WriteTrace("Completed Sending Alive Notifications For All Devices");
  346. }
  347. catch (ObjectDisposedException ex)
  348. {
  349. WriteTrace("Publisher stopped, exception " + ex.Message);
  350. Dispose();
  351. }
  352. //finally
  353. //{
  354. // // This is causing all notifications to stop
  355. // //if (!this.IsDisposed)
  356. // //SetRebroadcastAliveNotificationsTimer(_MinCacheTime);
  357. //}
  358. }
  359. private void SendAliveNotifications(SsdpDevice device, bool isRoot)
  360. {
  361. if (isRoot)
  362. {
  363. SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice));
  364. if (this.SupportPnpRootDevice)
  365. SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice));
  366. }
  367. SendAliveNotification(device, device.Udn, device.Udn);
  368. SendAliveNotification(device, device.FullDeviceType, GetUsn(device.Udn, device.FullDeviceType));
  369. foreach (var childDevice in device.Devices)
  370. {
  371. SendAliveNotifications(childDevice, false);
  372. }
  373. }
  374. private void SendAliveNotification(SsdpDevice device, string notificationType, string uniqueServiceName)
  375. {
  376. var rootDevice = device.ToRootDevice();
  377. const string header = "NOTIFY * HTTP/1.1";
  378. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  379. // If needed later for non-server devices, these headers will need to be dynamic
  380. values["HOST"] = "239.255.255.250:1900";
  381. values["DATE"] = DateTime.UtcNow.ToString("r");
  382. values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
  383. values["LOCATION"] = rootDevice.Location.ToString();
  384. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  385. values["NTS"] = "ssdp:alive";
  386. values["NT"] = notificationType;
  387. values["USN"] = uniqueServiceName;
  388. var message = BuildMessage(header, values);
  389. _CommsServer.SendMulticastMessage(System.Text.UTF8Encoding.UTF8.GetBytes(message));
  390. WriteTrace(String.Format("Sent alive notification"), device);
  391. }
  392. private string BuildMessage(string header, Dictionary<string, string> values)
  393. {
  394. var builder = new StringBuilder();
  395. const string argFormat = "{0}: {1}\r\n";
  396. builder.AppendFormat("{0}\r\n", header);
  397. foreach (var pair in values)
  398. {
  399. builder.AppendFormat(argFormat, pair.Key, pair.Value);
  400. }
  401. builder.Append("\r\n");
  402. return builder.ToString();
  403. }
  404. #endregion
  405. #region ByeBye
  406. private async Task SendByeByeNotifications(SsdpDevice device, bool isRoot)
  407. {
  408. if (isRoot)
  409. {
  410. await SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice)).ConfigureAwait(false);
  411. if (this.SupportPnpRootDevice)
  412. await SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice")).ConfigureAwait(false); ;
  413. }
  414. await SendByeByeNotification(device, device.Udn, device.Udn).ConfigureAwait(false); ;
  415. await SendByeByeNotification(device, String.Format("urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType)).ConfigureAwait(false); ;
  416. foreach (var childDevice in device.Devices)
  417. {
  418. await SendByeByeNotifications(childDevice, false).ConfigureAwait(false); ;
  419. }
  420. }
  421. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")]
  422. private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName)
  423. {
  424. const string header = "NOTIFY * HTTP/1.1";
  425. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  426. // If needed later for non-server devices, these headers will need to be dynamic
  427. values["HOST"] = "239.255.255.250:1900";
  428. values["DATE"] = DateTime.UtcNow.ToString("r");
  429. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  430. values["NTS"] = "ssdp:byebye";
  431. values["NT"] = notificationType;
  432. values["USN"] = uniqueServiceName;
  433. var message = BuildMessage(header, values);
  434. return _CommsServer.SendMulticastMessage(System.Text.UTF8Encoding.UTF8.GetBytes(message));
  435. //WriteTrace(String.Format("Sent byebye notification"), device);
  436. }
  437. #endregion
  438. #region Rebroadcast Timer
  439. private void DisposeRebroadcastTimer()
  440. {
  441. var timer = _RebroadcastAliveNotificationsTimer;
  442. _RebroadcastAliveNotificationsTimer = null;
  443. if (timer != null)
  444. timer.Dispose();
  445. }
  446. private void SetRebroadcastAliveNotificationsTimer(TimeSpan minCacheTime)
  447. {
  448. //if (minCacheTime == _RebroadcastAliveNotificationsTimeSpan) return;
  449. DisposeRebroadcastTimer();
  450. if (minCacheTime == TimeSpan.Zero) return;
  451. // According to UPnP/SSDP spec, we should randomise the interval at
  452. // which we broadcast notifications, to help with network congestion.
  453. // Specs also advise to choose a random interval up to *half* the cache time.
  454. // Here we do that, but using the minimum non-zero cache time of any device we are publishing.
  455. var rebroadCastInterval = new TimeSpan(minCacheTime.Ticks);
  456. // If we were already setup to rebroadcast someime in the future,
  457. // don't just blindly reset the next broadcast time to the new interval
  458. // as repeatedly changing the interval might end up causing us to over
  459. // delay in sending the next one.
  460. var nextBroadcastInterval = rebroadCastInterval;
  461. if (_LastNotificationTime != DateTime.MinValue)
  462. {
  463. nextBroadcastInterval = rebroadCastInterval.Subtract(DateTime.Now.Subtract(_LastNotificationTime));
  464. if (nextBroadcastInterval.Ticks < 0)
  465. nextBroadcastInterval = TimeSpan.Zero;
  466. else if (nextBroadcastInterval > rebroadCastInterval)
  467. nextBroadcastInterval = rebroadCastInterval;
  468. }
  469. //_RebroadcastAliveNotificationsTimeSpan = rebroadCastInterval;
  470. _RebroadcastAliveNotificationsTimer = _timerFactory.Create(SendAllAliveNotifications, null, nextBroadcastInterval, rebroadCastInterval);
  471. WriteTrace(String.Format("Rebroadcast Interval = {0}, Next Broadcast At = {1}", rebroadCastInterval.ToString(), nextBroadcastInterval.ToString()));
  472. }
  473. private TimeSpan GetMinimumNonZeroCacheLifetime()
  474. {
  475. var nonzeroCacheLifetimesQuery = (from device
  476. in _Devices
  477. where device.CacheLifetime != TimeSpan.Zero
  478. select device.CacheLifetime).ToList();
  479. if (nonzeroCacheLifetimesQuery.Any())
  480. return nonzeroCacheLifetimesQuery.Min();
  481. else
  482. return TimeSpan.Zero;
  483. }
  484. #endregion
  485. #endregion
  486. private static string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
  487. {
  488. string retVal = null;
  489. IEnumerable<String> values = null;
  490. if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null)
  491. retVal = values.FirstOrDefault();
  492. return retVal;
  493. }
  494. public static Action<string> LogFunction { get; set; }
  495. private static void WriteTrace(string text)
  496. {
  497. if (LogFunction != null)
  498. {
  499. LogFunction(text);
  500. }
  501. //System.Diagnostics.Debug.WriteLine(text, "SSDP Publisher");
  502. }
  503. private static void WriteTrace(string text, SsdpDevice device)
  504. {
  505. var rootDevice = device as SsdpRootDevice;
  506. if (rootDevice != null)
  507. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
  508. else
  509. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid);
  510. }
  511. private void ConnectToDeviceEvents(SsdpDevice device)
  512. {
  513. device.DeviceAdded += device_DeviceAdded;
  514. device.DeviceRemoved += device_DeviceRemoved;
  515. foreach (var childDevice in device.Devices)
  516. {
  517. ConnectToDeviceEvents(childDevice);
  518. }
  519. }
  520. private void DisconnectFromDeviceEvents(SsdpDevice device)
  521. {
  522. device.DeviceAdded -= device_DeviceAdded;
  523. device.DeviceRemoved -= device_DeviceRemoved;
  524. foreach (var childDevice in device.Devices)
  525. {
  526. DisconnectFromDeviceEvents(childDevice);
  527. }
  528. }
  529. #endregion
  530. #region Event Handlers
  531. private void device_DeviceAdded(object sender, DeviceEventArgs e)
  532. {
  533. SendAliveNotifications(e.Device, false);
  534. ConnectToDeviceEvents(e.Device);
  535. }
  536. private void device_DeviceRemoved(object sender, DeviceEventArgs e)
  537. {
  538. var task = SendByeByeNotifications(e.Device, false);
  539. Task.WaitAll(task);
  540. DisconnectFromDeviceEvents(e.Device);
  541. }
  542. private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
  543. {
  544. if (this.IsDisposed) return;
  545. if (e.Message.Method.Method == SsdpConstants.MSearchMethod)
  546. {
  547. //According to SSDP/UPnP spec, ignore message if missing these headers.
  548. // Edit: But some devices do it anyway
  549. //if (!e.Message.Headers.Contains("MX"))
  550. // WriteTrace("Ignoring search request - missing MX header.");
  551. //else if (!e.Message.Headers.Contains("MAN"))
  552. // WriteTrace("Ignoring search request - missing MAN header.");
  553. //else
  554. ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom);
  555. }
  556. }
  557. #endregion
  558. #region Private Classes
  559. private class SearchRequest
  560. {
  561. public IpEndPointInfo EndPoint { get; set; }
  562. public DateTime Received { get; set; }
  563. public string SearchTarget { get; set; }
  564. public string Key
  565. {
  566. get { return this.SearchTarget + ":" + this.EndPoint.ToString(); }
  567. }
  568. public bool IsOld()
  569. {
  570. return DateTime.UtcNow.Subtract(this.Received).TotalMilliseconds > 500;
  571. }
  572. }
  573. #endregion
  574. }
  575. }