SsdpDevicePublisher.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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("communicationsServer");
  36. if (osName == null) throw new ArgumentNullException("osName");
  37. if (osName.Length == 0) throw new ArgumentException("osName cannot be an empty string.", "osName");
  38. if (osVersion == null) throw new ArgumentNullException("osVersion");
  39. if (osVersion.Length == 0) throw new ArgumentException("osVersion cannot be an empty string.", "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="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
  66. /// <exception cref="System.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("device");
  71. ThrowIfDisposed();
  72. TimeSpan 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="System.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("device");
  101. bool wasRemoved = false;
  102. TimeSpan 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(System.Text.Encoding.UTF8.GetBytes(message), endPoint, receivedOnlocalIpAddress, cancellationToken).ConfigureAwait(false);
  264. }
  265. catch (Exception ex)
  266. {
  267. }
  268. //WriteTrace(String.Format("Sent search response to " + endPoint.ToString()), device);
  269. }
  270. private bool IsDuplicateSearchRequest(string searchTarget, IpEndPointInfo endPoint)
  271. {
  272. var isDuplicateRequest = false;
  273. var newRequest = new SearchRequest() { EndPoint = endPoint, SearchTarget = searchTarget, Received = DateTime.UtcNow };
  274. lock (_RecentSearchRequests)
  275. {
  276. if (_RecentSearchRequests.ContainsKey(newRequest.Key))
  277. {
  278. var lastRequest = _RecentSearchRequests[newRequest.Key];
  279. if (lastRequest.IsOld())
  280. _RecentSearchRequests[newRequest.Key] = newRequest;
  281. else
  282. isDuplicateRequest = true;
  283. }
  284. else
  285. {
  286. _RecentSearchRequests.Add(newRequest.Key, newRequest);
  287. if (_RecentSearchRequests.Count > 10)
  288. CleanUpRecentSearchRequestsAsync();
  289. }
  290. }
  291. return isDuplicateRequest;
  292. }
  293. private void CleanUpRecentSearchRequestsAsync()
  294. {
  295. lock (_RecentSearchRequests)
  296. {
  297. foreach (var requestKey in (from r in _RecentSearchRequests where r.Value.IsOld() select r.Key).ToArray())
  298. {
  299. _RecentSearchRequests.Remove(requestKey);
  300. }
  301. }
  302. }
  303. private void SendAllAliveNotifications(object state)
  304. {
  305. try
  306. {
  307. if (IsDisposed) return;
  308. //WriteTrace("Begin Sending Alive Notifications For All Devices");
  309. SsdpRootDevice[] devices;
  310. lock (_Devices)
  311. {
  312. devices = _Devices.ToArray();
  313. }
  314. foreach (var device in devices)
  315. {
  316. if (IsDisposed) return;
  317. SendAliveNotifications(device, true, CancellationToken.None);
  318. }
  319. //WriteTrace("Completed Sending Alive Notifications For All Devices");
  320. }
  321. catch (ObjectDisposedException ex)
  322. {
  323. WriteTrace("Publisher stopped, exception " + ex.Message);
  324. Dispose();
  325. }
  326. }
  327. private void SendAliveNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
  328. {
  329. if (isRoot)
  330. {
  331. SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken);
  332. if (this.SupportPnpRootDevice)
  333. SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), cancellationToken);
  334. }
  335. SendAliveNotification(device, device.Udn, device.Udn, cancellationToken);
  336. SendAliveNotification(device, device.FullDeviceType, GetUsn(device.Udn, device.FullDeviceType), cancellationToken);
  337. foreach (var childDevice in device.Devices)
  338. {
  339. SendAliveNotifications(childDevice, false, cancellationToken);
  340. }
  341. }
  342. private void SendAliveNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
  343. {
  344. var rootDevice = device.ToRootDevice();
  345. const string header = "NOTIFY * HTTP/1.1";
  346. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  347. // If needed later for non-server devices, these headers will need to be dynamic
  348. values["HOST"] = "239.255.255.250:1900";
  349. values["DATE"] = DateTime.UtcNow.ToString("r");
  350. values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
  351. values["LOCATION"] = rootDevice.Location.ToString();
  352. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  353. values["NTS"] = "ssdp:alive";
  354. values["NT"] = notificationType;
  355. values["USN"] = uniqueServiceName;
  356. var message = BuildMessage(header, values);
  357. _CommsServer.SendMulticastMessage(message, cancellationToken);
  358. //WriteTrace(String.Format("Sent alive notification"), device);
  359. }
  360. private Task SendByeByeNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
  361. {
  362. var tasks = new List<Task>();
  363. if (isRoot)
  364. {
  365. tasks.Add(SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken));
  366. if (this.SupportPnpRootDevice)
  367. tasks.Add(SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"), cancellationToken));
  368. }
  369. tasks.Add(SendByeByeNotification(device, device.Udn, device.Udn, cancellationToken));
  370. tasks.Add(SendByeByeNotification(device, String.Format("urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType), cancellationToken));
  371. foreach (var childDevice in device.Devices)
  372. {
  373. tasks.Add(SendByeByeNotifications(childDevice, false, cancellationToken));
  374. }
  375. return Task.WhenAll(tasks);
  376. }
  377. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")]
  378. private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
  379. {
  380. const string header = "NOTIFY * HTTP/1.1";
  381. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  382. // If needed later for non-server devices, these headers will need to be dynamic
  383. values["HOST"] = "239.255.255.250:1900";
  384. values["DATE"] = DateTime.UtcNow.ToString("r");
  385. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  386. values["NTS"] = "ssdp:byebye";
  387. values["NT"] = notificationType;
  388. values["USN"] = uniqueServiceName;
  389. var message = BuildMessage(header, values);
  390. var sendCount = IsDisposed ? 1 : 3;
  391. WriteTrace(String.Format("Sent byebye notification"), device);
  392. return _CommsServer.SendMulticastMessage(message, sendCount, cancellationToken);
  393. }
  394. private void DisposeRebroadcastTimer()
  395. {
  396. var timer = _RebroadcastAliveNotificationsTimer;
  397. _RebroadcastAliveNotificationsTimer = null;
  398. if (timer != null)
  399. timer.Dispose();
  400. }
  401. private TimeSpan GetMinimumNonZeroCacheLifetime()
  402. {
  403. var nonzeroCacheLifetimesQuery = (from device
  404. in _Devices
  405. where device.CacheLifetime != TimeSpan.Zero
  406. select device.CacheLifetime).ToList();
  407. if (nonzeroCacheLifetimesQuery.Any())
  408. return nonzeroCacheLifetimesQuery.Min();
  409. else
  410. return TimeSpan.Zero;
  411. }
  412. private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
  413. {
  414. string retVal = null;
  415. IEnumerable<String> values = null;
  416. if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null)
  417. retVal = values.FirstOrDefault();
  418. return retVal;
  419. }
  420. public Action<string> LogFunction { get; set; }
  421. private void WriteTrace(string text)
  422. {
  423. if (LogFunction != null)
  424. {
  425. LogFunction(text);
  426. }
  427. //System.Diagnostics.Debug.WriteLine(text, "SSDP Publisher");
  428. }
  429. private void WriteTrace(string text, SsdpDevice device)
  430. {
  431. var rootDevice = device as SsdpRootDevice;
  432. if (rootDevice != null)
  433. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
  434. else
  435. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid);
  436. }
  437. private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
  438. {
  439. if (this.IsDisposed) return;
  440. if (string.Equals(e.Message.Method.Method, SsdpConstants.MSearchMethod, StringComparison.OrdinalIgnoreCase))
  441. {
  442. //According to SSDP/UPnP spec, ignore message if missing these headers.
  443. // Edit: But some devices do it anyway
  444. //if (!e.Message.Headers.Contains("MX"))
  445. // WriteTrace("Ignoring search request - missing MX header.");
  446. //else if (!e.Message.Headers.Contains("MAN"))
  447. // WriteTrace("Ignoring search request - missing MAN header.");
  448. //else
  449. ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIpAddress, CancellationToken.None);
  450. }
  451. }
  452. private class SearchRequest
  453. {
  454. public IpEndPointInfo EndPoint { get; set; }
  455. public DateTime Received { get; set; }
  456. public string SearchTarget { get; set; }
  457. public string Key
  458. {
  459. get { return this.SearchTarget + ":" + this.EndPoint.ToString(); }
  460. }
  461. public bool IsOld()
  462. {
  463. return DateTime.UtcNow.Subtract(this.Received).TotalMilliseconds > 500;
  464. }
  465. }
  466. }
  467. }