SsdpDevicePublisher.cs 26 KB

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