1
0

BaseHttpServer.cs 70 KB

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