SsdpCommunicationsServer.cs 20 KB

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