SsdpDevicePublisher.cs 24 KB

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