1
0

BaseHttpServer.cs 70 KB

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