SsdpDevicePublisher.cs 25 KB

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