BaseHttpServer.cs 81 KB

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