SsdpDevicePublisher.cs 26 KB

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