SsdpDevicePublisher.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  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. /// <summary>
  28. /// Default constructor.
  29. /// </summary>
  30. public SsdpDevicePublisher(
  31. ISsdpCommunicationsServer communicationsServer,
  32. string osName,
  33. string osVersion,
  34. bool sendOnlyMatchedHost)
  35. {
  36. if (communicationsServer is null)
  37. {
  38. throw new ArgumentNullException(nameof(communicationsServer));
  39. }
  40. if (osName is null)
  41. {
  42. throw new ArgumentNullException(nameof(osName));
  43. }
  44. if (osName.Length == 0)
  45. {
  46. throw new ArgumentException("osName cannot be an empty string.", nameof(osName));
  47. }
  48. if (osVersion is null)
  49. {
  50. throw new ArgumentNullException(nameof(osVersion));
  51. }
  52. if (osVersion.Length == 0)
  53. {
  54. throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName));
  55. }
  56. _SupportPnpRootDevice = true;
  57. _Devices = new List<SsdpRootDevice>();
  58. _ReadOnlyDevices = new ReadOnlyCollection<SsdpRootDevice>(_Devices);
  59. _RecentSearchRequests = new Dictionary<string, SearchRequest>(StringComparer.OrdinalIgnoreCase);
  60. _Random = new Random();
  61. _CommsServer = communicationsServer;
  62. _CommsServer.RequestReceived += CommsServer_RequestReceived;
  63. _OSName = osName;
  64. _OSVersion = osVersion;
  65. _sendOnlyMatchedHost = sendOnlyMatchedHost;
  66. _CommsServer.BeginListeningForMulticast();
  67. // Send alive notification once on creation
  68. SendAllAliveNotifications(null);
  69. }
  70. public void StartSendingAliveNotifications(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. public void AddDevice(SsdpRootDevice device)
  86. {
  87. if (device is 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 is 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 is not 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 is not 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. int maxWaitInterval = 0;
  211. if (String.IsNullOrEmpty(mx))
  212. {
  213. // Windows Explorer is poorly behaved and doesn't supply an MX header value.
  214. // if (this.SupportPnpRootDevice)
  215. mx = "1";
  216. // else
  217. // return;
  218. }
  219. if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0)
  220. {
  221. return;
  222. }
  223. if (maxWaitInterval > 120)
  224. {
  225. maxWaitInterval = _Random.Next(0, 120);
  226. }
  227. // Do not block synchronously as that may tie up a threadpool thread for several seconds.
  228. Task.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) =>
  229. {
  230. // Copying devices to local array here to avoid threading issues/enumerator exceptions.
  231. IEnumerable<SsdpDevice> devices = null;
  232. lock (_Devices)
  233. {
  234. if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)
  235. {
  236. devices = GetAllDevicesAsFlatEnumerable().ToArray();
  237. }
  238. else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (this.SupportPnpRootDevice && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0))
  239. {
  240. devices = _Devices.ToArray();
  241. }
  242. else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
  243. {
  244. devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0).ToArray();
  245. }
  246. else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
  247. {
  248. devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0).ToArray();
  249. }
  250. }
  251. if (devices is not null)
  252. {
  253. // WriteTrace(String.Format("Sending {0} search responses", deviceList.Count));
  254. foreach (var device in devices)
  255. {
  256. var root = device.ToRootDevice();
  257. if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIPAddress))
  258. {
  259. SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIPAddress, cancellationToken);
  260. }
  261. }
  262. }
  263. });
  264. }
  265. private IEnumerable<SsdpDevice> GetAllDevicesAsFlatEnumerable()
  266. {
  267. return _Devices.Union(_Devices.SelectManyRecursive<SsdpDevice>((d) => d.Devices));
  268. }
  269. private void SendDeviceSearchResponses(
  270. SsdpDevice device,
  271. IPEndPoint endPoint,
  272. IPAddress receivedOnlocalIPAddress,
  273. CancellationToken cancellationToken)
  274. {
  275. bool isRootDevice = (device as SsdpRootDevice) is not null;
  276. if (isRootDevice)
  277. {
  278. SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken);
  279. if (this.SupportPnpRootDevice)
  280. {
  281. SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken);
  282. }
  283. }
  284. SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIPAddress, cancellationToken);
  285. SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIPAddress, cancellationToken);
  286. }
  287. private string GetUsn(string udn, string fullDeviceType)
  288. {
  289. return String.Format(CultureInfo.InvariantCulture, "{0}::{1}", udn, fullDeviceType);
  290. }
  291. private async void SendSearchResponse(
  292. string searchTarget,
  293. SsdpDevice device,
  294. string uniqueServiceName,
  295. IPEndPoint endPoint,
  296. IPAddress receivedOnlocalIPAddress,
  297. CancellationToken cancellationToken)
  298. {
  299. const string header = "HTTP/1.1 200 OK";
  300. var rootDevice = device.ToRootDevice();
  301. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  302. values["EXT"] = "";
  303. values["DATE"] = DateTime.UtcNow.ToString("r");
  304. values["HOST"] = "239.255.255.250:1900";
  305. values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
  306. values["ST"] = searchTarget;
  307. values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
  308. values["USN"] = uniqueServiceName;
  309. values["LOCATION"] = rootDevice.Location.ToString();
  310. var message = BuildMessage(header, values);
  311. try
  312. {
  313. await _CommsServer.SendMessage(
  314. Encoding.UTF8.GetBytes(message),
  315. endPoint,
  316. receivedOnlocalIPAddress,
  317. cancellationToken)
  318. .ConfigureAwait(false);
  319. }
  320. catch (Exception)
  321. {
  322. }
  323. // WriteTrace(String.Format("Sent search response to " + endPoint.ToString()), device);
  324. }
  325. private bool IsDuplicateSearchRequest(string searchTarget, IPEndPoint endPoint)
  326. {
  327. var isDuplicateRequest = false;
  328. var newRequest = new SearchRequest() { EndPoint = endPoint, SearchTarget = searchTarget, Received = DateTime.UtcNow };
  329. lock (_RecentSearchRequests)
  330. {
  331. if (_RecentSearchRequests.ContainsKey(newRequest.Key))
  332. {
  333. var lastRequest = _RecentSearchRequests[newRequest.Key];
  334. if (lastRequest.IsOld())
  335. {
  336. _RecentSearchRequests[newRequest.Key] = newRequest;
  337. }
  338. else
  339. {
  340. isDuplicateRequest = true;
  341. }
  342. }
  343. else
  344. {
  345. _RecentSearchRequests.Add(newRequest.Key, newRequest);
  346. if (_RecentSearchRequests.Count > 10)
  347. {
  348. CleanUpRecentSearchRequestsAsync();
  349. }
  350. }
  351. }
  352. return isDuplicateRequest;
  353. }
  354. private void CleanUpRecentSearchRequestsAsync()
  355. {
  356. lock (_RecentSearchRequests)
  357. {
  358. foreach (var requestKey in (from r in _RecentSearchRequests where r.Value.IsOld() select r.Key).ToArray())
  359. {
  360. _RecentSearchRequests.Remove(requestKey);
  361. }
  362. }
  363. }
  364. private void SendAllAliveNotifications(object state)
  365. {
  366. try
  367. {
  368. if (IsDisposed)
  369. {
  370. return;
  371. }
  372. // WriteTrace("Begin Sending Alive Notifications For All Devices");
  373. SsdpRootDevice[] devices;
  374. lock (_Devices)
  375. {
  376. devices = _Devices.ToArray();
  377. }
  378. foreach (var device in devices)
  379. {
  380. if (IsDisposed)
  381. {
  382. return;
  383. }
  384. SendAliveNotifications(device, true, CancellationToken.None);
  385. }
  386. // WriteTrace("Completed Sending Alive Notifications For All Devices");
  387. }
  388. catch (ObjectDisposedException ex)
  389. {
  390. WriteTrace("Publisher stopped, exception " + ex.Message);
  391. Dispose();
  392. }
  393. }
  394. private void SendAliveNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
  395. {
  396. if (isRoot)
  397. {
  398. SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken);
  399. if (this.SupportPnpRootDevice)
  400. {
  401. SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), cancellationToken);
  402. }
  403. }
  404. SendAliveNotification(device, device.Udn, device.Udn, cancellationToken);
  405. SendAliveNotification(device, device.FullDeviceType, GetUsn(device.Udn, device.FullDeviceType), cancellationToken);
  406. foreach (var childDevice in device.Devices)
  407. {
  408. SendAliveNotifications(childDevice, false, cancellationToken);
  409. }
  410. }
  411. private void SendAliveNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
  412. {
  413. var rootDevice = device.ToRootDevice();
  414. const string header = "NOTIFY * HTTP/1.1";
  415. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  416. // If needed later for non-server devices, these headers will need to be dynamic
  417. values["HOST"] = "239.255.255.250:1900";
  418. values["DATE"] = DateTime.UtcNow.ToString("r");
  419. values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
  420. values["LOCATION"] = rootDevice.Location.ToString();
  421. values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
  422. values["NTS"] = "ssdp:alive";
  423. values["NT"] = notificationType;
  424. values["USN"] = uniqueServiceName;
  425. var message = BuildMessage(header, values);
  426. _CommsServer.SendMulticastMessage(message, _sendOnlyMatchedHost ? rootDevice.Address : null, cancellationToken);
  427. // WriteTrace(String.Format("Sent alive notification"), device);
  428. }
  429. private Task SendByeByeNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
  430. {
  431. var tasks = new List<Task>();
  432. if (isRoot)
  433. {
  434. tasks.Add(SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken));
  435. if (this.SupportPnpRootDevice)
  436. {
  437. tasks.Add(SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"), cancellationToken));
  438. }
  439. }
  440. tasks.Add(SendByeByeNotification(device, device.Udn, device.Udn, cancellationToken));
  441. tasks.Add(SendByeByeNotification(device, String.Format(CultureInfo.InvariantCulture, "urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType), cancellationToken));
  442. foreach (var childDevice in device.Devices)
  443. {
  444. tasks.Add(SendByeByeNotifications(childDevice, false, cancellationToken));
  445. }
  446. return Task.WhenAll(tasks);
  447. }
  448. private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
  449. {
  450. const string header = "NOTIFY * HTTP/1.1";
  451. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  452. // If needed later for non-server devices, these headers will need to be dynamic
  453. values["HOST"] = "239.255.255.250:1900";
  454. values["DATE"] = DateTime.UtcNow.ToString("r");
  455. values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
  456. values["NTS"] = "ssdp:byebye";
  457. values["NT"] = notificationType;
  458. values["USN"] = uniqueServiceName;
  459. var message = BuildMessage(header, values);
  460. var sendCount = IsDisposed ? 1 : 3;
  461. WriteTrace(String.Format(CultureInfo.InvariantCulture, "Sent byebye notification"), device);
  462. return _CommsServer.SendMulticastMessage(message, sendCount, _sendOnlyMatchedHost ? device.ToRootDevice().Address : null, cancellationToken);
  463. }
  464. private void DisposeRebroadcastTimer()
  465. {
  466. var timer = _RebroadcastAliveNotificationsTimer;
  467. _RebroadcastAliveNotificationsTimer = null;
  468. if (timer is not null)
  469. {
  470. timer.Dispose();
  471. }
  472. }
  473. private TimeSpan GetMinimumNonZeroCacheLifetime()
  474. {
  475. var nonzeroCacheLifetimesQuery = (
  476. from device
  477. in _Devices
  478. where device.CacheLifetime != TimeSpan.Zero
  479. select device.CacheLifetime).ToList();
  480. if (nonzeroCacheLifetimesQuery.Any())
  481. {
  482. return nonzeroCacheLifetimesQuery.Min();
  483. }
  484. else
  485. {
  486. return TimeSpan.Zero;
  487. }
  488. }
  489. private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
  490. {
  491. string retVal = null;
  492. IEnumerable<String> values = null;
  493. if (httpRequestHeaders.TryGetValues(headerName, out values) && values is not null)
  494. {
  495. retVal = values.FirstOrDefault();
  496. }
  497. return retVal;
  498. }
  499. public Action<string> LogFunction { get; set; }
  500. private void WriteTrace(string text)
  501. {
  502. if (LogFunction is not null)
  503. {
  504. LogFunction(text);
  505. }
  506. // System.Diagnostics.Debug.WriteLine(text, "SSDP Publisher");
  507. }
  508. private void WriteTrace(string text, SsdpDevice device)
  509. {
  510. var rootDevice = device as SsdpRootDevice;
  511. if (rootDevice is not null)
  512. {
  513. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
  514. }
  515. else
  516. {
  517. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid);
  518. }
  519. }
  520. private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
  521. {
  522. if (this.IsDisposed)
  523. {
  524. return;
  525. }
  526. if (string.Equals(e.Message.Method.Method, SsdpConstants.MSearchMethod, StringComparison.OrdinalIgnoreCase))
  527. {
  528. // According to SSDP/UPnP spec, ignore message if missing these headers.
  529. // Edit: But some devices do it anyway
  530. // if (!e.Message.Headers.Contains("MX"))
  531. // WriteTrace("Ignoring search request - missing MX header.");
  532. // else if (!e.Message.Headers.Contains("MAN"))
  533. // WriteTrace("Ignoring search request - missing MAN header.");
  534. // else
  535. ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIPAddress, CancellationToken.None);
  536. }
  537. }
  538. private class SearchRequest
  539. {
  540. public IPEndPoint EndPoint { get; set; }
  541. public DateTime Received { get; set; }
  542. public string SearchTarget { get; set; }
  543. public string Key
  544. {
  545. get { return this.SearchTarget + ":" + this.EndPoint.ToString(); }
  546. }
  547. public bool IsOld()
  548. {
  549. return DateTime.UtcNow.Subtract(this.Received).TotalMilliseconds > 500;
  550. }
  551. }
  552. }
  553. }