TcpManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. using Alchemy;
  2. using Alchemy.Classes;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Serialization;
  5. using MediaBrowser.Model.Configuration;
  6. using MediaBrowser.Model.Logging;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Sockets;
  14. using System.Net.WebSockets;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Kernel
  20. {
  21. /// <summary>
  22. /// Manages the Http Server, Udp Server and WebSocket connections
  23. /// </summary>
  24. public class TcpManager : BaseManager<IKernel>
  25. {
  26. /// <summary>
  27. /// This is the udp server used for server discovery by clients
  28. /// </summary>
  29. /// <value>The UDP server.</value>
  30. private UdpServer UdpServer { get; set; }
  31. /// <summary>
  32. /// Gets or sets the UDP listener.
  33. /// </summary>
  34. /// <value>The UDP listener.</value>
  35. private IDisposable UdpListener { get; set; }
  36. /// <summary>
  37. /// Both the Ui and server will have a built-in HttpServer.
  38. /// People will inevitably want remote control apps so it's needed in the Ui too.
  39. /// </summary>
  40. /// <value>The HTTP server.</value>
  41. public HttpServer HttpServer { get; private set; }
  42. /// <summary>
  43. /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
  44. /// </summary>
  45. /// <value>The HTTP listener.</value>
  46. private IDisposable HttpListener { get; set; }
  47. /// <summary>
  48. /// The web socket connections
  49. /// </summary>
  50. private readonly List<WebSocketConnection> _webSocketConnections = new List<WebSocketConnection>();
  51. /// <summary>
  52. /// Gets or sets the external web socket server.
  53. /// </summary>
  54. /// <value>The external web socket server.</value>
  55. private WebSocketServer ExternalWebSocketServer { get; set; }
  56. /// <summary>
  57. /// The _logger
  58. /// </summary>
  59. private readonly ILogger _logger;
  60. /// <summary>
  61. /// The _application host
  62. /// </summary>
  63. private readonly IApplicationHost _applicationHost;
  64. /// <summary>
  65. /// The _supports native web socket
  66. /// </summary>
  67. private bool? _supportsNativeWebSocket;
  68. /// <summary>
  69. /// Gets a value indicating whether [supports web socket].
  70. /// </summary>
  71. /// <value><c>true</c> if [supports web socket]; otherwise, <c>false</c>.</value>
  72. internal bool SupportsNativeWebSocket
  73. {
  74. get
  75. {
  76. if (!_supportsNativeWebSocket.HasValue)
  77. {
  78. try
  79. {
  80. new ClientWebSocket();
  81. _supportsNativeWebSocket = true;
  82. }
  83. catch (PlatformNotSupportedException)
  84. {
  85. _supportsNativeWebSocket = false;
  86. }
  87. }
  88. return _supportsNativeWebSocket.Value;
  89. }
  90. }
  91. /// <summary>
  92. /// Gets the web socket port number.
  93. /// </summary>
  94. /// <value>The web socket port number.</value>
  95. public int WebSocketPortNumber
  96. {
  97. get { return SupportsNativeWebSocket ? Kernel.Configuration.HttpServerPortNumber : Kernel.Configuration.LegacyWebSocketPortNumber; }
  98. }
  99. /// <summary>
  100. /// Initializes a new instance of the <see cref="TcpManager" /> class.
  101. /// </summary>
  102. /// <param name="applicationHost">The application host.</param>
  103. /// <param name="kernel">The kernel.</param>
  104. /// <param name="logger">The logger.</param>
  105. public TcpManager(IApplicationHost applicationHost, IKernel kernel, ILogger logger)
  106. : base(kernel)
  107. {
  108. _logger = logger;
  109. _applicationHost = applicationHost;
  110. if (kernel.IsFirstRun)
  111. {
  112. RegisterServerWithAdministratorAccess();
  113. }
  114. ReloadUdpServer();
  115. ReloadHttpServer();
  116. if (!SupportsNativeWebSocket)
  117. {
  118. ReloadExternalWebSocketServer();
  119. }
  120. }
  121. /// <summary>
  122. /// Starts the external web socket server.
  123. /// </summary>
  124. private void ReloadExternalWebSocketServer()
  125. {
  126. // Avoid windows firewall prompts in the ui
  127. if (Kernel.KernelContext != KernelContext.Server)
  128. {
  129. return;
  130. }
  131. DisposeExternalWebSocketServer();
  132. ExternalWebSocketServer = new WebSocketServer(Kernel.Configuration.LegacyWebSocketPortNumber, IPAddress.Any)
  133. {
  134. OnConnected = OnAlchemyWebSocketClientConnected,
  135. TimeOut = TimeSpan.FromMinutes(60)
  136. };
  137. ExternalWebSocketServer.Start();
  138. _logger.Info("Alchemy Web Socket Server started");
  139. }
  140. /// <summary>
  141. /// Called when [alchemy web socket client connected].
  142. /// </summary>
  143. /// <param name="context">The context.</param>
  144. private void OnAlchemyWebSocketClientConnected(UserContext context)
  145. {
  146. var connection = new WebSocketConnection(new AlchemyWebSocket(context, _logger), context.ClientAddress, ProcessWebSocketMessageReceived, _logger);
  147. _webSocketConnections.Add(connection);
  148. }
  149. /// <summary>
  150. /// Restarts the Http Server, or starts it if not currently running
  151. /// </summary>
  152. /// <param name="registerServerOnFailure">if set to <c>true</c> [register server on failure].</param>
  153. public void ReloadHttpServer(bool registerServerOnFailure = true)
  154. {
  155. // Only reload if the port has changed, so that we don't disconnect any active users
  156. if (HttpServer != null && HttpServer.UrlPrefix.Equals(Kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  157. {
  158. return;
  159. }
  160. DisposeHttpServer();
  161. _logger.Info("Loading Http Server");
  162. try
  163. {
  164. HttpServer = new HttpServer(Kernel.HttpServerUrlPrefix, "Media Browser", _applicationHost, Kernel, _logger);
  165. }
  166. catch (HttpListenerException ex)
  167. {
  168. _logger.ErrorException("Error starting Http Server", ex);
  169. if (registerServerOnFailure)
  170. {
  171. RegisterServerWithAdministratorAccess();
  172. // Don't get stuck in a loop
  173. ReloadHttpServer(false);
  174. return;
  175. }
  176. throw;
  177. }
  178. HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
  179. }
  180. /// <summary>
  181. /// Handles the WebSocketConnected event of the HttpServer control.
  182. /// </summary>
  183. /// <param name="sender">The source of the event.</param>
  184. /// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
  185. void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
  186. {
  187. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, ProcessWebSocketMessageReceived, _logger);
  188. _webSocketConnections.Add(connection);
  189. }
  190. /// <summary>
  191. /// Processes the web socket message received.
  192. /// </summary>
  193. /// <param name="result">The result.</param>
  194. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  195. {
  196. var tasks = Kernel.WebSocketListeners.Select(i => Task.Run(async () =>
  197. {
  198. try
  199. {
  200. await i.ProcessMessage(result).ConfigureAwait(false);
  201. }
  202. catch (Exception ex)
  203. {
  204. _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
  205. }
  206. }));
  207. await Task.WhenAll(tasks).ConfigureAwait(false);
  208. }
  209. /// <summary>
  210. /// Starts or re-starts the udp server
  211. /// </summary>
  212. private void ReloadUdpServer()
  213. {
  214. // For now, there's no reason to keep reloading this over and over
  215. if (UdpServer != null)
  216. {
  217. return;
  218. }
  219. // Avoid windows firewall prompts in the ui
  220. if (Kernel.KernelContext != KernelContext.Server)
  221. {
  222. return;
  223. }
  224. DisposeUdpServer();
  225. try
  226. {
  227. // The port number can't be in configuration because we don't want it to ever change
  228. UdpServer = new UdpServer(new IPEndPoint(IPAddress.Any, Kernel.UdpServerPortNumber));
  229. }
  230. catch (SocketException ex)
  231. {
  232. _logger.ErrorException("Failed to start UDP Server", ex);
  233. return;
  234. }
  235. UdpListener = UdpServer.Subscribe(async res =>
  236. {
  237. var expectedMessage = String.Format("who is MediaBrowser{0}?", Kernel.KernelContext);
  238. var expectedMessageBytes = Encoding.UTF8.GetBytes(expectedMessage);
  239. if (expectedMessageBytes.SequenceEqual(res.Buffer))
  240. {
  241. _logger.Info("Received UDP server request from " + res.RemoteEndPoint.ToString());
  242. // Send a response back with our ip address and port
  243. var response = String.Format("MediaBrowser{0}|{1}:{2}", Kernel.KernelContext, NetUtils.GetLocalIpAddress(), Kernel.UdpServerPortNumber);
  244. await UdpServer.SendAsync(response, res.RemoteEndPoint);
  245. }
  246. });
  247. }
  248. /// <summary>
  249. /// Sends a message to all clients currently connected via a web socket
  250. /// </summary>
  251. /// <typeparam name="T"></typeparam>
  252. /// <param name="messageType">Type of the message.</param>
  253. /// <param name="data">The data.</param>
  254. /// <returns>Task.</returns>
  255. public void SendWebSocketMessage<T>(string messageType, T data)
  256. {
  257. SendWebSocketMessage(messageType, () => data);
  258. }
  259. /// <summary>
  260. /// Sends a message to all clients currently connected via a web socket
  261. /// </summary>
  262. /// <typeparam name="T"></typeparam>
  263. /// <param name="messageType">Type of the message.</param>
  264. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  265. public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
  266. {
  267. Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
  268. }
  269. /// <summary>
  270. /// Sends a message to all clients currently connected via a web socket
  271. /// </summary>
  272. /// <typeparam name="T"></typeparam>
  273. /// <param name="messageType">Type of the message.</param>
  274. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  275. /// <param name="cancellationToken">The cancellation token.</param>
  276. /// <returns>Task.</returns>
  277. /// <exception cref="System.ArgumentNullException">messageType</exception>
  278. public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
  279. {
  280. if (string.IsNullOrEmpty(messageType))
  281. {
  282. throw new ArgumentNullException("messageType");
  283. }
  284. if (dataFunction == null)
  285. {
  286. throw new ArgumentNullException("dataFunction");
  287. }
  288. if (cancellationToken == null)
  289. {
  290. throw new ArgumentNullException("cancellationToken");
  291. }
  292. cancellationToken.ThrowIfCancellationRequested();
  293. var connections = _webSocketConnections.Where(s => s.State == WebSocketState.Open).ToList();
  294. if (connections.Count > 0)
  295. {
  296. _logger.Info("Sending web socket message {0}", messageType);
  297. var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
  298. var bytes = JsonSerializer.SerializeToBytes(message);
  299. var tasks = connections.Select(s => Task.Run(() =>
  300. {
  301. try
  302. {
  303. s.SendAsync(bytes, cancellationToken);
  304. }
  305. catch (OperationCanceledException)
  306. {
  307. throw;
  308. }
  309. catch (Exception ex)
  310. {
  311. _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
  312. }
  313. }));
  314. await Task.WhenAll(tasks).ConfigureAwait(false);
  315. }
  316. }
  317. /// <summary>
  318. /// Disposes the udp server
  319. /// </summary>
  320. private void DisposeUdpServer()
  321. {
  322. if (UdpServer != null)
  323. {
  324. UdpServer.Dispose();
  325. }
  326. if (UdpListener != null)
  327. {
  328. UdpListener.Dispose();
  329. }
  330. }
  331. /// <summary>
  332. /// Disposes the current HttpServer
  333. /// </summary>
  334. private void DisposeHttpServer()
  335. {
  336. foreach (var socket in _webSocketConnections)
  337. {
  338. // Dispose the connection
  339. socket.Dispose();
  340. }
  341. _webSocketConnections.Clear();
  342. if (HttpServer != null)
  343. {
  344. _logger.Info("Disposing Http Server");
  345. HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
  346. HttpServer.Dispose();
  347. }
  348. if (HttpListener != null)
  349. {
  350. HttpListener.Dispose();
  351. }
  352. DisposeExternalWebSocketServer();
  353. }
  354. /// <summary>
  355. /// Registers the server with administrator access.
  356. /// </summary>
  357. private void RegisterServerWithAdministratorAccess()
  358. {
  359. // Create a temp file path to extract the bat file to
  360. var tmpFile = Path.Combine(Kernel.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
  361. // Extract the bat file
  362. using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Common.Kernel.RegisterServer.bat"))
  363. {
  364. using (var fileStream = File.Create(tmpFile))
  365. {
  366. stream.CopyTo(fileStream);
  367. }
  368. }
  369. var startInfo = new ProcessStartInfo
  370. {
  371. FileName = tmpFile,
  372. Arguments = string.Format("{0} {1} {2} {3}", Kernel.Configuration.HttpServerPortNumber,
  373. Kernel.HttpServerUrlPrefix,
  374. Kernel.UdpServerPortNumber,
  375. Kernel.Configuration.LegacyWebSocketPortNumber),
  376. CreateNoWindow = true,
  377. WindowStyle = ProcessWindowStyle.Hidden,
  378. Verb = "runas",
  379. ErrorDialog = false
  380. };
  381. using (var process = Process.Start(startInfo))
  382. {
  383. process.WaitForExit();
  384. }
  385. }
  386. /// <summary>
  387. /// Releases unmanaged and - optionally - managed resources.
  388. /// </summary>
  389. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  390. protected override void Dispose(bool dispose)
  391. {
  392. if (dispose)
  393. {
  394. DisposeUdpServer();
  395. DisposeHttpServer();
  396. }
  397. base.Dispose(dispose);
  398. }
  399. /// <summary>
  400. /// Disposes the external web socket server.
  401. /// </summary>
  402. private void DisposeExternalWebSocketServer()
  403. {
  404. if (ExternalWebSocketServer != null)
  405. {
  406. ExternalWebSocketServer.Dispose();
  407. }
  408. }
  409. /// <summary>
  410. /// Called when [application configuration changed].
  411. /// </summary>
  412. /// <param name="oldConfig">The old config.</param>
  413. /// <param name="newConfig">The new config.</param>
  414. public void OnApplicationConfigurationChanged(BaseApplicationConfiguration oldConfig, BaseApplicationConfiguration newConfig)
  415. {
  416. if (oldConfig.HttpServerPortNumber != newConfig.HttpServerPortNumber)
  417. {
  418. ReloadHttpServer();
  419. }
  420. if (!SupportsNativeWebSocket && oldConfig.LegacyWebSocketPortNumber != newConfig.LegacyWebSocketPortNumber)
  421. {
  422. ReloadExternalWebSocketServer();
  423. }
  424. }
  425. }
  426. }