Listener.cs 7.1 KB

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