BaseHttpServer.cs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991
  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 OpenSimulator 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;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.IO;
  32. using System.Net;
  33. using System.Net.Sockets;
  34. using System.Security.Cryptography.X509Certificates;
  35. using System.Reflection;
  36. using System.Globalization;
  37. using System.Text;
  38. using System.Threading;
  39. using System.Xml;
  40. using HttpServer;
  41. using log4net;
  42. using Nwc.XmlRpc;
  43. using OpenMetaverse.StructuredData;
  44. using CoolHTTPListener = HttpServer.HttpListener;
  45. using HttpListener=System.Net.HttpListener;
  46. using LogPrio=HttpServer.LogPrio;
  47. namespace OpenSim.Framework.Servers.HttpServer
  48. {
  49. public class BaseHttpServer : IHttpServer
  50. {
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. private HttpServerLogWriter httpserverlog = new HttpServerLogWriter();
  53. private volatile int NotSocketErrors = 0;
  54. public volatile bool HTTPDRunning = false;
  55. // protected HttpListener m_httpListener;
  56. protected CoolHTTPListener m_httpListener2;
  57. protected Dictionary<string, XmlRpcMethod> m_rpcHandlers = new Dictionary<string, XmlRpcMethod>();
  58. protected Dictionary<string, bool> m_rpcHandlersKeepAlive = new Dictionary<string, bool>();
  59. protected DefaultLLSDMethod m_defaultLlsdHandler = null; // <-- Moving away from the monolithic.. and going to /registered/
  60. protected Dictionary<string, LLSDMethod> m_llsdHandlers = new Dictionary<string, LLSDMethod>();
  61. protected Dictionary<string, IRequestHandler> m_streamHandlers = new Dictionary<string, IRequestHandler>();
  62. protected Dictionary<string, GenericHTTPMethod> m_HTTPHandlers = new Dictionary<string, GenericHTTPMethod>();
  63. protected Dictionary<string, IHttpAgentHandler> m_agentHandlers = new Dictionary<string, IHttpAgentHandler>();
  64. protected Dictionary<string, PollServiceEventArgs> m_pollHandlers =
  65. new Dictionary<string, PollServiceEventArgs>();
  66. protected uint m_port;
  67. protected uint m_sslport;
  68. protected bool m_ssl;
  69. private X509Certificate2 m_cert;
  70. protected bool m_firstcaps = true;
  71. protected string m_SSLCommonName = "";
  72. protected IPAddress m_listenIPAddress = IPAddress.Any;
  73. private PollServiceRequestManager m_PollServiceManager;
  74. /// <summary>
  75. /// Control the printing of certain debug messages.
  76. /// </summary>
  77. public int DebugLevel { get; set; }
  78. public uint SSLPort
  79. {
  80. get { return m_sslport; }
  81. }
  82. public string SSLCommonName
  83. {
  84. get { return m_SSLCommonName; }
  85. }
  86. public uint Port
  87. {
  88. get { return m_port; }
  89. }
  90. public bool UseSSL
  91. {
  92. get { return m_ssl; }
  93. }
  94. public IPAddress ListenIPAddress
  95. {
  96. get { return m_listenIPAddress; }
  97. set { m_listenIPAddress = value; }
  98. }
  99. public BaseHttpServer(uint port)
  100. {
  101. m_port = port;
  102. }
  103. public BaseHttpServer(uint port, bool ssl) : this (port)
  104. {
  105. m_ssl = ssl;
  106. }
  107. public BaseHttpServer(uint port, bool ssl, uint sslport, string CN) : this (port, ssl)
  108. {
  109. if (m_ssl)
  110. {
  111. m_sslport = sslport;
  112. }
  113. }
  114. public BaseHttpServer(uint port, bool ssl, string CPath, string CPass) : this (port, ssl)
  115. {
  116. if (m_ssl)
  117. {
  118. m_cert = new X509Certificate2(CPath, CPass);
  119. }
  120. }
  121. /// <summary>
  122. /// Add a stream handler to the http server. If the handler already exists, then nothing happens.
  123. /// </summary>
  124. /// <param name="handler"></param>
  125. public void AddStreamHandler(IRequestHandler handler)
  126. {
  127. string httpMethod = handler.HttpMethod;
  128. string path = handler.Path;
  129. string handlerKey = GetHandlerKey(httpMethod, path);
  130. lock (m_streamHandlers)
  131. {
  132. if (!m_streamHandlers.ContainsKey(handlerKey))
  133. {
  134. // m_log.DebugFormat("[BASE HTTP SERVER]: Adding handler key {0}", handlerKey);
  135. m_streamHandlers.Add(handlerKey, handler);
  136. }
  137. }
  138. }
  139. public List<string> GetStreamHandlerKeys()
  140. {
  141. lock (m_streamHandlers)
  142. return new List<string>(m_streamHandlers.Keys);
  143. }
  144. private static string GetHandlerKey(string httpMethod, string path)
  145. {
  146. return httpMethod + ":" + path;
  147. }
  148. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  149. {
  150. return AddXmlRPCHandler(method, handler, true);
  151. }
  152. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler, bool keepAlive)
  153. {
  154. lock (m_rpcHandlers)
  155. {
  156. m_rpcHandlers[method] = handler;
  157. m_rpcHandlersKeepAlive[method] = keepAlive; // default
  158. }
  159. return true;
  160. }
  161. public XmlRpcMethod GetXmlRPCHandler(string method)
  162. {
  163. lock (m_rpcHandlers)
  164. {
  165. if (m_rpcHandlers.ContainsKey(method))
  166. {
  167. return m_rpcHandlers[method];
  168. }
  169. else
  170. {
  171. return null;
  172. }
  173. }
  174. }
  175. public List<string> GetXmlRpcHandlerKeys()
  176. {
  177. lock (m_rpcHandlers)
  178. return new List<string>(m_rpcHandlers.Keys);
  179. }
  180. public bool AddHTTPHandler(string methodName, GenericHTTPMethod handler)
  181. {
  182. //m_log.DebugFormat("[BASE HTTP SERVER]: Registering {0}", methodName);
  183. lock (m_HTTPHandlers)
  184. {
  185. if (!m_HTTPHandlers.ContainsKey(methodName))
  186. {
  187. m_HTTPHandlers.Add(methodName, handler);
  188. return true;
  189. }
  190. }
  191. //must already have a handler for that path so return false
  192. return false;
  193. }
  194. public List<string> GetHTTPHandlerKeys()
  195. {
  196. lock (m_HTTPHandlers)
  197. return new List<string>(m_HTTPHandlers.Keys);
  198. }
  199. public bool AddPollServiceHTTPHandler(string methodName, GenericHTTPMethod handler, PollServiceEventArgs args)
  200. {
  201. bool pollHandlerResult = false;
  202. lock (m_pollHandlers)
  203. {
  204. if (!m_pollHandlers.ContainsKey(methodName))
  205. {
  206. m_pollHandlers.Add(methodName,args);
  207. pollHandlerResult = true;
  208. }
  209. }
  210. if (pollHandlerResult)
  211. return AddHTTPHandler(methodName, handler);
  212. return false;
  213. }
  214. public List<string> GetPollServiceHandlerKeys()
  215. {
  216. lock (m_pollHandlers)
  217. return new List<string>(m_pollHandlers.Keys);
  218. }
  219. // Note that the agent string is provided simply to differentiate
  220. // the handlers - it is NOT required to be an actual agent header
  221. // value.
  222. public bool AddAgentHandler(string agent, IHttpAgentHandler handler)
  223. {
  224. lock (m_agentHandlers)
  225. {
  226. if (!m_agentHandlers.ContainsKey(agent))
  227. {
  228. m_agentHandlers.Add(agent, handler);
  229. return true;
  230. }
  231. }
  232. //must already have a handler for that path so return false
  233. return false;
  234. }
  235. public List<string> GetAgentHandlerKeys()
  236. {
  237. lock (m_agentHandlers)
  238. return new List<string>(m_agentHandlers.Keys);
  239. }
  240. public bool AddLLSDHandler(string path, LLSDMethod handler)
  241. {
  242. lock (m_llsdHandlers)
  243. {
  244. if (!m_llsdHandlers.ContainsKey(path))
  245. {
  246. m_llsdHandlers.Add(path, handler);
  247. return true;
  248. }
  249. }
  250. return false;
  251. }
  252. public List<string> GetLLSDHandlerKeys()
  253. {
  254. lock (m_llsdHandlers)
  255. return new List<string>(m_llsdHandlers.Keys);
  256. }
  257. public bool SetDefaultLLSDHandler(DefaultLLSDMethod handler)
  258. {
  259. m_defaultLlsdHandler = handler;
  260. return true;
  261. }
  262. private void OnRequest(object source, RequestEventArgs args)
  263. {
  264. try
  265. {
  266. IHttpClientContext context = (IHttpClientContext)source;
  267. IHttpRequest request = args.Request;
  268. PollServiceEventArgs psEvArgs;
  269. if (TryGetPollServiceHTTPHandler(request.UriPath.ToString(), out psEvArgs))
  270. {
  271. PollServiceHttpRequest psreq = new PollServiceHttpRequest(psEvArgs, context, request);
  272. if (psEvArgs.Request != null)
  273. {
  274. OSHttpRequest req = new OSHttpRequest(context, request);
  275. Stream requestStream = req.InputStream;
  276. Encoding encoding = Encoding.UTF8;
  277. StreamReader reader = new StreamReader(requestStream, encoding);
  278. string requestBody = reader.ReadToEnd();
  279. Hashtable keysvals = new Hashtable();
  280. Hashtable headervals = new Hashtable();
  281. string[] querystringkeys = req.QueryString.AllKeys;
  282. string[] rHeaders = req.Headers.AllKeys;
  283. keysvals.Add("body", requestBody);
  284. keysvals.Add("uri", req.RawUrl);
  285. keysvals.Add("content-type", req.ContentType);
  286. keysvals.Add("http-method", req.HttpMethod);
  287. foreach (string queryname in querystringkeys)
  288. {
  289. keysvals.Add(queryname, req.QueryString[queryname]);
  290. }
  291. foreach (string headername in rHeaders)
  292. {
  293. headervals[headername] = req.Headers[headername];
  294. }
  295. keysvals.Add("headers", headervals);
  296. keysvals.Add("querystringkeys", querystringkeys);
  297. psEvArgs.Request(psreq.RequestID, keysvals);
  298. }
  299. m_PollServiceManager.Enqueue(psreq);
  300. }
  301. else
  302. {
  303. OnHandleRequestIOThread(context, request);
  304. }
  305. }
  306. catch (Exception e)
  307. {
  308. m_log.ErrorFormat("[BASE HTTP SERVER]: OnRequest() failed with {0}{1}", e.Message, e.StackTrace);
  309. }
  310. }
  311. public void OnHandleRequestIOThread(IHttpClientContext context, IHttpRequest request)
  312. {
  313. OSHttpRequest req = new OSHttpRequest(context, request);
  314. OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context);
  315. HandleRequest(req, resp);
  316. // !!!HACK ALERT!!!
  317. // There seems to be a bug in the underlying http code that makes subsequent requests
  318. // come up with trash in Accept headers. Until that gets fixed, we're cleaning them up here.
  319. if (request.AcceptTypes != null)
  320. for (int i = 0; i < request.AcceptTypes.Length; i++)
  321. request.AcceptTypes[i] = string.Empty;
  322. }
  323. // public void ConvertIHttpClientContextToOSHttp(object stateinfo)
  324. // {
  325. // HttpServerContextObj objstate = (HttpServerContextObj)stateinfo;
  326. // OSHttpRequest request = objstate.oreq;
  327. // OSHttpResponse resp = objstate.oresp;
  328. // HandleRequest(request,resp);
  329. // }
  330. /// <summary>
  331. /// This methods is the start of incoming HTTP request handling.
  332. /// </summary>
  333. /// <param name="request"></param>
  334. /// <param name="response"></param>
  335. public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response)
  336. {
  337. if (request.HttpMethod == String.Empty) // Can't handle empty requests, not wasting a thread
  338. {
  339. try
  340. {
  341. SendHTML500(response);
  342. }
  343. catch
  344. {
  345. }
  346. return;
  347. }
  348. string requestMethod = request.HttpMethod;
  349. string uriString = request.RawUrl;
  350. // string reqnum = "unknown";
  351. int tickstart = Environment.TickCount;
  352. try
  353. {
  354. // OpenSim.Framework.WebUtil.OSHeaderRequestID
  355. // if (request.Headers["opensim-request-id"] != null)
  356. // reqnum = String.Format("{0}:{1}",request.RemoteIPEndPoint,request.Headers["opensim-request-id"]);
  357. //m_log.DebugFormat("[BASE HTTP SERVER]: <{0}> handle request for {1}",reqnum,request.RawUrl);
  358. Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", true);
  359. // This is the REST agent interface. We require an agent to properly identify
  360. // itself. If the REST handler recognizes the prefix it will attempt to
  361. // satisfy the request. If it is not recognizable, and no damage has occurred
  362. // the request can be passed through to the other handlers. This is a low
  363. // probability event; if a request is matched it is normally expected to be
  364. // handled
  365. IHttpAgentHandler agentHandler;
  366. if (TryGetAgentHandler(request, response, out agentHandler))
  367. {
  368. if (HandleAgentRequest(agentHandler, request, response))
  369. {
  370. return;
  371. }
  372. }
  373. //response.KeepAlive = true;
  374. response.SendChunked = false;
  375. IRequestHandler requestHandler;
  376. string path = request.RawUrl;
  377. string handlerKey = GetHandlerKey(request.HttpMethod, path);
  378. if (TryGetStreamHandler(handlerKey, out requestHandler))
  379. {
  380. if (DebugLevel >= 1)
  381. m_log.DebugFormat(
  382. "[BASE HTTP SERVER]: Found stream handler for {0} {1}",
  383. request.HttpMethod, request.Url.PathAndQuery);
  384. // Okay, so this is bad, but should be considered temporary until everything is IStreamHandler.
  385. byte[] buffer = null;
  386. response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type.
  387. if (requestHandler is IStreamedRequestHandler)
  388. {
  389. IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler;
  390. buffer = streamedRequestHandler.Handle(path, request.InputStream, request, response);
  391. }
  392. else if (requestHandler is IGenericHTTPHandler)
  393. {
  394. //m_log.Debug("[BASE HTTP SERVER]: Found Caps based HTTP Handler");
  395. IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler;
  396. Stream requestStream = request.InputStream;
  397. Encoding encoding = Encoding.UTF8;
  398. StreamReader reader = new StreamReader(requestStream, encoding);
  399. string requestBody = reader.ReadToEnd();
  400. reader.Close();
  401. //requestStream.Close();
  402. Hashtable keysvals = new Hashtable();
  403. Hashtable headervals = new Hashtable();
  404. //string host = String.Empty;
  405. string[] querystringkeys = request.QueryString.AllKeys;
  406. string[] rHeaders = request.Headers.AllKeys;
  407. foreach (string queryname in querystringkeys)
  408. {
  409. keysvals.Add(queryname, request.QueryString[queryname]);
  410. }
  411. foreach (string headername in rHeaders)
  412. {
  413. //m_log.Warn("[HEADER]: " + headername + "=" + request.Headers[headername]);
  414. headervals[headername] = request.Headers[headername];
  415. }
  416. // if (headervals.Contains("Host"))
  417. // {
  418. // host = (string)headervals["Host"];
  419. // }
  420. keysvals.Add("requestbody", requestBody);
  421. keysvals.Add("headers",headervals);
  422. if (keysvals.Contains("method"))
  423. {
  424. //m_log.Warn("[HTTP]: Contains Method");
  425. //string method = (string)keysvals["method"];
  426. //m_log.Warn("[HTTP]: " + requestBody);
  427. }
  428. DoHTTPGruntWork(HTTPRequestHandler.Handle(path, keysvals), response);
  429. return;
  430. }
  431. else
  432. {
  433. IStreamHandler streamHandler = (IStreamHandler)requestHandler;
  434. using (MemoryStream memoryStream = new MemoryStream())
  435. {
  436. streamHandler.Handle(path, request.InputStream, memoryStream, request, response);
  437. memoryStream.Flush();
  438. buffer = memoryStream.ToArray();
  439. }
  440. }
  441. request.InputStream.Close();
  442. // HTTP IN support. The script engine takes it from here
  443. // Nothing to worry about for us.
  444. //
  445. if (buffer == null)
  446. return;
  447. if (!response.SendChunked)
  448. response.ContentLength64 = buffer.LongLength;
  449. try
  450. {
  451. response.OutputStream.Write(buffer, 0, buffer.Length);
  452. //response.OutputStream.Close();
  453. }
  454. catch (HttpListenerException)
  455. {
  456. m_log.WarnFormat("[BASE HTTP SERVER]: HTTP request abnormally terminated.");
  457. }
  458. //response.OutputStream.Close();
  459. try
  460. {
  461. response.Send();
  462. //response.FreeContext();
  463. }
  464. catch (SocketException e)
  465. {
  466. // This has to be here to prevent a Linux/Mono crash
  467. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  468. }
  469. catch (IOException e)
  470. {
  471. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  472. }
  473. return;
  474. }
  475. if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
  476. {
  477. foreach (string strAccept in request.AcceptTypes)
  478. {
  479. if (strAccept.Contains("application/llsd+xml") ||
  480. strAccept.Contains("application/llsd+json"))
  481. {
  482. if (DebugLevel >= 1)
  483. m_log.DebugFormat(
  484. "[BASE HTTP SERVER]: Found application/llsd+xml accept header handler for {0} {1}",
  485. request.HttpMethod, request.Url.PathAndQuery);
  486. HandleLLSDRequests(request, response);
  487. return;
  488. }
  489. }
  490. }
  491. switch (request.ContentType)
  492. {
  493. case null:
  494. case "text/html":
  495. if (DebugLevel >= 1)
  496. m_log.DebugFormat(
  497. "[BASE HTTP SERVER]: Found a {0} content type handler for {1} {2}",
  498. request.ContentType, request.HttpMethod, request.Url.PathAndQuery);
  499. HandleHTTPRequest(request, response);
  500. return;
  501. case "application/llsd+xml":
  502. case "application/xml+llsd":
  503. case "application/llsd+json":
  504. if (DebugLevel >= 1)
  505. m_log.DebugFormat(
  506. "[BASE HTTP SERVER]: Found a {0} content type handler for {1} {2}",
  507. request.ContentType, request.HttpMethod, request.Url.PathAndQuery);
  508. HandleLLSDRequests(request, response);
  509. return;
  510. case "text/xml":
  511. case "application/xml":
  512. case "application/json":
  513. default:
  514. //m_log.Info("[Debug BASE HTTP SERVER]: in default handler");
  515. // Point of note.. the DoWeHaveA methods check for an EXACT path
  516. // if (request.RawUrl.Contains("/CAPS/EQG"))
  517. // {
  518. // int i = 1;
  519. // }
  520. //m_log.Info("[Debug BASE HTTP SERVER]: Checking for LLSD Handler");
  521. if (DoWeHaveALLSDHandler(request.RawUrl))
  522. {
  523. if (DebugLevel >= 1)
  524. m_log.DebugFormat(
  525. "[BASE HTTP SERVER]: Found a {0} content type handler for {1} {2}",
  526. request.ContentType, request.HttpMethod, request.Url.PathAndQuery);
  527. HandleLLSDRequests(request, response);
  528. return;
  529. }
  530. // m_log.DebugFormat("[BASE HTTP SERVER]: Checking for HTTP Handler for request {0}", request.RawUrl);
  531. if (DoWeHaveAHTTPHandler(request.RawUrl))
  532. {
  533. if (DebugLevel >= 1)
  534. m_log.DebugFormat(
  535. "[BASE HTTP SERVER]: Found a {0} content type handler for {1} {2}",
  536. request.ContentType, request.HttpMethod, request.Url.PathAndQuery);
  537. HandleHTTPRequest(request, response);
  538. return;
  539. }
  540. if (DebugLevel >= 1)
  541. m_log.DebugFormat(
  542. "[BASE HTTP SERVER]: Assuming a generic XMLRPC request for {0} {1}",
  543. request.HttpMethod, request.Url.PathAndQuery);
  544. // generic login request.
  545. HandleXmlRpcRequests(request, response);
  546. return;
  547. }
  548. }
  549. catch (SocketException e)
  550. {
  551. // At least on linux, it appears that if the client makes a request without requiring the response,
  552. // an unconnected socket exception is thrown when we close the response output stream. There's no
  553. // obvious way to tell if the client didn't require the response, so instead we'll catch and ignore
  554. // the exception instead.
  555. //
  556. // An alternative may be to turn off all response write exceptions on the HttpListener, but let's go
  557. // with the minimum first
  558. m_log.WarnFormat("[BASE HTTP SERVER]: HandleRequest threw {0}.\nNOTE: this may be spurious on Linux", e);
  559. }
  560. catch (IOException e)
  561. {
  562. m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw ", e);
  563. }
  564. catch (Exception e)
  565. {
  566. m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw " + e.ToString());
  567. SendHTML500(response);
  568. }
  569. finally
  570. {
  571. // Every month or so this will wrap and give bad numbers, not really a problem
  572. // since its just for reporting, tickdiff limit can be adjusted
  573. int tickdiff = Environment.TickCount - tickstart;
  574. if (tickdiff > 3000)
  575. m_log.InfoFormat(
  576. "[BASE HTTP SERVER]: slow {0} request for {1} from {2} took {3} ms", requestMethod, uriString, request.RemoteIPEndPoint.ToString(), tickdiff);
  577. }
  578. }
  579. private bool TryGetStreamHandler(string handlerKey, out IRequestHandler streamHandler)
  580. {
  581. string bestMatch = null;
  582. lock (m_streamHandlers)
  583. {
  584. foreach (string pattern in m_streamHandlers.Keys)
  585. {
  586. if (handlerKey.StartsWith(pattern))
  587. {
  588. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  589. {
  590. bestMatch = pattern;
  591. }
  592. }
  593. }
  594. if (String.IsNullOrEmpty(bestMatch))
  595. {
  596. streamHandler = null;
  597. return false;
  598. }
  599. else
  600. {
  601. streamHandler = m_streamHandlers[bestMatch];
  602. return true;
  603. }
  604. }
  605. }
  606. private bool TryGetPollServiceHTTPHandler(string handlerKey, out PollServiceEventArgs oServiceEventArgs)
  607. {
  608. string bestMatch = null;
  609. lock (m_pollHandlers)
  610. {
  611. foreach (string pattern in m_pollHandlers.Keys)
  612. {
  613. if (handlerKey.StartsWith(pattern))
  614. {
  615. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  616. {
  617. bestMatch = pattern;
  618. }
  619. }
  620. }
  621. if (String.IsNullOrEmpty(bestMatch))
  622. {
  623. oServiceEventArgs = null;
  624. return false;
  625. }
  626. else
  627. {
  628. oServiceEventArgs = m_pollHandlers[bestMatch];
  629. return true;
  630. }
  631. }
  632. }
  633. private bool TryGetHTTPHandler(string handlerKey, out GenericHTTPMethod HTTPHandler)
  634. {
  635. // m_log.DebugFormat("[BASE HTTP HANDLER]: Looking for HTTP handler for {0}", handlerKey);
  636. string bestMatch = null;
  637. lock (m_HTTPHandlers)
  638. {
  639. foreach (string pattern in m_HTTPHandlers.Keys)
  640. {
  641. if (handlerKey.StartsWith(pattern))
  642. {
  643. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  644. {
  645. bestMatch = pattern;
  646. }
  647. }
  648. }
  649. if (String.IsNullOrEmpty(bestMatch))
  650. {
  651. HTTPHandler = null;
  652. return false;
  653. }
  654. else
  655. {
  656. HTTPHandler = m_HTTPHandlers[bestMatch];
  657. return true;
  658. }
  659. }
  660. }
  661. private bool TryGetAgentHandler(OSHttpRequest request, OSHttpResponse response, out IHttpAgentHandler agentHandler)
  662. {
  663. agentHandler = null;
  664. lock (m_agentHandlers)
  665. {
  666. foreach (IHttpAgentHandler handler in m_agentHandlers.Values)
  667. {
  668. if (handler.Match(request, response))
  669. {
  670. agentHandler = handler;
  671. return true;
  672. }
  673. }
  674. }
  675. return false;
  676. }
  677. /// <summary>
  678. /// Try all the registered xmlrpc handlers when an xmlrpc request is received.
  679. /// Sends back an XMLRPC unknown request response if no handler is registered for the requested method.
  680. /// </summary>
  681. /// <param name="request"></param>
  682. /// <param name="response"></param>
  683. private void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
  684. {
  685. Stream requestStream = request.InputStream;
  686. Encoding encoding = Encoding.UTF8;
  687. StreamReader reader = new StreamReader(requestStream, encoding);
  688. string requestBody = reader.ReadToEnd();
  689. reader.Close();
  690. requestStream.Close();
  691. //m_log.Debug(requestBody);
  692. requestBody = requestBody.Replace("<base64></base64>", "");
  693. string responseString = String.Empty;
  694. XmlRpcRequest xmlRprcRequest = null;
  695. try
  696. {
  697. xmlRprcRequest = (XmlRpcRequest) (new XmlRpcRequestDeserializer()).Deserialize(requestBody);
  698. }
  699. catch (XmlException)
  700. {
  701. }
  702. if (xmlRprcRequest != null)
  703. {
  704. string methodName = xmlRprcRequest.MethodName;
  705. if (methodName != null)
  706. {
  707. xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
  708. XmlRpcResponse xmlRpcResponse;
  709. XmlRpcMethod method;
  710. bool methodWasFound;
  711. bool keepAlive = false;
  712. lock (m_rpcHandlers)
  713. {
  714. methodWasFound = m_rpcHandlers.TryGetValue(methodName, out method);
  715. if (methodWasFound)
  716. keepAlive = m_rpcHandlersKeepAlive[methodName];
  717. }
  718. if (methodWasFound)
  719. {
  720. xmlRprcRequest.Params.Add(request.Url); // Param[2]
  721. string xff = "X-Forwarded-For";
  722. string xfflower = xff.ToLower();
  723. foreach (string s in request.Headers.AllKeys)
  724. {
  725. if (s != null && s.Equals(xfflower))
  726. {
  727. xff = xfflower;
  728. break;
  729. }
  730. }
  731. xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3]
  732. try
  733. {
  734. xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
  735. }
  736. catch(Exception e)
  737. {
  738. string errorMessage
  739. = String.Format(
  740. "Requested method [{0}] from {1} threw exception: {2} {3}",
  741. methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace);
  742. m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
  743. // if the registered XmlRpc method threw an exception, we pass a fault-code along
  744. xmlRpcResponse = new XmlRpcResponse();
  745. // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  746. xmlRpcResponse.SetFault(-32603, errorMessage);
  747. }
  748. // if the method wasn't found, we can't determine KeepAlive state anyway, so lets do it only here
  749. response.KeepAlive = keepAlive;
  750. }
  751. else
  752. {
  753. xmlRpcResponse = new XmlRpcResponse();
  754. // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  755. xmlRpcResponse.SetFault(
  756. XmlRpcErrorCodes.SERVER_ERROR_METHOD,
  757. String.Format("Requested method [{0}] not found", methodName));
  758. }
  759. responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse);
  760. }
  761. else
  762. {
  763. //HandleLLSDRequests(request, response);
  764. response.ContentType = "text/plain";
  765. response.StatusCode = 404;
  766. response.StatusDescription = "Not Found";
  767. response.ProtocolVersion = "HTTP/1.0";
  768. byte[] buf = Encoding.UTF8.GetBytes("Not found");
  769. response.KeepAlive = false;
  770. m_log.ErrorFormat(
  771. "[BASE HTTP SERVER]: Handler not found for http request {0} {1}",
  772. request.HttpMethod, request.Url.PathAndQuery);
  773. response.SendChunked = false;
  774. response.ContentLength64 = buf.Length;
  775. response.ContentEncoding = Encoding.UTF8;
  776. try
  777. {
  778. response.OutputStream.Write(buf, 0, buf.Length);
  779. }
  780. catch (Exception ex)
  781. {
  782. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  783. }
  784. finally
  785. {
  786. try
  787. {
  788. response.Send();
  789. //response.FreeContext();
  790. }
  791. catch (SocketException e)
  792. {
  793. // This has to be here to prevent a Linux/Mono crash
  794. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  795. }
  796. catch (IOException e)
  797. {
  798. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  799. }
  800. }
  801. return;
  802. //responseString = "Error";
  803. }
  804. }
  805. response.ContentType = "text/xml";
  806. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  807. response.SendChunked = false;
  808. response.ContentLength64 = buffer.Length;
  809. response.ContentEncoding = Encoding.UTF8;
  810. try
  811. {
  812. response.OutputStream.Write(buffer, 0, buffer.Length);
  813. }
  814. catch (Exception ex)
  815. {
  816. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  817. }
  818. finally
  819. {
  820. try
  821. {
  822. response.Send();
  823. //response.FreeContext();
  824. }
  825. catch (SocketException e)
  826. {
  827. // This has to be here to prevent a Linux/Mono crash
  828. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  829. }
  830. catch (IOException e)
  831. {
  832. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  833. }
  834. }
  835. }
  836. private void HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response)
  837. {
  838. //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
  839. Stream requestStream = request.InputStream;
  840. Encoding encoding = Encoding.UTF8;
  841. StreamReader reader = new StreamReader(requestStream, encoding);
  842. string requestBody = reader.ReadToEnd();
  843. reader.Close();
  844. requestStream.Close();
  845. //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
  846. response.KeepAlive = true;
  847. OSD llsdRequest = null;
  848. OSD llsdResponse = null;
  849. bool LegacyLLSDLoginLibOMV = (requestBody.Contains("passwd") && requestBody.Contains("mac") && requestBody.Contains("viewer_digest"));
  850. if (requestBody.Length == 0)
  851. // Get Request
  852. {
  853. requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>";
  854. }
  855. try
  856. {
  857. llsdRequest = OSDParser.Deserialize(requestBody);
  858. }
  859. catch (Exception ex)
  860. {
  861. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  862. }
  863. if (llsdRequest != null)// && m_defaultLlsdHandler != null)
  864. {
  865. LLSDMethod llsdhandler = null;
  866. if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV)
  867. {
  868. // we found a registered llsd handler to service this request
  869. llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint.ToString());
  870. }
  871. else
  872. {
  873. // we didn't find a registered llsd handler to service this request
  874. // check if we have a default llsd handler
  875. if (m_defaultLlsdHandler != null)
  876. {
  877. // LibOMV path
  878. llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
  879. }
  880. else
  881. {
  882. // Oops, no handler for this.. give em the failed message
  883. llsdResponse = GenerateNoLLSDHandlerResponse();
  884. }
  885. }
  886. }
  887. else
  888. {
  889. llsdResponse = GenerateNoLLSDHandlerResponse();
  890. }
  891. byte[] buffer = new byte[0];
  892. if (llsdResponse.ToString() == "shutdown404!")
  893. {
  894. response.ContentType = "text/plain";
  895. response.StatusCode = 404;
  896. response.StatusDescription = "Not Found";
  897. response.ProtocolVersion = "HTTP/1.0";
  898. buffer = Encoding.UTF8.GetBytes("Not found");
  899. }
  900. else
  901. {
  902. // Select an appropriate response format
  903. buffer = BuildLLSDResponse(request, response, llsdResponse);
  904. }
  905. response.SendChunked = false;
  906. response.ContentLength64 = buffer.Length;
  907. response.ContentEncoding = Encoding.UTF8;
  908. response.KeepAlive = true;
  909. try
  910. {
  911. response.OutputStream.Write(buffer, 0, buffer.Length);
  912. }
  913. catch (Exception ex)
  914. {
  915. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  916. }
  917. finally
  918. {
  919. //response.OutputStream.Close();
  920. try
  921. {
  922. response.Send();
  923. response.OutputStream.Flush();
  924. //response.FreeContext();
  925. //response.OutputStream.Close();
  926. }
  927. catch (IOException e)
  928. {
  929. m_log.WarnFormat("[BASE HTTP SERVER]: LLSD IOException {0}.", e);
  930. }
  931. catch (SocketException e)
  932. {
  933. // This has to be here to prevent a Linux/Mono crash
  934. m_log.WarnFormat("[BASE HTTP SERVER]: LLSD issue {0}.\nNOTE: this may be spurious on Linux.", e);
  935. }
  936. }
  937. }
  938. private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
  939. {
  940. if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
  941. {
  942. foreach (string strAccept in request.AcceptTypes)
  943. {
  944. switch (strAccept)
  945. {
  946. case "application/llsd+xml":
  947. case "application/xml":
  948. case "text/xml":
  949. response.ContentType = strAccept;
  950. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  951. case "application/llsd+json":
  952. case "application/json":
  953. response.ContentType = strAccept;
  954. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  955. }
  956. }
  957. }
  958. if (!String.IsNullOrEmpty(request.ContentType))
  959. {
  960. switch (request.ContentType)
  961. {
  962. case "application/llsd+xml":
  963. case "application/xml":
  964. case "text/xml":
  965. response.ContentType = request.ContentType;
  966. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  967. case "application/llsd+json":
  968. case "application/json":
  969. response.ContentType = request.ContentType;
  970. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  971. }
  972. }
  973. // response.ContentType = "application/llsd+json";
  974. // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  975. response.ContentType = "application/llsd+xml";
  976. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  977. }
  978. /// <summary>
  979. /// Checks if we have an Exact path in the LLSD handlers for the path provided
  980. /// </summary>
  981. /// <param name="path">URI of the request</param>
  982. /// <returns>true if we have one, false if not</returns>
  983. private bool DoWeHaveALLSDHandler(string path)
  984. {
  985. string[] pathbase = path.Split('/');
  986. string searchquery = "/";
  987. if (pathbase.Length < 1)
  988. return false;
  989. for (int i = 1; i < pathbase.Length; i++)
  990. {
  991. searchquery += pathbase[i];
  992. if (pathbase.Length - 1 != i)
  993. searchquery += "/";
  994. }
  995. string bestMatch = null;
  996. lock (m_llsdHandlers)
  997. {
  998. foreach (string pattern in m_llsdHandlers.Keys)
  999. {
  1000. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1001. bestMatch = pattern;
  1002. }
  1003. }
  1004. // extra kicker to remove the default XMLRPC login case.. just in case..
  1005. if (path != "/" && bestMatch == "/" && searchquery != "/")
  1006. return false;
  1007. if (path == "/")
  1008. return false;
  1009. if (String.IsNullOrEmpty(bestMatch))
  1010. {
  1011. return false;
  1012. }
  1013. else
  1014. {
  1015. return true;
  1016. }
  1017. }
  1018. /// <summary>
  1019. /// Checks if we have an Exact path in the HTTP handlers for the path provided
  1020. /// </summary>
  1021. /// <param name="path">URI of the request</param>
  1022. /// <returns>true if we have one, false if not</returns>
  1023. private bool DoWeHaveAHTTPHandler(string path)
  1024. {
  1025. string[] pathbase = path.Split('/');
  1026. string searchquery = "/";
  1027. if (pathbase.Length < 1)
  1028. return false;
  1029. for (int i = 1; i < pathbase.Length; i++)
  1030. {
  1031. searchquery += pathbase[i];
  1032. if (pathbase.Length - 1 != i)
  1033. searchquery += "/";
  1034. }
  1035. string bestMatch = null;
  1036. //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
  1037. lock (m_HTTPHandlers)
  1038. {
  1039. foreach (string pattern in m_HTTPHandlers.Keys)
  1040. {
  1041. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1042. {
  1043. bestMatch = pattern;
  1044. }
  1045. }
  1046. // extra kicker to remove the default XMLRPC login case.. just in case..
  1047. if (path == "/")
  1048. return false;
  1049. if (String.IsNullOrEmpty(bestMatch))
  1050. {
  1051. return false;
  1052. }
  1053. else
  1054. {
  1055. return true;
  1056. }
  1057. }
  1058. }
  1059. private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
  1060. {
  1061. llsdHandler = null;
  1062. // Pull out the first part of the path
  1063. // splitting the path by '/' means we'll get the following return..
  1064. // {0}/{1}/{2}
  1065. // where {0} isn't something we really control 100%
  1066. string[] pathbase = path.Split('/');
  1067. string searchquery = "/";
  1068. if (pathbase.Length < 1)
  1069. return false;
  1070. for (int i=1; i<pathbase.Length; i++)
  1071. {
  1072. searchquery += pathbase[i];
  1073. if (pathbase.Length-1 != i)
  1074. searchquery += "/";
  1075. }
  1076. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1077. //
  1078. // [] = optional
  1079. // /resource/UUID/action[/action]
  1080. //
  1081. // now try to get the closest match to the reigstered path
  1082. // at least for OGP, registered path would probably only consist of the /resource/
  1083. string bestMatch = null;
  1084. lock (m_llsdHandlers)
  1085. {
  1086. foreach (string pattern in m_llsdHandlers.Keys)
  1087. {
  1088. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1089. {
  1090. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1091. {
  1092. // You have to specifically register for '/' and to get it, you must specificaly request it
  1093. //
  1094. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1095. bestMatch = pattern;
  1096. }
  1097. }
  1098. }
  1099. if (String.IsNullOrEmpty(bestMatch))
  1100. {
  1101. llsdHandler = null;
  1102. return false;
  1103. }
  1104. else
  1105. {
  1106. llsdHandler = m_llsdHandlers[bestMatch];
  1107. return true;
  1108. }
  1109. }
  1110. }
  1111. private OSDMap GenerateNoLLSDHandlerResponse()
  1112. {
  1113. OSDMap map = new OSDMap();
  1114. map["reason"] = OSD.FromString("LLSDRequest");
  1115. map["message"] = OSD.FromString("No handler registered for LLSD Requests");
  1116. map["login"] = OSD.FromString("false");
  1117. return map;
  1118. }
  1119. /// <summary>
  1120. /// A specific agent handler was provided. Such a handler is expecetd to have an
  1121. /// intimate, and highly specific relationship with the client. Consequently,
  1122. /// nothing is done here.
  1123. /// </summary>
  1124. /// <param name="handler"></param>
  1125. /// <param name="request"></param>
  1126. /// <param name="response"></param>
  1127. private bool HandleAgentRequest(IHttpAgentHandler handler, OSHttpRequest request, OSHttpResponse response)
  1128. {
  1129. // In the case of REST, then handler is responsible for ALL aspects of
  1130. // the request/response handling. Nothing is done here, not even encoding.
  1131. try
  1132. {
  1133. return handler.Handle(request, response);
  1134. }
  1135. catch (Exception e)
  1136. {
  1137. // If the handler did in fact close the stream, then this will blow
  1138. // chunks. So that that doesn't disturb anybody we throw away any
  1139. // and all exceptions raised. We've done our best to release the
  1140. // client.
  1141. try
  1142. {
  1143. m_log.Warn("[HTTP-AGENT]: Error - " + e.Message);
  1144. response.SendChunked = false;
  1145. response.KeepAlive = true;
  1146. response.StatusCode = (int)OSHttpStatusCode.ServerErrorInternalError;
  1147. //response.OutputStream.Close();
  1148. try
  1149. {
  1150. response.Send();
  1151. //response.FreeContext();
  1152. }
  1153. catch (SocketException f)
  1154. {
  1155. // This has to be here to prevent a Linux/Mono crash
  1156. m_log.WarnFormat(
  1157. "[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", f);
  1158. }
  1159. }
  1160. catch(Exception)
  1161. {
  1162. }
  1163. }
  1164. // Indicate that the request has been "handled"
  1165. return true;
  1166. }
  1167. public void HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
  1168. {
  1169. // m_log.DebugFormat(
  1170. // "[BASE HTTP SERVER]: HandleHTTPRequest for request to {0}, method {1}",
  1171. // request.RawUrl, request.HttpMethod);
  1172. switch (request.HttpMethod)
  1173. {
  1174. case "OPTIONS":
  1175. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1176. return;
  1177. default:
  1178. HandleContentVerbs(request, response);
  1179. return;
  1180. }
  1181. }
  1182. private void HandleContentVerbs(OSHttpRequest request, OSHttpResponse response)
  1183. {
  1184. // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl);
  1185. // This is a test. There's a workable alternative.. as this way sucks.
  1186. // We'd like to put this into a text file parhaps that's easily editable.
  1187. //
  1188. // For this test to work, I used the following secondlife.exe parameters
  1189. // "C:\Program Files\SecondLifeWindLight\SecondLifeWindLight.exe" -settings settings_windlight.xml -channel "Second Life WindLight" -set SystemLanguage en-us -loginpage http://10.1.1.2:8002/?show_login_form=TRUE -loginuri http://10.1.1.2:8002 -user 10.1.1.2
  1190. //
  1191. // Even after all that, there's still an error, but it's a start.
  1192. //
  1193. // I depend on show_login_form being in the secondlife.exe parameters to figure out
  1194. // to display the form, or process it.
  1195. // a better way would be nifty.
  1196. Stream requestStream = request.InputStream;
  1197. Encoding encoding = Encoding.UTF8;
  1198. StreamReader reader = new StreamReader(requestStream, encoding);
  1199. string requestBody = reader.ReadToEnd();
  1200. // avoid warning for now
  1201. reader.ReadToEnd();
  1202. reader.Close();
  1203. requestStream.Close();
  1204. Hashtable keysvals = new Hashtable();
  1205. Hashtable headervals = new Hashtable();
  1206. Hashtable requestVars = new Hashtable();
  1207. string host = String.Empty;
  1208. string[] querystringkeys = request.QueryString.AllKeys;
  1209. string[] rHeaders = request.Headers.AllKeys;
  1210. keysvals.Add("body", requestBody);
  1211. keysvals.Add("uri", request.RawUrl);
  1212. keysvals.Add("content-type", request.ContentType);
  1213. keysvals.Add("http-method", request.HttpMethod);
  1214. foreach (string queryname in querystringkeys)
  1215. {
  1216. // m_log.DebugFormat(
  1217. // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
  1218. keysvals.Add(queryname, request.QueryString[queryname]);
  1219. requestVars.Add(queryname, keysvals[queryname]);
  1220. }
  1221. foreach (string headername in rHeaders)
  1222. {
  1223. // m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
  1224. headervals[headername] = request.Headers[headername];
  1225. }
  1226. if (headervals.Contains("Host"))
  1227. {
  1228. host = (string)headervals["Host"];
  1229. }
  1230. keysvals.Add("headers", headervals);
  1231. keysvals.Add("querystringkeys", querystringkeys);
  1232. keysvals.Add("requestvars", requestVars);
  1233. // keysvals.Add("form", request.Form);
  1234. if (keysvals.Contains("method"))
  1235. {
  1236. // m_log.Debug("[BASE HTTP SERVER]: Contains Method");
  1237. string method = (string) keysvals["method"];
  1238. // m_log.Debug("[BASE HTTP SERVER]: " + requestBody);
  1239. GenericHTTPMethod requestprocessor;
  1240. bool foundHandler = TryGetHTTPHandler(method, out requestprocessor);
  1241. if (foundHandler)
  1242. {
  1243. Hashtable responsedata1 = requestprocessor(keysvals);
  1244. DoHTTPGruntWork(responsedata1,response);
  1245. //SendHTML500(response);
  1246. }
  1247. else
  1248. {
  1249. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found");
  1250. SendHTML404(response, host);
  1251. }
  1252. }
  1253. else
  1254. {
  1255. GenericHTTPMethod requestprocessor;
  1256. bool foundHandler = TryGetHTTPHandlerPathBased(request.RawUrl, out requestprocessor);
  1257. if (foundHandler)
  1258. {
  1259. Hashtable responsedata2 = requestprocessor(keysvals);
  1260. DoHTTPGruntWork(responsedata2, response);
  1261. //SendHTML500(response);
  1262. }
  1263. else
  1264. {
  1265. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found2");
  1266. SendHTML404(response, host);
  1267. }
  1268. }
  1269. }
  1270. private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
  1271. {
  1272. httpHandler = null;
  1273. // Pull out the first part of the path
  1274. // splitting the path by '/' means we'll get the following return..
  1275. // {0}/{1}/{2}
  1276. // where {0} isn't something we really control 100%
  1277. string[] pathbase = path.Split('/');
  1278. string searchquery = "/";
  1279. if (pathbase.Length < 1)
  1280. return false;
  1281. for (int i = 1; i < pathbase.Length; i++)
  1282. {
  1283. searchquery += pathbase[i];
  1284. if (pathbase.Length - 1 != i)
  1285. searchquery += "/";
  1286. }
  1287. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1288. //
  1289. // [] = optional
  1290. // /resource/UUID/action[/action]
  1291. //
  1292. // now try to get the closest match to the reigstered path
  1293. // at least for OGP, registered path would probably only consist of the /resource/
  1294. string bestMatch = null;
  1295. // m_log.DebugFormat(
  1296. // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
  1297. lock (m_HTTPHandlers)
  1298. {
  1299. foreach (string pattern in m_HTTPHandlers.Keys)
  1300. {
  1301. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1302. {
  1303. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1304. {
  1305. // You have to specifically register for '/' and to get it, you must specifically request it
  1306. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1307. bestMatch = pattern;
  1308. }
  1309. }
  1310. }
  1311. if (String.IsNullOrEmpty(bestMatch))
  1312. {
  1313. httpHandler = null;
  1314. return false;
  1315. }
  1316. else
  1317. {
  1318. if (bestMatch == "/" && searchquery != "/")
  1319. return false;
  1320. httpHandler = m_HTTPHandlers[bestMatch];
  1321. return true;
  1322. }
  1323. }
  1324. }
  1325. internal void DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
  1326. {
  1327. //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
  1328. int responsecode = (int)responsedata["int_response_code"];
  1329. string responseString = (string)responsedata["str_response_string"];
  1330. string contentType = (string)responsedata["content_type"];
  1331. if (responsedata.ContainsKey("error_status_text"))
  1332. {
  1333. response.StatusDescription = (string)responsedata["error_status_text"];
  1334. }
  1335. if (responsedata.ContainsKey("http_protocol_version"))
  1336. {
  1337. response.ProtocolVersion = (string)responsedata["http_protocol_version"];
  1338. }
  1339. if (responsedata.ContainsKey("keepalive"))
  1340. {
  1341. bool keepalive = (bool)responsedata["keepalive"];
  1342. response.KeepAlive = keepalive;
  1343. }
  1344. if (responsedata.ContainsKey("reusecontext"))
  1345. response.ReuseContext = (bool) responsedata["reusecontext"];
  1346. // Cross-Origin Resource Sharing with simple requests
  1347. if (responsedata.ContainsKey("access_control_allow_origin"))
  1348. response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
  1349. //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
  1350. //and should check for NullReferenceExceptions
  1351. if (string.IsNullOrEmpty(contentType))
  1352. {
  1353. contentType = "text/html";
  1354. }
  1355. // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
  1356. response.StatusCode = responsecode;
  1357. if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently)
  1358. {
  1359. response.RedirectLocation = (string)responsedata["str_redirect_location"];
  1360. response.StatusCode = responsecode;
  1361. }
  1362. response.AddHeader("Content-Type", contentType);
  1363. byte[] buffer;
  1364. if (!(contentType.Contains("image")
  1365. || contentType.Contains("x-shockwave-flash")
  1366. || contentType.Contains("application/x-oar")
  1367. || contentType.Contains("application/vnd.ll.mesh")))
  1368. {
  1369. // Text
  1370. buffer = Encoding.UTF8.GetBytes(responseString);
  1371. }
  1372. else
  1373. {
  1374. // Binary!
  1375. buffer = Convert.FromBase64String(responseString);
  1376. }
  1377. response.SendChunked = false;
  1378. response.ContentLength64 = buffer.Length;
  1379. response.ContentEncoding = Encoding.UTF8;
  1380. try
  1381. {
  1382. response.OutputStream.Write(buffer, 0, buffer.Length);
  1383. }
  1384. catch (Exception ex)
  1385. {
  1386. m_log.Warn("[HTTPD]: Error - " + ex.Message);
  1387. }
  1388. finally
  1389. {
  1390. //response.OutputStream.Close();
  1391. try
  1392. {
  1393. response.OutputStream.Flush();
  1394. response.Send();
  1395. //if (!response.KeepAlive && response.ReuseContext)
  1396. // response.FreeContext();
  1397. }
  1398. catch (SocketException e)
  1399. {
  1400. // This has to be here to prevent a Linux/Mono crash
  1401. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  1402. }
  1403. catch (IOException e)
  1404. {
  1405. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  1406. }
  1407. }
  1408. }
  1409. public void SendHTML404(OSHttpResponse response, string host)
  1410. {
  1411. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1412. response.StatusCode = 404;
  1413. response.AddHeader("Content-type", "text/html");
  1414. string responseString = GetHTTP404(host);
  1415. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1416. response.SendChunked = false;
  1417. response.ContentLength64 = buffer.Length;
  1418. response.ContentEncoding = Encoding.UTF8;
  1419. try
  1420. {
  1421. response.OutputStream.Write(buffer, 0, buffer.Length);
  1422. }
  1423. catch (Exception ex)
  1424. {
  1425. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1426. }
  1427. finally
  1428. {
  1429. //response.OutputStream.Close();
  1430. try
  1431. {
  1432. response.Send();
  1433. //response.FreeContext();
  1434. }
  1435. catch (SocketException e)
  1436. {
  1437. // This has to be here to prevent a Linux/Mono crash
  1438. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  1439. }
  1440. }
  1441. }
  1442. public void SendHTML500(OSHttpResponse response)
  1443. {
  1444. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1445. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1446. response.AddHeader("Content-type", "text/html");
  1447. string responseString = GetHTTP500();
  1448. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1449. response.SendChunked = false;
  1450. response.ContentLength64 = buffer.Length;
  1451. response.ContentEncoding = Encoding.UTF8;
  1452. try
  1453. {
  1454. response.OutputStream.Write(buffer, 0, buffer.Length);
  1455. }
  1456. catch (Exception ex)
  1457. {
  1458. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1459. }
  1460. finally
  1461. {
  1462. //response.OutputStream.Close();
  1463. try
  1464. {
  1465. response.Send();
  1466. //response.FreeContext();
  1467. }
  1468. catch (SocketException e)
  1469. {
  1470. // This has to be here to prevent a Linux/Mono crash
  1471. m_log.WarnFormat("[BASE HTTP SERVER] XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  1472. }
  1473. }
  1474. }
  1475. public void Start()
  1476. {
  1477. StartHTTP();
  1478. }
  1479. private void StartHTTP()
  1480. {
  1481. try
  1482. {
  1483. //m_httpListener = new HttpListener();
  1484. NotSocketErrors = 0;
  1485. if (!m_ssl)
  1486. {
  1487. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1488. //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/");
  1489. m_httpListener2 = CoolHTTPListener.Create(m_listenIPAddress, (int)m_port);
  1490. m_httpListener2.ExceptionThrown += httpServerException;
  1491. m_httpListener2.LogWriter = httpserverlog;
  1492. // Uncomment this line in addition to those in HttpServerLogWriter
  1493. // if you want more detailed trace information from the HttpServer
  1494. //m_httpListener2.UseTraceLogs = true;
  1495. //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
  1496. }
  1497. else
  1498. {
  1499. //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
  1500. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1501. m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert);
  1502. m_httpListener2.ExceptionThrown += httpServerException;
  1503. m_httpListener2.LogWriter = httpserverlog;
  1504. }
  1505. m_httpListener2.RequestReceived += OnRequest;
  1506. //m_httpListener.Start();
  1507. m_httpListener2.Start(64);
  1508. // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events
  1509. m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000);
  1510. HTTPDRunning = true;
  1511. //HttpListenerContext context;
  1512. //while (true)
  1513. //{
  1514. // context = m_httpListener.GetContext();
  1515. // ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(HandleRequest), context);
  1516. // }
  1517. }
  1518. catch (Exception e)
  1519. {
  1520. m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
  1521. m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?");
  1522. // We want this exception to halt the entire server since in current configurations we aren't too
  1523. // useful without inbound HTTP.
  1524. throw e;
  1525. }
  1526. }
  1527. public void httpServerDisconnectMonitor(IHttpClientContext source, SocketError err)
  1528. {
  1529. switch (err)
  1530. {
  1531. case SocketError.NotSocket:
  1532. NotSocketErrors++;
  1533. break;
  1534. }
  1535. }
  1536. public void httpServerException(object source, Exception exception)
  1537. {
  1538. m_log.ErrorFormat("[BASE HTTP SERVER]: {0} had an exception {1}", source.ToString(), exception.ToString());
  1539. /*
  1540. if (HTTPDRunning)// && NotSocketErrors > 5)
  1541. {
  1542. Stop();
  1543. Thread.Sleep(200);
  1544. StartHTTP();
  1545. m_log.Warn("[HTTPSERVER]: Died. Trying to kick.....");
  1546. }
  1547. */
  1548. }
  1549. public void Stop()
  1550. {
  1551. HTTPDRunning = false;
  1552. try
  1553. {
  1554. m_httpListener2.ExceptionThrown -= httpServerException;
  1555. //m_httpListener2.DisconnectHandler = null;
  1556. m_httpListener2.LogWriter = null;
  1557. m_httpListener2.RequestReceived -= OnRequest;
  1558. m_httpListener2.Stop();
  1559. }
  1560. catch (NullReferenceException)
  1561. {
  1562. m_log.Warn("[BASE HTTP SERVER]: Null Reference when stopping HttpServer.");
  1563. }
  1564. }
  1565. public void RemoveStreamHandler(string httpMethod, string path)
  1566. {
  1567. string handlerKey = GetHandlerKey(httpMethod, path);
  1568. //m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey);
  1569. lock (m_streamHandlers)
  1570. m_streamHandlers.Remove(handlerKey);
  1571. }
  1572. public void RemoveHTTPHandler(string httpMethod, string path)
  1573. {
  1574. lock (m_HTTPHandlers)
  1575. {
  1576. if (httpMethod != null && httpMethod.Length == 0)
  1577. {
  1578. m_HTTPHandlers.Remove(path);
  1579. return;
  1580. }
  1581. m_HTTPHandlers.Remove(GetHandlerKey(httpMethod, path));
  1582. }
  1583. }
  1584. public void RemovePollServiceHTTPHandler(string httpMethod, string path)
  1585. {
  1586. lock (m_pollHandlers)
  1587. m_pollHandlers.Remove(path);
  1588. RemoveHTTPHandler(httpMethod, path);
  1589. }
  1590. public bool RemoveAgentHandler(string agent, IHttpAgentHandler handler)
  1591. {
  1592. lock (m_agentHandlers)
  1593. {
  1594. IHttpAgentHandler foundHandler;
  1595. if (m_agentHandlers.TryGetValue(agent, out foundHandler) && foundHandler == handler)
  1596. {
  1597. m_agentHandlers.Remove(agent);
  1598. return true;
  1599. }
  1600. }
  1601. return false;
  1602. }
  1603. public void RemoveXmlRPCHandler(string method)
  1604. {
  1605. lock (m_rpcHandlers)
  1606. m_rpcHandlers.Remove(method);
  1607. }
  1608. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  1609. {
  1610. lock (m_llsdHandlers)
  1611. {
  1612. LLSDMethod foundHandler;
  1613. if (m_llsdHandlers.TryGetValue(path, out foundHandler) && foundHandler == handler)
  1614. {
  1615. m_llsdHandlers.Remove(path);
  1616. return true;
  1617. }
  1618. }
  1619. return false;
  1620. }
  1621. public string GetHTTP404(string host)
  1622. {
  1623. string file = Path.Combine(".", "http_404.html");
  1624. if (!File.Exists(file))
  1625. return getDefaultHTTP404(host);
  1626. StreamReader sr = File.OpenText(file);
  1627. string result = sr.ReadToEnd();
  1628. sr.Close();
  1629. return result;
  1630. }
  1631. public string GetHTTP500()
  1632. {
  1633. string file = Path.Combine(".", "http_500.html");
  1634. if (!File.Exists(file))
  1635. return getDefaultHTTP500();
  1636. StreamReader sr = File.OpenText(file);
  1637. string result = sr.ReadToEnd();
  1638. sr.Close();
  1639. return result;
  1640. }
  1641. // Fallback HTTP responses in case the HTTP error response files don't exist
  1642. private static string getDefaultHTTP404(string host)
  1643. {
  1644. return "<HTML><HEAD><TITLE>404 Page not found</TITLE><BODY><BR /><H1>Ooops!</H1><P>The page you requested has been obsconded with by knomes. Find hippos quick!</P><P>If you are trying to log-in, your link parameters should have: &quot;-loginpage http://" + host + "/?method=login -loginuri http://" + host + "/&quot; in your link </P></BODY></HTML>";
  1645. }
  1646. private static string getDefaultHTTP500()
  1647. {
  1648. return "<HTML><HEAD><TITLE>500 Internal Server Error</TITLE><BODY><BR /><H1>Ooops!</H1><P>The server you requested is overun by knomes! Find hippos quick!</P></BODY></HTML>";
  1649. }
  1650. }
  1651. public class HttpServerContextObj
  1652. {
  1653. public IHttpClientContext context = null;
  1654. public IHttpRequest req = null;
  1655. public OSHttpRequest oreq = null;
  1656. public OSHttpResponse oresp = null;
  1657. public HttpServerContextObj(IHttpClientContext contxt, IHttpRequest reqs)
  1658. {
  1659. context = contxt;
  1660. req = reqs;
  1661. }
  1662. public HttpServerContextObj(OSHttpRequest osreq, OSHttpResponse osresp)
  1663. {
  1664. oreq = osreq;
  1665. oresp = osresp;
  1666. }
  1667. }
  1668. /// <summary>
  1669. /// Relays HttpServer log messages to our own logging mechanism.
  1670. /// </summary>
  1671. /// To use this you must uncomment the switch section
  1672. ///
  1673. /// You may also be able to get additional trace information from HttpServer if you uncomment the UseTraceLogs
  1674. /// property in StartHttp() for the HttpListener
  1675. public class HttpServerLogWriter : ILogWriter
  1676. {
  1677. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1678. public void Write(object source, LogPrio priority, string message)
  1679. {
  1680. /*
  1681. switch (priority)
  1682. {
  1683. case LogPrio.Trace:
  1684. m_log.DebugFormat("[{0}]: {1}", source, message);
  1685. break;
  1686. case LogPrio.Debug:
  1687. m_log.DebugFormat("[{0}]: {1}", source, message);
  1688. break;
  1689. case LogPrio.Error:
  1690. m_log.ErrorFormat("[{0}]: {1}", source, message);
  1691. break;
  1692. case LogPrio.Info:
  1693. m_log.InfoFormat("[{0}]: {1}", source, message);
  1694. break;
  1695. case LogPrio.Warning:
  1696. m_log.WarnFormat("[{0}]: {1}", source, message);
  1697. break;
  1698. case LogPrio.Fatal:
  1699. m_log.ErrorFormat("[{0}]: FATAL! - {1}", source, message);
  1700. break;
  1701. default:
  1702. break;
  1703. }
  1704. */
  1705. return;
  1706. }
  1707. }
  1708. }