SsdpDevicePublisher.cs 25 KB

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