SsdpDevicePublisher.cs 26 KB

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