OSHttpServer.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Net;
  30. using System.Net.Sockets;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using System.Security.Cryptography.X509Certificates;
  35. using log4net;
  36. using HttpServer;
  37. using HttpListener = HttpServer.HttpListener;
  38. namespace OpenSim.Framework.Servers
  39. {
  40. /// <summary>
  41. /// OSHttpServer provides an HTTP server bound to a specific
  42. /// port. When instantiated with just address and port it uses
  43. /// normal HTTP, when instantiated with address, port, and X509
  44. /// certificate, it uses HTTPS.
  45. /// </summary>
  46. public class OSHttpServer
  47. {
  48. private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private object _syncObject = new object();
  50. // underlying HttpServer.HttpListener
  51. protected HttpListener _listener;
  52. // underlying core/engine thread
  53. protected Thread _engine;
  54. // Queue containing (OS)HttpRequests
  55. protected OSHttpRequestQueue _queue;
  56. // OSHttpRequestPumps "pumping" incoming OSHttpRequests
  57. // upwards
  58. protected OSHttpRequestPump[] _pumps;
  59. // thread identifier
  60. protected string _engineId;
  61. public string EngineID
  62. {
  63. get { return _engineId; }
  64. }
  65. /// <summary>
  66. /// True if this is an HTTPS connection; false otherwise.
  67. /// </summary>
  68. protected bool _isSecure;
  69. public bool IsSecure
  70. {
  71. get { return _isSecure; }
  72. }
  73. public int QueueSize
  74. {
  75. get { return _pumps.Length; }
  76. }
  77. /// <summary>
  78. /// List of registered OSHttpHandlers for this OSHttpServer instance.
  79. /// </summary>
  80. protected List<OSHttpHandler> _httpHandlers = new List<OSHttpHandler>();
  81. public List<OSHttpHandler> OSHttpHandlers
  82. {
  83. get
  84. {
  85. lock (_httpHandlers)
  86. {
  87. return new List<OSHttpHandler>(_httpHandlers);
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// Instantiate an HTTP server.
  93. /// </summary>
  94. public OSHttpServer(IPAddress address, int port, int poolSize)
  95. {
  96. _engineId = String.Format("OSHttpServer (HTTP:{0})", port);
  97. _isSecure = false;
  98. _log.DebugFormat("[{0}] HTTP server instantiated", EngineID);
  99. _listener = new HttpListener(address, port);
  100. _queue = new OSHttpRequestQueue();
  101. _pumps = OSHttpRequestPump.Pumps(this, _queue, poolSize);
  102. }
  103. /// <summary>
  104. /// Instantiate an HTTPS server.
  105. /// </summary>
  106. public OSHttpServer(IPAddress address, int port, X509Certificate certificate, int poolSize)
  107. {
  108. _engineId = String.Format("OSHttpServer [HTTPS:{0}/ps:{1}]", port, poolSize);
  109. _isSecure = true;
  110. _log.DebugFormat("[{0}] HTTPS server instantiated", EngineID);
  111. _listener = new HttpListener(address, port, certificate);
  112. _queue = new OSHttpRequestQueue();
  113. _pumps = OSHttpRequestPump.Pumps(this, _queue, poolSize);
  114. }
  115. /// <summary>
  116. /// Turn an HttpRequest into an OSHttpRequestItem and place it
  117. /// in the queue. The OSHttpRequestQueue object will pulse the
  118. /// next available idle pump.
  119. /// </summary>
  120. protected void OnHttpRequest(HttpClientContext client, HttpRequest request)
  121. {
  122. // turn request into OSHttpRequest
  123. OSHttpRequest req = new OSHttpRequest(client, request);
  124. // place OSHttpRequest into _httpRequestQueue, will
  125. // trigger Pulse to idle waiting pumps
  126. _queue.Enqueue(req);
  127. }
  128. /// <summary>
  129. /// Start the HTTP server engine.
  130. /// </summary>
  131. public void Start()
  132. {
  133. _engine = new Thread(new ThreadStart(Engine));
  134. _engine.Name = _engineId;
  135. _engine.IsBackground = true;
  136. _engine.Start();
  137. ThreadTracker.Add(_engine);
  138. // start the pumps...
  139. for (int i = 0; i < _pumps.Length; i++)
  140. _pumps[i].Start();
  141. }
  142. public void Stop()
  143. {
  144. lock (_syncObject) Monitor.Pulse(_syncObject);
  145. }
  146. /// <summary>
  147. /// Engine keeps the HTTP server running.
  148. /// </summary>
  149. private void Engine()
  150. {
  151. try {
  152. _listener.RequestHandler += OnHttpRequest;
  153. _listener.Start(QueueSize);
  154. _log.InfoFormat("[{0}] HTTP server started", EngineID);
  155. lock (_syncObject) Monitor.Wait(_syncObject);
  156. }
  157. catch (Exception ex)
  158. {
  159. _log.DebugFormat("[{0}] HTTP server startup failed: {1}", EngineID, ex.ToString());
  160. }
  161. _log.InfoFormat("[{0}] HTTP server terminated", EngineID);
  162. }
  163. /// <summary>
  164. /// Add an HTTP request handler.
  165. /// </summary>
  166. /// <param name="handler">OSHttpHandler delegate</param>
  167. /// <param name="path">regex object for path matching</parm>
  168. /// <param name="headers">dictionary containing header names
  169. /// and regular expressions to match against header values</param>
  170. public void AddHandler(OSHttpHandler handler)
  171. {
  172. lock (_httpHandlers)
  173. {
  174. if (_httpHandlers.Contains(handler))
  175. {
  176. _log.DebugFormat("[OSHttpServer] attempt to add already existing handler ignored");
  177. return;
  178. }
  179. _httpHandlers.Add(handler);
  180. }
  181. }
  182. }
  183. }