HttpContextFactory.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 IRequestParserFactory m_parserfactory;
  19. private readonly ILogWriter m_logWriter;
  20. /// <summary>
  21. /// A request have been received from one of the contexts.
  22. /// </summary>
  23. public event EventHandler<RequestEventArgs> RequestReceived;
  24. /// <summary>
  25. /// Initializes a new instance of the <see cref="HttpContextFactory"/> class.
  26. /// </summary>
  27. /// <param name="writer">The writer.</param>
  28. /// <param name="bufferSize">Amount of bytes to read from the incoming socket stream.</param>
  29. /// <param name="factory">Used to create a request parser.</param>
  30. public HttpContextFactory(ILogWriter writer, IRequestParserFactory factory)
  31. {
  32. m_logWriter = writer;
  33. m_parserfactory = factory;
  34. ContextTimeoutManager.Start();
  35. }
  36. /// <summary>
  37. /// Create a new context.
  38. /// </summary>
  39. /// <param name="isSecured">true if socket is running HTTPS.</param>
  40. /// <param name="endPoint">Client that connected</param>
  41. /// <param name="stream">Network/SSL stream.</param>
  42. /// <returns>A context.</returns>
  43. protected HttpClientContext CreateContext(bool isSecured, IPEndPoint endPoint, Stream stream, Socket sock)
  44. {
  45. HttpClientContext context;
  46. context = CreateNewContext(isSecured, endPoint, stream, sock);
  47. context.Disconnected += OnFreeContext;
  48. context.RequestReceived += OnRequestReceived;
  49. context.Stream = stream;
  50. context.IsSecured = isSecured;
  51. context.RemotePort = endPoint.Port.ToString();
  52. context.RemoteAddress = endPoint.Address.ToString();
  53. ContextTimeoutManager.StartMonitoringContext(context);
  54. m_activeContexts[context.contextID] = context;
  55. context.Start();
  56. return context;
  57. }
  58. /// <summary>
  59. /// Create a new context.
  60. /// </summary>
  61. /// <param name="isSecured">true if HTTPS is used.</param>
  62. /// <param name="endPoint">Remote client</param>
  63. /// <param name="stream">Network stream, <see cref="HttpClientContext"/></param>
  64. /// <returns>A new context (always).</returns>
  65. protected virtual HttpClientContext CreateNewContext(bool isSecured, IPEndPoint endPoint, Stream stream, Socket sock)
  66. {
  67. return new HttpClientContext(isSecured, endPoint, stream, m_parserfactory, sock);
  68. }
  69. private void OnRequestReceived(object sender, RequestEventArgs e)
  70. {
  71. RequestReceived?.Invoke(sender, e);
  72. }
  73. private void OnFreeContext(object sender, DisconnectedEventArgs e)
  74. {
  75. var imp = sender as HttpClientContext;
  76. if (imp == null || imp.contextID < 0)
  77. return;
  78. m_activeContexts.TryRemove(imp.contextID, out HttpClientContext dummy);
  79. imp.Close();
  80. }
  81. #region IHttpContextFactory Members
  82. /// <summary>
  83. /// Create a secure <see cref="IHttpClientContext"/>.
  84. /// </summary>
  85. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  86. /// <param name="certificate">HTTPS certificate to use.</param>
  87. /// <param name="protocol">Kind of HTTPS protocol. Usually TLS or SSL.</param>
  88. /// <returns>
  89. /// A created <see cref="IHttpClientContext"/>.
  90. /// </returns>
  91. public IHttpClientContext CreateSecureContext(Socket socket, X509Certificate certificate,
  92. SslProtocols protocol, RemoteCertificateValidationCallback _clientCallback = null)
  93. {
  94. socket.NoDelay = true;
  95. var networkStream = new NetworkStream(socket, true);
  96. var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
  97. SslStream sslStream = null;
  98. try
  99. {
  100. if (_clientCallback == null)
  101. {
  102. sslStream = new SslStream(networkStream, false);
  103. sslStream.AuthenticateAsServer(certificate, false, protocol, false);
  104. }
  105. else
  106. {
  107. sslStream = new SslStream(networkStream, false,
  108. new RemoteCertificateValidationCallback(_clientCallback));
  109. sslStream.AuthenticateAsServer(certificate, true, protocol, false);
  110. }
  111. }
  112. catch (Exception e)
  113. {
  114. m_logWriter.Write(this, LogPrio.Error, e.Message);
  115. sslStream.Close();
  116. return null;
  117. }
  118. return CreateContext(true, remoteEndPoint, sslStream, socket);
  119. }
  120. /// <summary>
  121. /// Creates a <see cref="IHttpClientContext"/> that handles a connected client.
  122. /// </summary>
  123. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  124. /// <returns>
  125. /// A creates <see cref="IHttpClientContext"/>.
  126. /// </returns>
  127. public IHttpClientContext CreateContext(Socket socket)
  128. {
  129. socket.NoDelay = true;
  130. var networkStream = new NetworkStream(socket, true);
  131. var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
  132. return CreateContext(false, remoteEndPoint, networkStream, socket);
  133. }
  134. #endregion
  135. /// <summary>
  136. /// Server is shutting down so shut down the factory
  137. /// </summary>
  138. public void Shutdown()
  139. {
  140. ContextTimeoutManager.Stop();
  141. }
  142. }
  143. /// <summary>
  144. /// Used to create <see cref="IHttpClientContext"/>es.
  145. /// </summary>
  146. public interface IHttpContextFactory
  147. {
  148. /// <summary>
  149. /// Creates a <see cref="IHttpClientContext"/> that handles a connected client.
  150. /// </summary>
  151. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  152. /// <returns>A creates <see cref="IHttpClientContext"/>.</returns>
  153. IHttpClientContext CreateContext(Socket socket);
  154. /// <summary>
  155. /// Create a secure <see cref="IHttpClientContext"/>.
  156. /// </summary>
  157. /// <param name="socket">Client socket (accepted by the <see cref="OSHttpListener"/>).</param>
  158. /// <param name="certificate">HTTPS certificate to use.</param>
  159. /// <param name="protocol">Kind of HTTPS protocol. Usually TLS or SSL.</param>
  160. /// <returns>A created <see cref="IHttpClientContext"/>.</returns>
  161. IHttpClientContext CreateSecureContext(Socket socket, X509Certificate certificate,
  162. SslProtocols protocol, RemoteCertificateValidationCallback _clientCallback = null);
  163. /// <summary>
  164. /// A request have been received from one of the contexts.
  165. /// </summary>
  166. event EventHandler<RequestEventArgs> RequestReceived;
  167. /// <summary>
  168. /// Server is shutting down so shut down the factory
  169. /// </summary>
  170. void Shutdown();
  171. }
  172. }