HostProgram.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. using System.Collections.Concurrent;
  2. using System.IO.Compression;
  3. using System.Net;
  4. using System.Net.WebSockets;
  5. using System.Runtime.CompilerServices;
  6. using System.Text;
  7. internal static class HostProgram
  8. {
  9. private static readonly ConcurrentDictionary<string, LoadedModule> Modules = new();
  10. private static readonly ConcurrentDictionary<int, WebSocket> Sessions = new();
  11. private static LoadedModule _defaultModule;
  12. private static List<byte[]> _historyMessage = new();
  13. private static bool _isLoading;
  14. private static bool _isRunning;
  15. private static DateTime _lastRequestAccepted;
  16. private static int _requestIdStore = 0;
  17. private static void Main(string[] args)
  18. {
  19. Console.WriteLine("Starting...");
  20. var tWorker = new Thread(Working);
  21. _isRunning = true;
  22. tWorker.Start();
  23. Task.Run(ReloadConfig);
  24. Console.WriteLine("Press ENTER to Stop.");
  25. Console.ReadLine();
  26. Console.WriteLine("Shutting down...");
  27. _isRunning = false;
  28. tWorker.Join();
  29. Console.WriteLine("Stopped.");
  30. Console.WriteLine();
  31. Console.Write("Press ENTER to Exit.");
  32. Console.ReadLine();
  33. }
  34. private static void ReloadConfig()
  35. {
  36. if (_isLoading)
  37. {
  38. Console.WriteLine("Still loading, SKIP");
  39. return;
  40. }
  41. _isLoading = true;
  42. try
  43. {
  44. ConfigFile.Reload();
  45. ReloadModulesInternal();
  46. }
  47. catch (Exception e)
  48. {
  49. Console.WriteLine($"Load error: {e}");
  50. }
  51. _isLoading = false;
  52. }
  53. private static void ReloadModulesInternal()
  54. {
  55. Modules.Clear();
  56. _defaultModule = null;
  57. if (ConfigFile.Instance.Modules?.Any() == true)
  58. {
  59. foreach (var modEnt in ConfigFile.Instance.Modules)
  60. {
  61. Console.WriteLine($"Loading module `{modEnt.Value.DisplayText}'...");
  62. var module = new LoadedModule
  63. {
  64. VirtualPath = modEnt.Key,
  65. DisplayText = modEnt.Value.DisplayText,
  66. DefaultDocument = modEnt.Value.DefaultDocument,
  67. EnableFallbackRoute = modEnt.Value.EnableFallbackRoute,
  68. HtmlBaseReplace = modEnt.Value.HtmlBaseReplace,
  69. Files = new Dictionary<string, byte[]>()
  70. };
  71. if (Directory.Exists(modEnt.Value.Path))
  72. {
  73. //load by fs
  74. var files = Directory.GetFiles(modEnt.Value.Path, "*", System.IO.SearchOption.AllDirectories);
  75. foreach (var item in files)
  76. {
  77. var k = item.Substring(modEnt.Value.Path.Length + 1).Replace("\\", "/").ToLower();
  78. module.Files[k] = File.ReadAllBytes(item);
  79. }
  80. }
  81. else if (File.Exists(modEnt.Value.Path))
  82. {
  83. //load by package
  84. using var arc = SharpCompress.Archives.ArchiveFactory.Open(modEnt.Value.Path);
  85. foreach (var ent in arc.Entries.Where(p => p.IsDirectory == false))
  86. {
  87. var buf = new byte[ent.Size];
  88. using var s = ent.OpenEntryStream();
  89. var r = s.Read(buf, 0, buf.Length);
  90. module.Files[ent.Key.ToLower()] = buf;
  91. }
  92. }
  93. else
  94. {
  95. Console.WriteLine("WARN: resource not found");
  96. continue;
  97. }
  98. if (modEnt.Value.IsDefault && _defaultModule == null) _defaultModule = module;
  99. Modules[modEnt.Key] = module;
  100. Console.WriteLine($"Module `{modEnt.Value.DisplayText}' loaded.");
  101. }
  102. }
  103. }
  104. private static void Working()
  105. {
  106. var listener = new HttpListener();
  107. listener.Prefixes.Add(ConfigFile.Instance.ListenPrefix);
  108. listener.Start();
  109. var upTime = DateTime.Now;
  110. Console.WriteLine($"HTTP Server started, listening on {ConfigFile.Instance.ListenPrefix}");
  111. listener.BeginGetContext(ContextGet, listener);
  112. _lastRequestAccepted = DateTime.Now;
  113. while (_isRunning)
  114. {
  115. var timeSpan = DateTime.Now - _lastRequestAccepted;
  116. var up = DateTime.Now - upTime;
  117. Console.Title =
  118. "SimWebCha"
  119. + $" UP {up.Days:00}D {up.Hours:00}H {up.Minutes:00}M {up.Seconds:00}S {up.Milliseconds:000}"
  120. + $" / "
  121. + $" LA {timeSpan.Days:00}D {timeSpan.Hours:00}H {timeSpan.Minutes:00}M {timeSpan.Seconds:00}S {timeSpan.Milliseconds:000}"
  122. ;
  123. Thread.Sleep(1000);
  124. }
  125. listener.Close();
  126. Thread.Sleep(1000);
  127. }
  128. private static void ContextGet(IAsyncResult ar)
  129. {
  130. var listener = (HttpListener)ar.AsyncState;
  131. HttpListenerContext context;
  132. try
  133. {
  134. context = listener.EndGetContext(ar);
  135. }
  136. catch (Exception e)
  137. {
  138. Console.WriteLine(e);
  139. return;
  140. }
  141. if (_isRunning) listener.BeginGetContext(ContextGet, listener);
  142. ProcessRequest(context);
  143. }
  144. private static void ProcessRequest(HttpListenerContext context)
  145. {
  146. _lastRequestAccepted = DateTime.Now;
  147. var request = context.Request;
  148. var currentSessionId = Interlocked.Increment(ref _requestIdStore);
  149. Console.WriteLine($"Request #{currentSessionId:00000} from {request.RemoteEndPoint} {request.HttpMethod} {request.RawUrl}");
  150. try
  151. {
  152. var requestPath = request.Url.LocalPath.ToLower();
  153. var pathParts = (IReadOnlyList<string>)requestPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  154. if (requestPath == "/" && _defaultModule != null)
  155. {
  156. if (_defaultModule.EnableFallbackRoute) context.Response.Redirect($"/modules/{_defaultModule.VirtualPath}/");
  157. else context.Response.Redirect($"/modules/{_defaultModule.VirtualPath}/{_defaultModule.DefaultDocument}");
  158. }
  159. else if (requestPath == "/connect" && request.IsWebSocketRequest)
  160. {
  161. var wsc = context.AcceptWebSocketAsync("swcp").Result;
  162. Console.WriteLine($"Request #{currentSessionId:00000} WebSocket Session Start");
  163. var sck = Sessions[currentSessionId] = wsc.WebSocket;
  164. var buffer = new byte[1024];
  165. try
  166. {
  167. var r = sck.ReceiveAsync(buffer, default).Result;
  168. var s = Encoding.UTF8.GetString(buffer, 0, r.Count);
  169. byte[][] copy;
  170. lock (_historyMessage) copy = _historyMessage.ToArray();
  171. foreach (var item in copy)
  172. {
  173. sck.SendAsync(item, WebSocketMessageType.Text, true, default).Wait();
  174. }
  175. BroadCast($"SYS{Environment.NewLine}" +
  176. $" Session #{currentSessionId:X4}({s}) Connected.{Environment.NewLine}" +
  177. $" Now number of online session: {Sessions.Count}");
  178. while (true)
  179. {
  180. r = sck.ReceiveAsync(buffer, default).Result;
  181. if (r.Count == 0)
  182. {
  183. break;
  184. }
  185. else
  186. {
  187. s = Encoding.UTF8.GetString(buffer, 0, r.Count);
  188. BroadCast($"#{currentSessionId:X4}{Environment.NewLine} {s}");
  189. }
  190. }
  191. }
  192. catch (Exception)
  193. {
  194. try
  195. {
  196. if (sck.State != WebSocketState.Aborted)
  197. {
  198. sck.CloseAsync(WebSocketCloseStatus.InternalServerError, "Error", default).Wait();
  199. }
  200. }
  201. catch (Exception e)
  202. {
  203. Console.WriteLine(e);
  204. }
  205. }
  206. }
  207. else if (requestPath.StartsWith("/modules/") && pathParts.Count > 1)
  208. {
  209. var moduleKey = pathParts[1];
  210. if (Modules.TryGetValue(moduleKey, out var module))
  211. {
  212. var entPath = string.Join("/", pathParts.Skip(2));
  213. void Output(byte[] bin)
  214. {
  215. if (entPath.ToLower().EndsWith(".js")) context.Response.ContentType = "application/javascript";
  216. else if (module.HtmlBaseReplace != null && entPath.ToLower().EndsWith(".html"))
  217. {
  218. //base replace
  219. var html = Encoding.UTF8.GetString(bin);
  220. var r = html.Replace(module.HtmlBaseReplace, $"<base href=\"/modules/{moduleKey}/\" />");
  221. bin = Encoding.UTF8.GetBytes(r);
  222. }
  223. context.Response.OutputStream.Write(bin, 0, bin.Length);
  224. }
  225. if (module.Files.TryGetValue(entPath, out var bin))
  226. {
  227. Output(bin);
  228. }
  229. else if (module.EnableFallbackRoute && module.Files.TryGetValue(module.DefaultDocument, out var defBin))
  230. {
  231. entPath = module.DefaultDocument;
  232. Output(defBin);
  233. }
  234. else context.Response.StatusCode = 404;
  235. }
  236. else context.Response.StatusCode = 404;
  237. }
  238. else if (requestPath == "/admin/" && false == request.QueryString.AllKeys.Contains("action"))
  239. {
  240. var sb = new StringBuilder();
  241. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  242. sb.Append($"<title> Admin - {ConfigFile.Instance.Title} </title>");
  243. sb.Append("<body bgColor=skyBlue>");
  244. sb.Append($"<h3>Admin</h3>");
  245. sb.Append("<div><a href=/>Back to home</a></div>");
  246. sb.Append($"<form method=GET>");
  247. sb.Append($"Password: <input type=password name=pass />");
  248. sb.Append($"<br/>");
  249. sb.Append($"Operation: ");
  250. sb.Append($"<input type=submit name=action value=Reload /> ");
  251. sb.Append($"</form>");
  252. context.WriteTextUtf8(sb.ToString());
  253. }
  254. else if (requestPath == "/admin/" && request.QueryString["action"] == "Reload" && request.QueryString["pass"] == ConfigFile.Instance.AdminPassword)
  255. {
  256. Task.Run(ReloadConfig);
  257. context.Response.Redirect("/");
  258. }
  259. else if (requestPath == "/admin/")
  260. {
  261. context.Response.Redirect("/");
  262. }
  263. else
  264. {
  265. context.Response.StatusCode = 404;
  266. }
  267. }
  268. catch (Exception e)
  269. {
  270. Console.WriteLine(e);
  271. try
  272. {
  273. context.Response.StatusCode = 500;
  274. }
  275. catch (Exception exception)
  276. {
  277. Console.WriteLine(exception);
  278. }
  279. }
  280. finally
  281. {
  282. try
  283. {
  284. if (request.IsWebSocketRequest)
  285. {
  286. Sessions.Remove(currentSessionId, out _);
  287. BroadCast($"SYS{Environment.NewLine}" +
  288. $" Session #{currentSessionId:X4} Disconnected.{Environment.NewLine}" +
  289. $" Now number of online session: {Sessions.Count}");
  290. }
  291. Console.WriteLine($"Request #{currentSessionId:0000} ends with status code: {context.Response.StatusCode}");
  292. }
  293. catch (Exception e)
  294. {
  295. Console.WriteLine(e);
  296. }
  297. try
  298. {
  299. context.Response.Close();
  300. }
  301. catch (Exception e)
  302. {
  303. Console.WriteLine(e);
  304. }
  305. }
  306. }
  307. private static void BroadCast(string content)
  308. {
  309. var now = DateTime.Now;
  310. string text = $"{now} {content}";
  311. var buf = Encoding.UTF8.GetBytes(text);
  312. lock (_historyMessage)
  313. {
  314. _historyMessage.Add(buf);
  315. while (_historyMessage.Count >= ConfigFile.Instance.HistoryMessageLength)
  316. {
  317. _historyMessage.RemoveAt(0);
  318. }
  319. }
  320. if (Sessions.Count == 0) return;
  321. foreach (var item in Sessions)
  322. {
  323. try
  324. {
  325. if (item.Value.State == WebSocketState.Open)
  326. {
  327. item.Value.SendAsync(buf, WebSocketMessageType.Text, true, default);
  328. }
  329. else
  330. {
  331. Sessions.Remove(item.Key, out _);
  332. BroadCast($"SYS{Environment.NewLine}" +
  333. $" Session #{item.Key:X4} Disconnected.{Environment.NewLine}" +
  334. $" Now number of online session: {Sessions.Count}");
  335. }
  336. }
  337. catch (Exception e)
  338. {
  339. Console.WriteLine(e);
  340. }
  341. }
  342. }
  343. public static void WriteTextUtf8(this HttpListenerContext context, string content, string contentType = "text/html")
  344. {
  345. var bytes = Encoding.UTF8.GetBytes(content);
  346. context.Response.ContentEncoding = Encoding.UTF8;
  347. context.Response.ContentType = contentType;
  348. if (true == context.Request.Headers["Accept-Encoding"]?.Contains("gzip"))
  349. {
  350. context.Response.AddHeader("Content-Encoding", "gzip");
  351. var memoryStream = new MemoryStream(bytes);
  352. var gZipStream = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, false);
  353. memoryStream.CopyTo(gZipStream);
  354. gZipStream.Flush();
  355. }
  356. else
  357. {
  358. context.Response.OutputStream.Write(bytes);
  359. }
  360. }
  361. }
  362. internal class LoadedModule
  363. {
  364. public string VirtualPath { get; set; }
  365. public string DisplayText { get; set; }
  366. public string DefaultDocument { get; set; }
  367. public Dictionary<string, byte[]> Files { get; set; }
  368. public bool EnableFallbackRoute { get; set; }
  369. public string HtmlBaseReplace { get; set; }
  370. }