SsdpDevicePublisher.cs 25 KB

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