OSHttpRequestPump.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. // #define DEBUGGING
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Net;
  34. using System.Reflection;
  35. using System.Text.RegularExpressions;
  36. using System.Threading;
  37. using log4net;
  38. using HttpServer;
  39. namespace OpenSim.Framework.Servers
  40. {
  41. /// <summary>
  42. /// An OSHttpRequestPump fetches incoming OSHttpRequest objects
  43. /// from the OSHttpRequestQueue and feeds them to all subscribed
  44. /// parties. Each OSHttpRequestPump encapsulates one thread to do
  45. /// the work and there is a fixed number of pumps for each
  46. /// OSHttpServer object.
  47. /// </summary>
  48. public class OSHttpRequestPump
  49. {
  50. private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. protected OSHttpServer _server;
  52. protected OSHttpRequestQueue _queue;
  53. protected Thread _engine;
  54. private int _id;
  55. public string EngineID
  56. {
  57. get { return String.Format("{0} pump {1}", _server.EngineID, _id); }
  58. }
  59. public OSHttpRequestPump(OSHttpServer server, OSHttpRequestQueue queue, int id)
  60. {
  61. _server = server;
  62. _queue = queue;
  63. _id = id;
  64. _engine = new Thread(new ThreadStart(Engine));
  65. _engine.Name = EngineID;
  66. _engine.IsBackground = true;
  67. _engine.Start();
  68. ThreadTracker.Add(_engine);
  69. }
  70. public static OSHttpRequestPump[] Pumps(OSHttpServer server, OSHttpRequestQueue queue, int poolSize)
  71. {
  72. OSHttpRequestPump[] pumps = new OSHttpRequestPump[poolSize];
  73. for (int i = 0; i < pumps.Length; i++)
  74. {
  75. pumps[i] = new OSHttpRequestPump(server, queue, i);
  76. }
  77. return pumps;
  78. }
  79. public void Start()
  80. {
  81. _engine = new Thread(new ThreadStart(Engine));
  82. _engine.Name = EngineID;
  83. _engine.IsBackground = true;
  84. _engine.Start();
  85. ThreadTracker.Add(_engine);
  86. }
  87. public void Engine()
  88. {
  89. OSHttpRequest req = null;
  90. while (true)
  91. {
  92. try {
  93. // dequeue an OSHttpRequest from OSHttpServer's
  94. // request queue
  95. req = _queue.Dequeue();
  96. // get a copy of the list of registered handlers
  97. List<OSHttpHandler> handlers = _server.OSHttpHandlers;
  98. // prune list and have it sorted from most
  99. // specific to least specific
  100. handlers = MatchHandlers(req, handlers);
  101. // process req: we try each handler in turn until
  102. // we are either out of handlers or get back a
  103. // Pass or Done
  104. OSHttpHandlerResult rc = OSHttpHandlerResult.Unprocessed;
  105. foreach (OSHttpHandler h in handlers)
  106. {
  107. rc = h.Process(req);
  108. // Pass: handler did not process the request,
  109. // try next handler
  110. if (OSHttpHandlerResult.Pass == rc) continue;
  111. // Handled: handler has processed the request
  112. if (OSHttpHandlerResult.Done == rc) break;
  113. // hmm, something went wrong
  114. throw new Exception(String.Format("[{0}] got unexpected OSHttpHandlerResult {1}", EngineID, rc));
  115. }
  116. if (OSHttpHandlerResult.Unprocessed == rc)
  117. {
  118. _log.InfoFormat("[{0}] OSHttpHandler: no handler registered for {1}", EngineID, req);
  119. // set up response header
  120. OSHttpResponse resp = new OSHttpResponse(req);
  121. resp.StatusCode = (int)OSHttpStatusCode.ClientErrorNotFound;
  122. resp.StatusDescription = String.Format("no handler on call for {0}", req);
  123. resp.ContentType = "text/html";
  124. // add explanatory message
  125. StreamWriter body = new StreamWriter(resp.Body);
  126. body.WriteLine("<html>");
  127. body.WriteLine("<header><title>Ooops...</title><header>");
  128. body.WriteLine(String.Format("<body><p>{0}</p></body>", resp.StatusDescription));
  129. body.WriteLine("</html>");
  130. body.Flush();
  131. // and ship it back
  132. resp.Send();
  133. }
  134. }
  135. catch (Exception e)
  136. {
  137. _log.DebugFormat("[{0}] OSHttpHandler problem: {1}", EngineID, e.ToString());
  138. _log.ErrorFormat("[{0}] OSHttpHandler problem: {1}", EngineID, e.Message);
  139. }
  140. }
  141. }
  142. protected List<OSHttpHandler> MatchHandlers(OSHttpRequest req, List<OSHttpHandler> handlers)
  143. {
  144. Dictionary<OSHttpHandler, int> scoredHandlers = new Dictionary<OSHttpHandler, int>();
  145. _log.DebugFormat("[{0}] MatchHandlers for {1}", EngineID, req);
  146. foreach (OSHttpHandler h in handlers)
  147. {
  148. Regex methodRegex = h.Method;
  149. Regex pathRegex = h.Path;
  150. Dictionary<string, Regex> headerRegexs = h.Headers;
  151. Regex endPointsRegex = h.IPEndPointWhitelist;
  152. // initial anchor
  153. scoredHandlers[h] = 0;
  154. // first, check whether IPEndPointWhitelist applies
  155. // and, if it does, whether client is on that white
  156. // list.
  157. if (null != endPointsRegex)
  158. {
  159. // TODO: following code requires code changes to
  160. // HttpServer.HttpRequest to become functional
  161. IPEndPoint remote = req.RemoteIPEndPoint;
  162. if (null != remote)
  163. {
  164. Match epm = endPointsRegex.Match(remote.ToString());
  165. if (!epm.Success) continue;
  166. }
  167. }
  168. if (null != methodRegex)
  169. {
  170. Match m = methodRegex.Match(req.HttpMethod);
  171. if (!m.Success) continue;
  172. scoredHandlers[h]++;
  173. }
  174. // whitelist ok, now check path
  175. if (null != pathRegex)
  176. {
  177. Match m = pathRegex.Match(req.RawUrl);
  178. if (!m.Success) continue;
  179. scoredHandlers[h] = m.ToString().Length;
  180. }
  181. // whitelist & path ok, now check headers
  182. if (null != headerRegexs)
  183. {
  184. int headersMatch = 0;
  185. // go through all header Regexs and evaluate
  186. // match:
  187. // if header field not present or does not match:
  188. // remove handler from scoredHandlers
  189. // continue
  190. // else:
  191. // add increment headersMatch
  192. NameValueCollection headers = req.HttpRequest.Headers;
  193. foreach (string tag in headerRegexs.Keys)
  194. {
  195. // do we have a header "tag"?
  196. if (null == headers[tag])
  197. {
  198. // no: remove the handler if it was added
  199. // earlier and on to the next one
  200. _log.DebugFormat("[{0}] dropping handler for {1}: null {2} header field: {3}", EngineID, req, tag, h);
  201. scoredHandlers.Remove(h);
  202. break;
  203. }
  204. // does the content of header "tag" match
  205. // the supplied regex?
  206. Match hm = headerRegexs[tag].Match(headers[tag]);
  207. if (!hm.Success) {
  208. // no: remove the handler if it was added
  209. // earlier and on to the next one
  210. _log.DebugFormat("[{0}] dropping handler for {1}: {2} header field content \"{3}\" does not match regex {4}: {5}",
  211. EngineID, req, tag, headers[tag], headerRegexs[tag].ToString(), h);
  212. scoredHandlers.Remove(h);
  213. break;
  214. }
  215. // if we are looking at the "content-type" tag,
  216. // check wether h has a ContentTypeChecker and
  217. // invoke it if it has
  218. if ((null != h.ContentTypeChecker) && !h.ContentTypeChecker(req))
  219. {
  220. scoredHandlers.Remove(h);
  221. _log.DebugFormat("[{0}] dropping handler for {1}: content checker returned false: {2}", EngineID, req, h);
  222. break;
  223. }
  224. // ok: header matches
  225. headersMatch++;
  226. _log.DebugFormat("[{0}] MatchHandlers: found handler for {1}: {2}", EngineID, req, h.ToString());
  227. continue;
  228. }
  229. // check whether h got kicked out
  230. if (!scoredHandlers.ContainsKey(h)) continue;
  231. scoredHandlers[h] += headersMatch;
  232. }
  233. }
  234. List<OSHttpHandler> matchingHandlers = new List<OSHttpHandler>(scoredHandlers.Keys);
  235. matchingHandlers.Sort(delegate(OSHttpHandler x, OSHttpHandler y)
  236. {
  237. return scoredHandlers[x] - scoredHandlers[y];
  238. });
  239. LogDumpHandlerList(matchingHandlers);
  240. return matchingHandlers;
  241. }
  242. [ConditionalAttribute("DEBUGGING")]
  243. private void LogDumpHandlerList(List<OSHttpHandler> l)
  244. {
  245. _log.DebugFormat("[{0}] OSHttpHandlerList dump:", EngineID);
  246. foreach (OSHttpHandler h in l)
  247. _log.DebugFormat(" ", h.ToString());
  248. }
  249. }
  250. }