SsdpDevicePublisherBase.cs 28 KB

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