SsdpCommunicationsServer.cs 22 KB

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