SsdpDevicePublisherBase.cs 29 KB

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