HttpContextFactory.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Concurrent;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Security;
  7. using System.Net.Sockets;
  8. using System.Security.Authentication;
  9. using System.Security.Cryptography.X509Certificates;
  10. namespace OSHttpServer
  11. {
  12. /// <summary>
  13. /// Used to create and reuse contexts.
  14. /// </summary>
  15. public class HttpContextFactory : IHttpContextFactory
  16. {
  17. private readonly ConcurrentDictionary<int, HttpClientContext> m_activeContexts = new ConcurrentDictionary<int, HttpClientContext>();
  18. private readonly ILogWriter m_logWriter;
  19. /// <summary>
  20. /// A request have been received from one of the contexts.
  21. /// </summary>
  22. public event EventHandler<RequestEventArgs> RequestReceived;
  23. /// <summary>
  24. /// Initializes a new instance of the <see cref="HttpContextFactory"/> class.
  25. /// </summary>
  26. /// <param name="writer">The writer.</param>
  27. /// <param name="bufferSize">Amount of bytes to read from the incoming socket stream.</param>
  28. /// <param name="factory">Used to create a request parser.</param>
  29. public HttpContextFactory(ILogWriter writer)
  30. {
  31. m_logWriter = writer;
  32. ContextTimeoutManager.Start();
  33. }
  34. /// <summary>
  35. /// Create a new context.
  36. /// </summary>
  37. /// <param name="isSecured">true if socket is running HTTPS.</param>
  38. /// <param name="endPoint">Client that connected</param>
  39. /// <param name="stream">Network/SSL stream.</param>
  40. /// <returns>A context.</returns>
  41. protected HttpClientContext CreateContext(bool isSecured, IPEndPoint endPoint, Stream stream, Socket sock)
  42. {
  43. var context = new HttpClientContext(isSecured, endPoint, stream, m_logWriter, sock);
  44. context.Disconnected += OnFreeContext;
  45. context.RequestReceived += OnRequestReceived;
  46. ContextTimeoutManager.StartMonitoringContext(context);
  47. m_activeContexts[context.contextID] = context;
  48. context.Start();
  49. return context;
  50. }
  51. private void OnRequestReceived(object sender, RequestEventArgs e)
  52. {
  53. RequestReceived?.Invoke(sender, e);
  54. }
  55. private void OnFreeContext(object sender, DisconnectedEventArgs e)
  56. {
  57. var imp = sender as HttpClientContext;
  58. if (imp == null || imp.contextID < 0)
  59. return;
  60. m_activeContexts.TryRemove(imp.contextID, out HttpClientContext dummy);
  61. imp.Close();
  62. }
  63. #region IHttpContextFactory Members
  64. /// <summary>
  65. /// Create a secure <see cref="IHttpClientContext"/>.
  66. /// </summary>
  67. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  68. /// <param name="certificate">HTTPS certificate to use.</param>
  69. /// <param name="protocol">Kind of HTTPS protocol. Usually TLS or SSL.</param>
  70. /// <returns>
  71. /// A created <see cref="IHttpClientContext"/>.
  72. /// </returns>
  73. public IHttpClientContext CreateSecureContext(Socket socket, X509Certificate certificate,
  74. SslProtocols protocol, RemoteCertificateValidationCallback _clientCallback = null)
  75. {
  76. var networkStream = new NetworkStream(socket, true);
  77. var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
  78. SslStream sslStream = null;
  79. try
  80. {
  81. if (_clientCallback == null)
  82. {
  83. sslStream = new SslStream(networkStream, false);
  84. sslStream.AuthenticateAsServer(certificate, false, protocol, false);
  85. }
  86. else
  87. {
  88. sslStream = new SslStream(networkStream, false,
  89. new RemoteCertificateValidationCallback(_clientCallback));
  90. sslStream.AuthenticateAsServer(certificate, true, protocol, false);
  91. }
  92. }
  93. catch (Exception e)
  94. {
  95. m_logWriter.Write(this, LogPrio.Error, e.Message);
  96. sslStream.Close();
  97. return null;
  98. }
  99. return CreateContext(true, remoteEndPoint, sslStream, socket);
  100. }
  101. /// <summary>
  102. /// Creates a <see cref="IHttpClientContext"/> that handles a connected client.
  103. /// </summary>
  104. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  105. /// <returns>
  106. /// A creates <see cref="IHttpClientContext"/>.
  107. /// </returns>
  108. public IHttpClientContext CreateContext(Socket socket)
  109. {
  110. var networkStream = new NetworkStream(socket, true);
  111. var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
  112. return CreateContext(false, remoteEndPoint, networkStream, socket);
  113. }
  114. #endregion
  115. /// <summary>
  116. /// Server is shutting down so shut down the factory
  117. /// </summary>
  118. public void Shutdown()
  119. {
  120. ContextTimeoutManager.Stop();
  121. }
  122. }
  123. /// <summary>
  124. /// Used to create <see cref="IHttpClientContext"/>es.
  125. /// </summary>
  126. public interface IHttpContextFactory
  127. {
  128. /// <summary>
  129. /// Creates a <see cref="IHttpClientContext"/> that handles a connected client.
  130. /// </summary>
  131. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  132. /// <returns>A creates <see cref="IHttpClientContext"/>.</returns>
  133. IHttpClientContext CreateContext(Socket socket);
  134. /// <summary>
  135. /// Create a secure <see cref="IHttpClientContext"/>.
  136. /// </summary>
  137. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  138. /// <param name="certificate">HTTPS certificate to use.</param>
  139. /// <param name="protocol">Kind of HTTPS protocol. Usually TLS or SSL.</param>
  140. /// <returns>A created <see cref="IHttpClientContext"/>.</returns>
  141. IHttpClientContext CreateSecureContext(Socket socket, X509Certificate certificate,
  142. SslProtocols protocol, RemoteCertificateValidationCallback _clientCallback = null);
  143. /// <summary>
  144. /// A request have been received from one of the contexts.
  145. /// </summary>
  146. event EventHandler<RequestEventArgs> RequestReceived;
  147. /// <summary>
  148. /// Server is shutting down so shut down the factory
  149. /// </summary>
  150. void Shutdown();
  151. }
  152. }