OSHttpRequestPump.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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.Collections.Specialized;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using log4net;
  35. using HttpServer;
  36. namespace OpenSim.Framework.Servers
  37. {
  38. /// <summary>
  39. /// An OSHttpRequestPump fetches incoming OSHttpRequest objects
  40. /// from the OSHttpRequestQueue and feeds them to all subscribed
  41. /// parties. Each OSHttpRequestPump encapsulates one thread to do
  42. /// the work and there is a fixed number of pumps for each
  43. /// OSHttpServer object.
  44. /// </summary>
  45. public class OSHttpRequestPump
  46. {
  47. private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. protected OSHttpServer _server;
  49. protected OSHttpRequestQueue _queue;
  50. protected Thread _engine;
  51. private int _id;
  52. public string EngineID
  53. {
  54. get { return String.Format("{0}-{1}", _server.EngineID, _id); }
  55. }
  56. public OSHttpRequestPump()
  57. {
  58. _engine = new Thread(new ThreadStart(Engine));
  59. _engine.Name = EngineID;
  60. _engine.IsBackground = true;
  61. _engine.Start();
  62. ThreadTracker.Add(_engine);
  63. }
  64. public static OSHttpRequestPump[] Pumps(OSHttpServer server, OSHttpRequestQueue queue, int poolSize)
  65. {
  66. OSHttpRequestPump[] pumps = new OSHttpRequestPump[poolSize];
  67. for (int i = 0; i < pumps.Length; i++)
  68. {
  69. pumps[i]._server = server;
  70. pumps[i]._queue = queue;
  71. pumps[i]._id = i;
  72. }
  73. return pumps;
  74. }
  75. public void Start()
  76. {
  77. _engine = new Thread(new ThreadStart(Engine));
  78. _engine.Name = EngineID;
  79. _engine.IsBackground = true;
  80. _engine.Start();
  81. ThreadTracker.Add(_engine);
  82. }
  83. public void Engine()
  84. {
  85. OSHttpRequest req = null;
  86. while (true)
  87. {
  88. try {
  89. // dequeue an OSHttpRequest from OSHttpServer's
  90. // request queue
  91. req = _queue.Dequeue();
  92. // get a copy of the list of registered handlers
  93. List<OSHttpHandler> handlers = _server.OSHttpHandlers;
  94. // prune list and have it sorted from most
  95. // specific to least specific
  96. handlers = MatchHandlers(req, handlers);
  97. // process req: we try each handler in turn until
  98. // we are either out of handlers or get back a
  99. // Handled or Detached
  100. OSHttpHandlerResult rc = OSHttpHandlerResult.Unprocessed;
  101. foreach (OSHttpHandler h in handlers)
  102. {
  103. rc = h.Process(req);
  104. // Pass: handler did not process the request,
  105. // try next handler
  106. if (OSHttpHandlerResult.Pass == rc) continue;
  107. // Detached: handler is taking over processing
  108. // of request, we are done
  109. if (OSHttpHandlerResult.Detached == rc) break;
  110. if (OSHttpHandlerResult.Handled != rc)
  111. {
  112. // something went wrong
  113. throw new Exception(String.Format("[{0}] got unexpected OSHttpHandlerResult {1}", EngineID, rc));
  114. }
  115. // Handled: clean up now
  116. req.HttpRequest.AddHeader("keep-alive", "false");
  117. break;
  118. }
  119. }
  120. catch (Exception e)
  121. {
  122. _log.DebugFormat("[{0}] OSHttpHandler problem: {1}", EngineID, e.ToString());
  123. _log.ErrorFormat("[{0}] OSHttpHandler problem: {1}", EngineID, e.Message);
  124. }
  125. }
  126. }
  127. protected List<OSHttpHandler> MatchHandlers(OSHttpRequest req, List<OSHttpHandler> handlers)
  128. {
  129. Dictionary<OSHttpHandler, int> scoredHandlers = new Dictionary<OSHttpHandler, int>();
  130. foreach (OSHttpHandler h in handlers)
  131. {
  132. Regex pathRegex = h.Path;
  133. Dictionary<string, Regex> headerRegexs = h.Headers;
  134. Regex endPointsRegex = h.IPEndPointWhitelist;
  135. // first, check whether IPEndPointWhitelist applies
  136. // and, if it does, whether client is on that white
  137. // list.
  138. if (null != endPointsRegex)
  139. {
  140. // TODO: following code requires code changes to
  141. // HttpServer.HttpRequest to become functional
  142. IPEndPoint remote = req.RemoteIPEndPoint;
  143. if (null != remote)
  144. {
  145. Match epm = endPointsRegex.Match(remote.ToString());
  146. if (!epm.Success) continue;
  147. }
  148. }
  149. // whitelist ok, now check path
  150. if (null != pathRegex)
  151. {
  152. Match m = pathRegex.Match(req.HttpRequest.Uri.AbsolutePath);
  153. if (!m.Success) continue;
  154. scoredHandlers[h] = m.ToString().Length;
  155. }
  156. // whitelist & path ok, now check headers
  157. if (null != headerRegexs)
  158. {
  159. int headersMatch = 0;
  160. // go through all header Regexs and evaluate
  161. // match:
  162. // if header field not present or does not match:
  163. // remove handler from scoredHandlers
  164. // continue
  165. // else:
  166. // add increment headersMatch
  167. NameValueCollection headers = req.HttpRequest.Headers;
  168. foreach (string tag in headerRegexs.Keys)
  169. {
  170. if (null != headers[tag])
  171. {
  172. Match hm = headerRegexs[tag].Match(headers[tag]);
  173. if (hm.Success) {
  174. headersMatch++;
  175. continue;
  176. }
  177. }
  178. scoredHandlers.Remove(h);
  179. break;
  180. }
  181. // check whether h got kicked out
  182. if (!scoredHandlers.ContainsKey(h)) continue;
  183. scoredHandlers[h] += headersMatch;
  184. }
  185. }
  186. List<OSHttpHandler> matchingHandlers = new List<OSHttpHandler>(scoredHandlers.Keys);
  187. matchingHandlers.Sort(delegate(OSHttpHandler x, OSHttpHandler y)
  188. {
  189. return scoredHandlers[x] - scoredHandlers[y];
  190. });
  191. return matchingHandlers;
  192. }
  193. }
  194. }