BaseHttpServer.cs 80 KB

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