SsdpDevicePublisherBase.cs 28 KB

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