SsdpDevicePublisher.cs 26 KB

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