SsdpDevicePublisher.cs 26 KB

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