SsdpDevicePublisher.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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 supresses 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 notifiation 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. if (!_sendOnlyMatchedHost ||
  260. _networkManager.IsInSameSubnet(device.ToRootDevice().Address, remoteEndPoint.Address, device.ToRootDevice().SubnetMask))
  261. {
  262. SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken);
  263. }
  264. }
  265. }
  266. else
  267. {
  268. // WriteTrace(String.Format("Sending 0 search responses."));
  269. }
  270. });
  271. }
  272. private IEnumerable<SsdpDevice> GetAllDevicesAsFlatEnumerable()
  273. {
  274. return _Devices.Union(_Devices.SelectManyRecursive<SsdpDevice>((d) => d.Devices));
  275. }
  276. private void SendDeviceSearchResponses(
  277. SsdpDevice device,
  278. IPEndPoint endPoint,
  279. IPAddress receivedOnlocalIpAddress,
  280. CancellationToken cancellationToken)
  281. {
  282. bool isRootDevice = (device as SsdpRootDevice) != null;
  283. if (isRootDevice)
  284. {
  285. SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
  286. if (this.SupportPnpRootDevice)
  287. {
  288. SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
  289. }
  290. }
  291. SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken);
  292. SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIpAddress, cancellationToken);
  293. }
  294. private string GetUsn(string udn, string fullDeviceType)
  295. {
  296. return String.Format("{0}::{1}", udn, fullDeviceType);
  297. }
  298. private async void SendSearchResponse(
  299. string searchTarget,
  300. SsdpDevice device,
  301. string uniqueServiceName,
  302. IPEndPoint endPoint,
  303. IPAddress receivedOnlocalIpAddress,
  304. CancellationToken cancellationToken)
  305. {
  306. var rootDevice = device.ToRootDevice();
  307. // var additionalheaders = FormatCustomHeadersForResponse(device);
  308. const string header = "HTTP/1.1 200 OK";
  309. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  310. values["EXT"] = "";
  311. values["DATE"] = DateTime.UtcNow.ToString("r");
  312. values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
  313. values["ST"] = searchTarget;
  314. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  315. values["USN"] = uniqueServiceName;
  316. values["LOCATION"] = rootDevice.Location.ToString();
  317. var message = BuildMessage(header, values);
  318. try
  319. {
  320. await _CommsServer.SendMessage(
  321. System.Text.Encoding.UTF8.GetBytes(message),
  322. endPoint,
  323. receivedOnlocalIpAddress,
  324. cancellationToken)
  325. .ConfigureAwait(false);
  326. }
  327. catch (Exception)
  328. {
  329. }
  330. // WriteTrace(String.Format("Sent search response to " + endPoint.ToString()), device);
  331. }
  332. private bool IsDuplicateSearchRequest(string searchTarget, IPEndPoint endPoint)
  333. {
  334. var isDuplicateRequest = false;
  335. var newRequest = new SearchRequest() { EndPoint = endPoint, SearchTarget = searchTarget, Received = DateTime.UtcNow };
  336. lock (_RecentSearchRequests)
  337. {
  338. if (_RecentSearchRequests.ContainsKey(newRequest.Key))
  339. {
  340. var lastRequest = _RecentSearchRequests[newRequest.Key];
  341. if (lastRequest.IsOld())
  342. {
  343. _RecentSearchRequests[newRequest.Key] = newRequest;
  344. }
  345. else
  346. {
  347. isDuplicateRequest = true;
  348. }
  349. }
  350. else
  351. {
  352. _RecentSearchRequests.Add(newRequest.Key, newRequest);
  353. if (_RecentSearchRequests.Count > 10)
  354. {
  355. CleanUpRecentSearchRequestsAsync();
  356. }
  357. }
  358. }
  359. return isDuplicateRequest;
  360. }
  361. private void CleanUpRecentSearchRequestsAsync()
  362. {
  363. lock (_RecentSearchRequests)
  364. {
  365. foreach (var requestKey in (from r in _RecentSearchRequests where r.Value.IsOld() select r.Key).ToArray())
  366. {
  367. _RecentSearchRequests.Remove(requestKey);
  368. }
  369. }
  370. }
  371. private void SendAllAliveNotifications(object state)
  372. {
  373. try
  374. {
  375. if (IsDisposed)
  376. {
  377. return;
  378. }
  379. // WriteTrace("Begin Sending Alive Notifications For All Devices");
  380. SsdpRootDevice[] devices;
  381. lock (_Devices)
  382. {
  383. devices = _Devices.ToArray();
  384. }
  385. foreach (var device in devices)
  386. {
  387. if (IsDisposed)
  388. {
  389. return;
  390. }
  391. SendAliveNotifications(device, true, CancellationToken.None);
  392. }
  393. // WriteTrace("Completed Sending Alive Notifications For All Devices");
  394. }
  395. catch (ObjectDisposedException ex)
  396. {
  397. WriteTrace("Publisher stopped, exception " + ex.Message);
  398. Dispose();
  399. }
  400. }
  401. private void SendAliveNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
  402. {
  403. if (isRoot)
  404. {
  405. SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken);
  406. if (this.SupportPnpRootDevice)
  407. {
  408. SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), cancellationToken);
  409. }
  410. }
  411. SendAliveNotification(device, device.Udn, device.Udn, cancellationToken);
  412. SendAliveNotification(device, device.FullDeviceType, GetUsn(device.Udn, device.FullDeviceType), cancellationToken);
  413. foreach (var childDevice in device.Devices)
  414. {
  415. SendAliveNotifications(childDevice, false, cancellationToken);
  416. }
  417. }
  418. private void SendAliveNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
  419. {
  420. var rootDevice = device.ToRootDevice();
  421. const string header = "NOTIFY * HTTP/1.1";
  422. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  423. // If needed later for non-server devices, these headers will need to be dynamic
  424. values["HOST"] = "239.255.255.250:1900";
  425. values["DATE"] = DateTime.UtcNow.ToString("r");
  426. values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
  427. values["LOCATION"] = rootDevice.Location.ToString();
  428. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  429. values["NTS"] = "ssdp:alive";
  430. values["NT"] = notificationType;
  431. values["USN"] = uniqueServiceName;
  432. var message = BuildMessage(header, values);
  433. _CommsServer.SendMulticastMessage(message, _sendOnlyMatchedHost ? rootDevice.Address : null, cancellationToken);
  434. // WriteTrace(String.Format("Sent alive notification"), device);
  435. }
  436. private Task SendByeByeNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
  437. {
  438. var tasks = new List<Task>();
  439. if (isRoot)
  440. {
  441. tasks.Add(SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken));
  442. if (this.SupportPnpRootDevice)
  443. {
  444. tasks.Add(SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"), cancellationToken));
  445. }
  446. }
  447. tasks.Add(SendByeByeNotification(device, device.Udn, device.Udn, cancellationToken));
  448. tasks.Add(SendByeByeNotification(device, String.Format("urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType), cancellationToken));
  449. foreach (var childDevice in device.Devices)
  450. {
  451. tasks.Add(SendByeByeNotifications(childDevice, false, cancellationToken));
  452. }
  453. return Task.WhenAll(tasks);
  454. }
  455. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")]
  456. private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
  457. {
  458. const string header = "NOTIFY * HTTP/1.1";
  459. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  460. // If needed later for non-server devices, these headers will need to be dynamic
  461. values["HOST"] = "239.255.255.250:1900";
  462. values["DATE"] = DateTime.UtcNow.ToString("r");
  463. values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
  464. values["NTS"] = "ssdp:byebye";
  465. values["NT"] = notificationType;
  466. values["USN"] = uniqueServiceName;
  467. var message = BuildMessage(header, values);
  468. var sendCount = IsDisposed ? 1 : 3;
  469. WriteTrace(String.Format("Sent byebye notification"), device);
  470. return _CommsServer.SendMulticastMessage(message, sendCount, _sendOnlyMatchedHost ? device.ToRootDevice().Address : null, cancellationToken);
  471. }
  472. private void DisposeRebroadcastTimer()
  473. {
  474. var timer = _RebroadcastAliveNotificationsTimer;
  475. _RebroadcastAliveNotificationsTimer = null;
  476. if (timer != null)
  477. {
  478. timer.Dispose();
  479. }
  480. }
  481. private TimeSpan GetMinimumNonZeroCacheLifetime()
  482. {
  483. var nonzeroCacheLifetimesQuery = (
  484. from device
  485. in _Devices
  486. where device.CacheLifetime != TimeSpan.Zero
  487. select device.CacheLifetime).ToList();
  488. if (nonzeroCacheLifetimesQuery.Any())
  489. {
  490. return nonzeroCacheLifetimesQuery.Min();
  491. }
  492. else
  493. {
  494. return TimeSpan.Zero;
  495. }
  496. }
  497. private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
  498. {
  499. string retVal = null;
  500. IEnumerable<String> values = null;
  501. if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null)
  502. {
  503. retVal = values.FirstOrDefault();
  504. }
  505. return retVal;
  506. }
  507. public Action<string> LogFunction { get; set; }
  508. private void WriteTrace(string text)
  509. {
  510. if (LogFunction != null)
  511. {
  512. LogFunction(text);
  513. }
  514. // System.Diagnostics.Debug.WriteLine(text, "SSDP Publisher");
  515. }
  516. private void WriteTrace(string text, SsdpDevice device)
  517. {
  518. var rootDevice = device as SsdpRootDevice;
  519. if (rootDevice != null)
  520. {
  521. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
  522. }
  523. else
  524. {
  525. WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid);
  526. }
  527. }
  528. private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
  529. {
  530. if (this.IsDisposed)
  531. {
  532. return;
  533. }
  534. if (string.Equals(e.Message.Method.Method, SsdpConstants.MSearchMethod, StringComparison.OrdinalIgnoreCase))
  535. {
  536. // According to SSDP/UPnP spec, ignore message if missing these headers.
  537. // Edit: But some devices do it anyway
  538. // if (!e.Message.Headers.Contains("MX"))
  539. // WriteTrace("Ignoring search request - missing MX header.");
  540. // else if (!e.Message.Headers.Contains("MAN"))
  541. // WriteTrace("Ignoring search request - missing MAN header.");
  542. // else
  543. ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIpAddress, CancellationToken.None);
  544. }
  545. }
  546. private class SearchRequest
  547. {
  548. public IPEndPoint EndPoint { get; set; }
  549. public DateTime Received { get; set; }
  550. public string SearchTarget { get; set; }
  551. public string Key
  552. {
  553. get { return this.SearchTarget + ":" + this.EndPoint.ToString(); }
  554. }
  555. public bool IsOld()
  556. {
  557. return DateTime.UtcNow.Subtract(this.Received).TotalMilliseconds > 500;
  558. }
  559. }
  560. }
  561. }