BaseHttpServer.cs 73 KB

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