SsdpDevicePublisher.cs 25 KB

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