2
0

SsdpDevicePublisher.cs 26 KB

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