SsdpDevicePublisherBase.cs 29 KB

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