SsdpCommunicationsServer.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Model.Net;
  12. using Microsoft.Extensions.Logging;
  13. namespace Rssdp.Infrastructure
  14. {
  15. /// <summary>
  16. /// Provides the platform independent logic for publishing device existence and responding to search requests.
  17. /// </summary>
  18. public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
  19. {
  20. /* We could technically use one socket listening on port 1900 for everything.
  21. * This should get both multicast (notifications) and unicast (search response) messages, however
  22. * this often doesn't work under Windows because the MS SSDP service is running. If that service
  23. * is running then it will steal the unicast messages and we will never see search responses.
  24. * Since stopping the service would be a bad idea (might not be allowed security wise and might
  25. * break other apps running on the system) the only other work around is to use two sockets.
  26. *
  27. * We use one group of sockets to listen for/receive notifications and search requests (_MulticastListenSockets).
  28. * We use a second group, bound to a different local port, to send search requests and listen for
  29. * responses (_SendSockets). The responses are sent to the local ports these sockets are bound to,
  30. * which aren't port 1900 so the MS service doesn't steal them. While the caller can specify a local
  31. * port to use, we will default to 0 which allows the underlying system to auto-assign a free port.
  32. */
  33. private object _BroadcastListenSocketSynchroniser = new();
  34. private List<Socket> _MulticastListenSockets;
  35. private object _SendSocketSynchroniser = new();
  36. private List<Socket> _sendSockets;
  37. private HttpRequestParser _RequestParser;
  38. private HttpResponseParser _ResponseParser;
  39. private readonly ILogger _logger;
  40. private ISocketFactory _SocketFactory;
  41. private readonly INetworkManager _networkManager;
  42. private int _LocalPort;
  43. private int _MulticastTtl;
  44. private bool _IsShared;
  45. /// <summary>
  46. /// Raised when a HTTPU request message is received by a socket (unicast or multicast).
  47. /// </summary>
  48. public event EventHandler<RequestReceivedEventArgs> RequestReceived;
  49. /// <summary>
  50. /// Raised when an HTTPU response message is received by a socket (unicast or multicast).
  51. /// </summary>
  52. public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
  53. /// <summary>
  54. /// Minimum constructor.
  55. /// </summary>
  56. /// <exception cref="ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  57. public SsdpCommunicationsServer(
  58. ISocketFactory socketFactory,
  59. INetworkManager networkManager,
  60. ILogger logger)
  61. : this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive, networkManager, logger)
  62. {
  63. }
  64. /// <summary>
  65. /// Full constructor.
  66. /// </summary>
  67. /// <exception cref="ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  68. /// <exception cref="ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
  69. public SsdpCommunicationsServer(
  70. ISocketFactory socketFactory,
  71. int localPort,
  72. int multicastTimeToLive,
  73. INetworkManager networkManager,
  74. ILogger logger)
  75. {
  76. if (socketFactory is null)
  77. {
  78. throw new ArgumentNullException(nameof(socketFactory));
  79. }
  80. if (multicastTimeToLive <= 0)
  81. {
  82. throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero.");
  83. }
  84. _BroadcastListenSocketSynchroniser = new();
  85. _SendSocketSynchroniser = new();
  86. _LocalPort = localPort;
  87. _SocketFactory = socketFactory;
  88. _RequestParser = new();
  89. _ResponseParser = new();
  90. _MulticastTtl = multicastTimeToLive;
  91. _networkManager = networkManager;
  92. _logger = logger;
  93. }
  94. /// <summary>
  95. /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
  96. /// </summary>
  97. /// <exception cref="ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  98. public void BeginListeningForMulticast()
  99. {
  100. ThrowIfDisposed();
  101. lock (_BroadcastListenSocketSynchroniser)
  102. {
  103. if (_MulticastListenSockets is null)
  104. {
  105. try
  106. {
  107. _MulticastListenSockets = CreateMulticastSocketsAndListen();
  108. }
  109. catch (SocketException ex)
  110. {
  111. _logger.LogError("Failed to bind to multicast address: {Message}. DLNA will be unavailable", ex.Message);
  112. }
  113. catch (Exception ex)
  114. {
  115. _logger.LogError(ex, "Error in BeginListeningForMulticast");
  116. }
  117. }
  118. }
  119. }
  120. /// <summary>
  121. /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
  122. /// </summary>
  123. /// <exception cref="ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  124. public void StopListeningForMulticast()
  125. {
  126. lock (_BroadcastListenSocketSynchroniser)
  127. {
  128. if (_MulticastListenSockets is not null)
  129. {
  130. _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name);
  131. foreach (var socket in _MulticastListenSockets)
  132. {
  133. socket.Dispose();
  134. }
  135. _MulticastListenSockets = null;
  136. }
  137. }
  138. }
  139. /// <summary>
  140. /// Sends a message to a particular address (uni or multicast) and port.
  141. /// </summary>
  142. public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
  143. {
  144. if (messageData is null)
  145. {
  146. throw new ArgumentNullException(nameof(messageData));
  147. }
  148. ThrowIfDisposed();
  149. var sockets = GetSendSockets(fromlocalIPAddress, destination);
  150. if (sockets.Count == 0)
  151. {
  152. return;
  153. }
  154. // SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
  155. for (var i = 0; i < SsdpConstants.UdpResendCount; i++)
  156. {
  157. var tasks = sockets.Select(s => SendFromSocket(s, messageData, destination, cancellationToken)).ToArray();
  158. await Task.WhenAll(tasks).ConfigureAwait(false);
  159. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  160. }
  161. }
  162. private async Task SendFromSocket(Socket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken)
  163. {
  164. try
  165. {
  166. await socket.SendToAsync(messageData, destination, cancellationToken).ConfigureAwait(false);
  167. }
  168. catch (ObjectDisposedException)
  169. {
  170. }
  171. catch (OperationCanceledException)
  172. {
  173. }
  174. catch (Exception ex)
  175. {
  176. var localIP = ((IPEndPoint)socket.LocalEndPoint).Address;
  177. _logger.LogError(ex, "Error sending socket message from {0} to {1}", localIP.ToString(), destination.ToString());
  178. }
  179. }
  180. private List<Socket> GetSendSockets(IPAddress fromlocalIPAddress, IPEndPoint destination)
  181. {
  182. EnsureSendSocketCreated();
  183. lock (_SendSocketSynchroniser)
  184. {
  185. var sockets = _sendSockets.Where(s => s.AddressFamily == fromlocalIPAddress.AddressFamily);
  186. // Send from the Any socket and the socket with the matching address
  187. if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetwork)
  188. {
  189. sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any)
  190. || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress));
  191. // If sending to the loopback address, filter the socket list as well
  192. if (destination.Address.Equals(IPAddress.Loopback))
  193. {
  194. sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any)
  195. || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback));
  196. }
  197. }
  198. else if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetworkV6)
  199. {
  200. sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any)
  201. || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress));
  202. // If sending to the loopback address, filter the socket list as well
  203. if (destination.Address.Equals(IPAddress.IPv6Loopback))
  204. {
  205. sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any)
  206. || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Loopback));
  207. }
  208. }
  209. return sockets.ToList();
  210. }
  211. }
  212. public Task SendMulticastMessage(string message, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
  213. {
  214. return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromlocalIPAddress, cancellationToken);
  215. }
  216. /// <summary>
  217. /// Sends a message to the SSDP multicast address and port.
  218. /// </summary>
  219. public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
  220. {
  221. if (message is null)
  222. {
  223. throw new ArgumentNullException(nameof(message));
  224. }
  225. byte[] messageData = Encoding.UTF8.GetBytes(message);
  226. ThrowIfDisposed();
  227. cancellationToken.ThrowIfCancellationRequested();
  228. EnsureSendSocketCreated();
  229. // SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
  230. for (var i = 0; i < sendCount; i++)
  231. {
  232. await SendMessageIfSocketNotDisposed(
  233. messageData,
  234. new IPEndPoint(
  235. IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress),
  236. SsdpConstants.MulticastPort),
  237. fromlocalIPAddress,
  238. cancellationToken).ConfigureAwait(false);
  239. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  240. }
  241. }
  242. /// <summary>
  243. /// Stops listening for search responses on the local, unicast socket.
  244. /// </summary>
  245. /// <exception cref="ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  246. public void StopListeningForResponses()
  247. {
  248. lock (_SendSocketSynchroniser)
  249. {
  250. if (_sendSockets is not null)
  251. {
  252. var sockets = _sendSockets.ToList();
  253. _sendSockets = null;
  254. _logger.LogInformation("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count);
  255. foreach (var socket in sockets)
  256. {
  257. var socketAddress = ((IPEndPoint)socket.LocalEndPoint).Address;
  258. _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socketAddress);
  259. socket.Dispose();
  260. }
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocator"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
  266. /// </summary>
  267. /// <remarks>
  268. /// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocator"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para>
  269. /// </remarks>
  270. public bool IsShared
  271. {
  272. get { return _IsShared; }
  273. set { _IsShared = value; }
  274. }
  275. /// <summary>
  276. /// Stops listening for requests, disposes this instance and all internal resources.
  277. /// </summary>
  278. /// <param name="disposing"></param>
  279. protected override void Dispose(bool disposing)
  280. {
  281. if (disposing)
  282. {
  283. StopListeningForMulticast();
  284. StopListeningForResponses();
  285. }
  286. }
  287. private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
  288. {
  289. var sockets = _sendSockets;
  290. if (sockets is not null)
  291. {
  292. sockets = sockets.ToList();
  293. var tasks = sockets.Where(s => fromlocalIPAddress is null || fromlocalIPAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address))
  294. .Select(s => SendFromSocket(s, messageData, destination, cancellationToken));
  295. return Task.WhenAll(tasks);
  296. }
  297. return Task.CompletedTask;
  298. }
  299. private List<Socket> CreateMulticastSocketsAndListen()
  300. {
  301. var sockets = new List<Socket>();
  302. var multicastGroupAddress = IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress);
  303. // IPv6 is currently unsupported
  304. var validInterfaces = _networkManager.GetInternalBindAddresses()
  305. .Where(x => x.Address is not null)
  306. .Where(x => x.SupportsMulticast)
  307. .Where(x => x.AddressFamily == AddressFamily.InterNetwork)
  308. .DistinctBy(x => x.Index);
  309. foreach (var intf in validInterfaces)
  310. {
  311. try
  312. {
  313. var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, intf, _MulticastTtl, SsdpConstants.MulticastPort);
  314. _ = ListenToSocketInternal(socket);
  315. sockets.Add(socket);
  316. }
  317. catch (Exception ex)
  318. {
  319. _logger.LogError(ex, "Failed to create SSDP UDP multicast socket for {0} on interface {1} (index {2})", intf.Address, intf.Name, intf.Index);
  320. }
  321. }
  322. return sockets;
  323. }
  324. private List<Socket> CreateSendSockets()
  325. {
  326. var sockets = new List<Socket>();
  327. // IPv6 is currently unsupported
  328. var validInterfaces = _networkManager.GetInternalBindAddresses()
  329. .Where(x => x.Address is not null)
  330. .Where(x => x.SupportsMulticast)
  331. .Where(x => x.AddressFamily == AddressFamily.InterNetwork);
  332. if (OperatingSystem.IsMacOS())
  333. {
  334. // Manually remove loopback on macOS due to https://github.com/dotnet/runtime/issues/24340
  335. validInterfaces = validInterfaces.Where(x => !x.Address.Equals(IPAddress.Loopback));
  336. }
  337. foreach (var intf in validInterfaces)
  338. {
  339. try
  340. {
  341. var socket = _SocketFactory.CreateSsdpUdpSocket(intf, _LocalPort);
  342. _ = ListenToSocketInternal(socket);
  343. sockets.Add(socket);
  344. }
  345. catch (Exception ex)
  346. {
  347. _logger.LogError(ex, "Failed to create SSDP UDP sender socket for {0} on interface {1} (index {2})", intf.Address, intf.Name, intf.Index);
  348. }
  349. }
  350. return sockets;
  351. }
  352. private async Task ListenToSocketInternal(Socket socket)
  353. {
  354. var cancelled = false;
  355. var receiveBuffer = new byte[8192];
  356. while (!cancelled && !IsDisposed)
  357. {
  358. try
  359. {
  360. var result = await socket.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, _LocalPort), CancellationToken.None).ConfigureAwait(false);;
  361. if (result.ReceivedBytes > 0)
  362. {
  363. var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint;
  364. var localEndpointAdapter = _networkManager.GetAllBindInterfaces().First(a => a.Index == result.PacketInformation.Interface);
  365. ProcessMessage(
  366. Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes),
  367. remoteEndpoint,
  368. localEndpointAdapter.Address);
  369. }
  370. }
  371. catch (ObjectDisposedException)
  372. {
  373. cancelled = true;
  374. }
  375. catch (TaskCanceledException)
  376. {
  377. cancelled = true;
  378. }
  379. }
  380. }
  381. private void EnsureSendSocketCreated()
  382. {
  383. if (_sendSockets is null)
  384. {
  385. lock (_SendSocketSynchroniser)
  386. {
  387. _sendSockets ??= CreateSendSockets();
  388. }
  389. }
  390. }
  391. private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnlocalIPAddress)
  392. {
  393. // Responses start with the HTTP version, prefixed with HTTP/ while
  394. // requests start with a method which can vary and might be one we haven't
  395. // seen/don't know. We'll check if this message is a request or a response
  396. // by checking for the HTTP/ prefix on the start of the message.
  397. _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnlocalIPAddress, data);
  398. if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
  399. {
  400. HttpResponseMessage responseMessage = null;
  401. try
  402. {
  403. responseMessage = _ResponseParser.Parse(data);
  404. }
  405. catch (ArgumentException)
  406. {
  407. // Ignore invalid packets.
  408. }
  409. if (responseMessage is not null)
  410. {
  411. OnResponseReceived(responseMessage, endPoint, receivedOnlocalIPAddress);
  412. }
  413. }
  414. else
  415. {
  416. HttpRequestMessage requestMessage = null;
  417. try
  418. {
  419. requestMessage = _RequestParser.Parse(data);
  420. }
  421. catch (ArgumentException)
  422. {
  423. // Ignore invalid packets.
  424. }
  425. if (requestMessage is not null)
  426. {
  427. OnRequestReceived(requestMessage, endPoint, receivedOnlocalIPAddress);
  428. }
  429. }
  430. }
  431. private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnlocalIPAddress)
  432. {
  433. // SSDP specification says only * is currently used but other uri's might
  434. // be implemented in the future and should be ignored unless understood.
  435. // Section 4.2 - http://tools.ietf.org/html/draft-cai-ssdp-v1-03#page-11
  436. if (data.RequestUri.ToString() != "*")
  437. {
  438. return;
  439. }
  440. var handlers = RequestReceived;
  441. if (handlers is not null)
  442. {
  443. handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnlocalIPAddress));
  444. }
  445. }
  446. private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIPAddress)
  447. {
  448. var handlers = ResponseReceived;
  449. if (handlers is not null)
  450. {
  451. handlers(this, new ResponseReceivedEventArgs(data, endPoint)
  452. {
  453. LocalIPAddress = localIPAddress
  454. });
  455. }
  456. }
  457. }
  458. }