BaseHttpServer.cs 83 KB

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