SsdpDevicePublisher.cs 25 KB

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