TcpManager.cs 16 KB

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