Listener.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using GenHTTP.Api.Content;
  2. using GenHTTP.Api.Infrastructure;
  3. using GenHTTP.Api.Protocol;
  4. using GenHTTP.Engine;
  5. using GenHTTP.Modules.Practices;
  6. using InABox.API;
  7. using InABox.Core;
  8. using NPOI.SS.Formula.Functions;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics.CodeAnalysis;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Security.Cryptography.X509Certificates;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. using System.Timers;
  19. namespace PRSServer.Engines
  20. {
  21. public abstract class Handler<TProperties> : IHandler
  22. {
  23. public IHandler Parent { get; set; }
  24. public abstract void Init(TProperties properties);
  25. public abstract ValueTask<IResponse?> HandleAsync(IRequest request);
  26. public ValueTask PrepareAsync()
  27. {
  28. return new ValueTask();
  29. }
  30. public IEnumerable<ContentElement> GetContent(IRequest request)
  31. {
  32. return Enumerable.Empty<ContentElement>();
  33. }
  34. }
  35. public class HandlerBuilder<THandler, TProperties> : IHandlerBuilder<HandlerBuilder<THandler, TProperties>>
  36. where THandler : Handler<TProperties>, new()
  37. {
  38. private readonly List<IConcernBuilder> _Concerns = new();
  39. public HandlerBuilder(TProperties properties)
  40. {
  41. Properties = properties;
  42. }
  43. private TProperties Properties;
  44. public HandlerBuilder<THandler, TProperties> Add(IConcernBuilder concern)
  45. {
  46. _Concerns.Add(concern);
  47. return this;
  48. }
  49. public IHandler Build(IHandler parent)
  50. {
  51. return Concerns.Chain(parent, _Concerns, p => {
  52. var handler = new THandler { Parent = p };
  53. handler.Init(Properties);
  54. return handler;
  55. });
  56. }
  57. }
  58. public class Listener<THandler, TProperties>
  59. where THandler : Handler<TProperties>, new()
  60. where TProperties : notnull
  61. {
  62. private X509Certificate2? certificate;
  63. private Timer? CertificateRefreshTimer;
  64. private Timer? CertificateHaltTimer;
  65. private string? CertificateFile;
  66. private ushort Port;
  67. private IServerHost host;
  68. private TProperties Properties;
  69. public Listener(TProperties properties)
  70. {
  71. Init(properties);
  72. }
  73. [MemberNotNull("host", "Properties")]
  74. public void Init(TProperties properties)
  75. {
  76. Properties = properties;
  77. host = Host.Create()
  78. .Console()
  79. .Handler(new HandlerBuilder<THandler, TProperties>(properties))
  80. .Defaults();
  81. }
  82. public void InitCertificate(ushort port, X509Certificate2 certificate)
  83. {
  84. this.certificate = certificate;
  85. host.Bind(IPAddress.Any, port, certificate);
  86. }
  87. public void InitPort(ushort port)
  88. {
  89. Port = port;
  90. host.Bind(IPAddress.Any, port);
  91. }
  92. public void InitHTTPS(ushort port, string certificateFile)
  93. {
  94. Port = port;
  95. var useHTTP = true;
  96. if (File.Exists(certificateFile))
  97. {
  98. Logger.Send(LogType.Information, "", "Certificate found; verifying HTTPS Certificate");
  99. try
  100. {
  101. var certificate = new X509Certificate2(certificateFile);
  102. if (certificate.NotAfter > DateTime.Now)
  103. {
  104. var names = certificate.GetNameInfo(X509NameType.DnsName, false);
  105. Logger.Send(LogType.Information, "", $"Certificate valid for {names}");
  106. CertificateFile = certificateFile;
  107. InitCertificate(port, certificate);
  108. useHTTP = false;
  109. }
  110. else
  111. {
  112. Logger.Send(LogType.Error, "", "HTTPS Certificate has expired, using HTTP instead");
  113. }
  114. }
  115. catch (Exception)
  116. {
  117. Logger.Send(LogType.Error, "", "Error validating HTTPS Certificate, using HTTP instead");
  118. }
  119. }
  120. if (useHTTP)
  121. {
  122. InitPort(port);
  123. }
  124. else
  125. {
  126. if (CertificateRefreshTimer == null)
  127. {
  128. CertificateRefreshTimer = new Timer(1000 * 60 * 60 * 24);
  129. CertificateRefreshTimer.Elapsed += CertificateTimer_Elapsed;
  130. CertificateRefreshTimer.AutoReset = true;
  131. }
  132. CertificateRefreshTimer.Start();
  133. }
  134. }
  135. public void Start()
  136. {
  137. host.Start();
  138. }
  139. public void Stop()
  140. {
  141. host.Stop();
  142. }
  143. private void Restart()
  144. {
  145. Clear();
  146. Init(Properties);
  147. if(CertificateFile != null)
  148. {
  149. InitHTTPS(Port, CertificateFile);
  150. }
  151. else
  152. {
  153. InitPort(Port);
  154. }
  155. Start();
  156. }
  157. /// <summary>
  158. /// Clears certificate and host information, and stops the listener.
  159. /// </summary>
  160. private void Clear()
  161. {
  162. host?.Stop();
  163. certificate = null;
  164. }
  165. #region Certificate Management
  166. private void CertificateTimer_Elapsed(object? sender, ElapsedEventArgs e)
  167. {
  168. if (certificate != null)
  169. {
  170. X509Certificate2? cert = null;
  171. if (File.Exists(CertificateFile))
  172. {
  173. cert = new X509Certificate2(CertificateFile);
  174. }
  175. if (cert != null && cert.NotAfter > certificate.NotAfter && cert.NotAfter > DateTime.Now)
  176. {
  177. Logger.Send(LogType.Information, "", "HTTPS Certificate with greater expiry date found; restarting HTTPS listener...");
  178. Restart();
  179. }
  180. var expiry = certificate.NotAfter;
  181. var untilExpiry = expiry - DateTime.Now;
  182. if (untilExpiry.TotalDays <= 7)
  183. {
  184. SendCertificateExpiryNotification(expiry);
  185. if (untilExpiry.TotalDays <= 1)
  186. {
  187. CertificateRefreshTimer?.Stop();
  188. CertificateHaltTimer = new Timer(untilExpiry.TotalMilliseconds);
  189. CertificateHaltTimer.Elapsed += HTTPS_Halt_Elapsed;
  190. CertificateHaltTimer.AutoReset = false;
  191. CertificateHaltTimer.Start();
  192. }
  193. }
  194. }
  195. }
  196. private void SendCertificateExpiryNotification(DateTime expiry)
  197. {
  198. string message;
  199. if (expiry.Date == DateTime.Now.Date)
  200. {
  201. message = $"HTTPS Certificate will expire today at {expiry.TimeOfDay:hh\\:mm}";
  202. }
  203. else
  204. {
  205. message = $"HTTPS Certificate will expire in {(expiry - DateTime.Now).Days} at {expiry:dd/MM/yyyy hh:mm}";
  206. }
  207. Logger.Send(LogType.Information, "", message);
  208. }
  209. /// <summary>
  210. /// Restarts listener in HTTP mode
  211. /// </summary>
  212. /// <param name="sender"></param>
  213. /// <param name="e"></param>
  214. private void HTTPS_Halt_Elapsed(object? sender, ElapsedEventArgs e)
  215. {
  216. CertificateHaltTimer?.Dispose();
  217. CertificateHaltTimer = null;
  218. Logger.Send(LogType.Information, "", "Expiry of certificate reached; restarting HTTPS listener...");
  219. Restart();
  220. }
  221. #endregion
  222. }
  223. }