BaseHttpServer.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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 HttpListener=System.Net.HttpListener;
  44. using LogPrio=HttpServer.LogPrio;
  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 to " + 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.DebugFormat(
  419. // "[BASE HTTP SERVER]: Found a text/html content type for request {0}", request.RawUrl);
  420. HandleHTTPRequest(request, response);
  421. return;
  422. case "application/llsd+xml":
  423. case "application/xml+llsd":
  424. case "application/llsd+json":
  425. //m_log.Info("[Debug BASE HTTP SERVER]: found a application/llsd+xml content type");
  426. HandleLLSDRequests(request, response);
  427. return;
  428. case "text/xml":
  429. case "application/xml":
  430. case "application/json":
  431. default:
  432. //m_log.Info("[Debug BASE HTTP SERVER]: in default handler");
  433. // Point of note.. the DoWeHaveA methods check for an EXACT path
  434. // if (request.RawUrl.Contains("/CAPS/EQG"))
  435. // {
  436. // int i = 1;
  437. // }
  438. //m_log.Info("[Debug BASE HTTP SERVER]: Checking for LLSD Handler");
  439. if (DoWeHaveALLSDHandler(request.RawUrl))
  440. {
  441. //m_log.Info("[Debug BASE HTTP SERVER]: Found LLSD Handler");
  442. HandleLLSDRequests(request, response);
  443. return;
  444. }
  445. // m_log.DebugFormat("[BASE HTTP SERVER]: Checking for HTTP Handler for request {0}", request.RawUrl);
  446. if (DoWeHaveAHTTPHandler(request.RawUrl))
  447. {
  448. // m_log.DebugFormat("[BASE HTTP SERVER]: Found HTTP Handler for request {0}", request.RawUrl);
  449. HandleHTTPRequest(request, response);
  450. return;
  451. }
  452. //m_log.Info("[Debug BASE HTTP SERVER]: Generic XMLRPC");
  453. // generic login request.
  454. HandleXmlRpcRequests(request, response);
  455. return;
  456. }
  457. }
  458. catch (SocketException e)
  459. {
  460. // At least on linux, it appears that if the client makes a request without requiring the response,
  461. // an unconnected socket exception is thrown when we close the response output stream. There's no
  462. // obvious way to tell if the client didn't require the response, so instead we'll catch and ignore
  463. // the exception instead.
  464. //
  465. // An alternative may be to turn off all response write exceptions on the HttpListener, but let's go
  466. // with the minimum first
  467. m_log.WarnFormat("[BASE HTTP SERVER]: HandleRequest threw {0}.\nNOTE: this may be spurious on Linux", e);
  468. }
  469. catch (IOException e)
  470. {
  471. m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw ", e);
  472. }
  473. catch (InvalidOperationException e)
  474. {
  475. m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw {0}", e);
  476. SendHTML500(response);
  477. }
  478. }
  479. private bool TryGetStreamHandler(string handlerKey, out IRequestHandler streamHandler)
  480. {
  481. string bestMatch = null;
  482. lock (m_streamHandlers)
  483. {
  484. foreach (string pattern in m_streamHandlers.Keys)
  485. {
  486. if (handlerKey.StartsWith(pattern))
  487. {
  488. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  489. {
  490. bestMatch = pattern;
  491. }
  492. }
  493. }
  494. if (String.IsNullOrEmpty(bestMatch))
  495. {
  496. streamHandler = null;
  497. return false;
  498. }
  499. else
  500. {
  501. streamHandler = m_streamHandlers[bestMatch];
  502. return true;
  503. }
  504. }
  505. }
  506. private bool TryGetPollServiceHTTPHandler(string handlerKey, out PollServiceEventArgs oServiceEventArgs)
  507. {
  508. string bestMatch = null;
  509. lock (m_pollHandlers)
  510. {
  511. foreach (string pattern in m_pollHandlers.Keys)
  512. {
  513. if (handlerKey.StartsWith(pattern))
  514. {
  515. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  516. {
  517. bestMatch = pattern;
  518. }
  519. }
  520. }
  521. if (String.IsNullOrEmpty(bestMatch))
  522. {
  523. oServiceEventArgs = null;
  524. return false;
  525. }
  526. else
  527. {
  528. oServiceEventArgs = m_pollHandlers[bestMatch];
  529. return true;
  530. }
  531. }
  532. }
  533. private bool TryGetHTTPHandler(string handlerKey, out GenericHTTPMethod HTTPHandler)
  534. {
  535. // m_log.DebugFormat("[BASE HTTP HANDLER]: Looking for HTTP handler for {0}", handlerKey);
  536. string bestMatch = null;
  537. lock (m_HTTPHandlers)
  538. {
  539. foreach (string pattern in m_HTTPHandlers.Keys)
  540. {
  541. if (handlerKey.StartsWith(pattern))
  542. {
  543. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  544. {
  545. bestMatch = pattern;
  546. }
  547. }
  548. }
  549. if (String.IsNullOrEmpty(bestMatch))
  550. {
  551. HTTPHandler = null;
  552. return false;
  553. }
  554. else
  555. {
  556. HTTPHandler = m_HTTPHandlers[bestMatch];
  557. return true;
  558. }
  559. }
  560. }
  561. private bool TryGetAgentHandler(OSHttpRequest request, OSHttpResponse response, out IHttpAgentHandler agentHandler)
  562. {
  563. agentHandler = null;
  564. try
  565. {
  566. foreach (IHttpAgentHandler handler in m_agentHandlers.Values)
  567. {
  568. if (handler.Match(request, response))
  569. {
  570. agentHandler = handler;
  571. return true;
  572. }
  573. }
  574. }
  575. catch(KeyNotFoundException)
  576. {
  577. }
  578. return false;
  579. }
  580. /// <summary>
  581. /// Try all the registered xmlrpc handlers when an xmlrpc request is received.
  582. /// Sends back an XMLRPC unknown request response if no handler is registered for the requested method.
  583. /// </summary>
  584. /// <param name="request"></param>
  585. /// <param name="response"></param>
  586. private void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
  587. {
  588. Stream requestStream = request.InputStream;
  589. Encoding encoding = Encoding.UTF8;
  590. StreamReader reader = new StreamReader(requestStream, encoding);
  591. string requestBody = reader.ReadToEnd();
  592. reader.Close();
  593. requestStream.Close();
  594. //m_log.Debug(requestBody);
  595. requestBody = requestBody.Replace("<base64></base64>", "");
  596. string responseString = String.Empty;
  597. XmlRpcRequest xmlRprcRequest = null;
  598. try
  599. {
  600. xmlRprcRequest = (XmlRpcRequest) (new XmlRpcRequestDeserializer()).Deserialize(requestBody);
  601. }
  602. catch (XmlException)
  603. {
  604. }
  605. if (xmlRprcRequest != null)
  606. {
  607. string methodName = xmlRprcRequest.MethodName;
  608. if (methodName != null)
  609. {
  610. xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
  611. XmlRpcResponse xmlRpcResponse;
  612. XmlRpcMethod method;
  613. bool methodWasFound;
  614. lock (m_rpcHandlers)
  615. {
  616. methodWasFound = m_rpcHandlers.TryGetValue(methodName, out method);
  617. }
  618. if (methodWasFound)
  619. {
  620. xmlRprcRequest.Params.Add(request.Url); // Param[2]
  621. try
  622. {
  623. xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
  624. }
  625. catch(Exception e)
  626. {
  627. string errorMessage
  628. = String.Format(
  629. "Requested method [{0}] from {1} threw exception: {2} {3}",
  630. methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace);
  631. m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
  632. // if the registered XmlRpc method threw an exception, we pass a fault-code along
  633. xmlRpcResponse = new XmlRpcResponse();
  634. // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  635. xmlRpcResponse.SetFault(-32603, errorMessage);
  636. }
  637. // if the method wasn't found, we can't determine KeepAlive state anyway, so lets do it only here
  638. response.KeepAlive = m_rpcHandlersKeepAlive[methodName];
  639. }
  640. else
  641. {
  642. xmlRpcResponse = new XmlRpcResponse();
  643. // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  644. xmlRpcResponse.SetFault(
  645. XmlRpcErrorCodes.SERVER_ERROR_METHOD,
  646. String.Format("Requested method [{0}] not found", methodName));
  647. }
  648. responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse);
  649. }
  650. else
  651. {
  652. //HandleLLSDRequests(request, response);
  653. response.ContentType = "text/plain";
  654. response.StatusCode = 404;
  655. response.StatusDescription = "Not Found";
  656. response.ProtocolVersion = "HTTP/1.0";
  657. byte[] buf = Encoding.UTF8.GetBytes("Not found");
  658. response.KeepAlive = false;
  659. m_log.ErrorFormat("[BASE HTTP SERVER]: Handler not found for http request {0}", request.RawUrl);
  660. response.SendChunked = false;
  661. response.ContentLength64 = buf.Length;
  662. response.ContentEncoding = Encoding.UTF8;
  663. try
  664. {
  665. response.OutputStream.Write(buf, 0, buf.Length);
  666. }
  667. catch (Exception ex)
  668. {
  669. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  670. }
  671. finally
  672. {
  673. try
  674. {
  675. response.Send();
  676. //response.FreeContext();
  677. }
  678. catch (SocketException e)
  679. {
  680. // This has to be here to prevent a Linux/Mono crash
  681. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  682. }
  683. catch (IOException e)
  684. {
  685. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  686. }
  687. }
  688. return;
  689. //responseString = "Error";
  690. }
  691. }
  692. response.ContentType = "text/xml";
  693. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  694. response.SendChunked = false;
  695. response.ContentLength64 = buffer.Length;
  696. response.ContentEncoding = Encoding.UTF8;
  697. try
  698. {
  699. response.OutputStream.Write(buffer, 0, buffer.Length);
  700. }
  701. catch (Exception ex)
  702. {
  703. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  704. }
  705. finally
  706. {
  707. try
  708. {
  709. response.Send();
  710. //response.FreeContext();
  711. }
  712. catch (SocketException e)
  713. {
  714. // This has to be here to prevent a Linux/Mono crash
  715. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  716. }
  717. catch (IOException e)
  718. {
  719. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  720. }
  721. }
  722. }
  723. private void HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response)
  724. {
  725. //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
  726. Stream requestStream = request.InputStream;
  727. Encoding encoding = Encoding.UTF8;
  728. StreamReader reader = new StreamReader(requestStream, encoding);
  729. string requestBody = reader.ReadToEnd();
  730. reader.Close();
  731. requestStream.Close();
  732. //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
  733. response.KeepAlive = true;
  734. OSD llsdRequest = null;
  735. OSD llsdResponse = null;
  736. bool LegacyLLSDLoginLibOMV = (requestBody.Contains("passwd") && requestBody.Contains("mac") && requestBody.Contains("viewer_digest"));
  737. if (requestBody.Length == 0)
  738. // Get Request
  739. {
  740. requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>";
  741. }
  742. try
  743. {
  744. llsdRequest = OSDParser.Deserialize(requestBody);
  745. }
  746. catch (Exception ex)
  747. {
  748. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  749. }
  750. if (llsdRequest != null)// && m_defaultLlsdHandler != null)
  751. {
  752. LLSDMethod llsdhandler = null;
  753. if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV)
  754. {
  755. // we found a registered llsd handler to service this request
  756. llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint.ToString());
  757. }
  758. else
  759. {
  760. // we didn't find a registered llsd handler to service this request
  761. // check if we have a default llsd handler
  762. if (m_defaultLlsdHandler != null)
  763. {
  764. // LibOMV path
  765. llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
  766. }
  767. else
  768. {
  769. // Oops, no handler for this.. give em the failed message
  770. llsdResponse = GenerateNoLLSDHandlerResponse();
  771. }
  772. }
  773. }
  774. else
  775. {
  776. llsdResponse = GenerateNoLLSDHandlerResponse();
  777. }
  778. byte[] buffer = new byte[0];
  779. if (llsdResponse.ToString() == "shutdown404!")
  780. {
  781. response.ContentType = "text/plain";
  782. response.StatusCode = 404;
  783. response.StatusDescription = "Not Found";
  784. response.ProtocolVersion = "HTTP/1.0";
  785. buffer = Encoding.UTF8.GetBytes("Not found");
  786. }
  787. else
  788. {
  789. // Select an appropriate response format
  790. buffer = BuildLLSDResponse(request, response, llsdResponse);
  791. }
  792. response.SendChunked = false;
  793. response.ContentLength64 = buffer.Length;
  794. response.ContentEncoding = Encoding.UTF8;
  795. response.KeepAlive = true;
  796. try
  797. {
  798. response.OutputStream.Write(buffer, 0, buffer.Length);
  799. }
  800. catch (Exception ex)
  801. {
  802. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  803. }
  804. finally
  805. {
  806. //response.OutputStream.Close();
  807. try
  808. {
  809. response.Send();
  810. response.OutputStream.Flush();
  811. //response.FreeContext();
  812. //response.OutputStream.Close();
  813. }
  814. catch (IOException e)
  815. {
  816. m_log.WarnFormat("[BASE HTTP SERVER]: LLSD IOException {0}.", e);
  817. }
  818. catch (SocketException e)
  819. {
  820. // This has to be here to prevent a Linux/Mono crash
  821. m_log.WarnFormat("[BASE HTTP SERVER]: LLSD issue {0}.\nNOTE: this may be spurious on Linux.", e);
  822. }
  823. }
  824. }
  825. private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
  826. {
  827. if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
  828. {
  829. foreach (string strAccept in request.AcceptTypes)
  830. {
  831. switch (strAccept)
  832. {
  833. case "application/llsd+xml":
  834. case "application/xml":
  835. case "text/xml":
  836. response.ContentType = strAccept;
  837. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  838. case "application/llsd+json":
  839. case "application/json":
  840. response.ContentType = strAccept;
  841. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  842. }
  843. }
  844. }
  845. if (!String.IsNullOrEmpty(request.ContentType))
  846. {
  847. switch (request.ContentType)
  848. {
  849. case "application/llsd+xml":
  850. case "application/xml":
  851. case "text/xml":
  852. response.ContentType = request.ContentType;
  853. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  854. case "application/llsd+json":
  855. case "application/json":
  856. response.ContentType = request.ContentType;
  857. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  858. }
  859. }
  860. // response.ContentType = "application/llsd+json";
  861. // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  862. response.ContentType = "application/llsd+xml";
  863. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  864. }
  865. /// <summary>
  866. /// Checks if we have an Exact path in the LLSD handlers for the path provided
  867. /// </summary>
  868. /// <param name="path">URI of the request</param>
  869. /// <returns>true if we have one, false if not</returns>
  870. private bool DoWeHaveALLSDHandler(string path)
  871. {
  872. string[] pathbase = path.Split('/');
  873. string searchquery = "/";
  874. if (pathbase.Length < 1)
  875. return false;
  876. for (int i = 1; i < pathbase.Length; i++)
  877. {
  878. searchquery += pathbase[i];
  879. if (pathbase.Length - 1 != i)
  880. searchquery += "/";
  881. }
  882. string bestMatch = null;
  883. foreach (string pattern in m_llsdHandlers.Keys)
  884. {
  885. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  886. {
  887. bestMatch = pattern;
  888. }
  889. }
  890. // extra kicker to remove the default XMLRPC login case.. just in case..
  891. if (path != "/" && bestMatch == "/" && searchquery != "/")
  892. return false;
  893. if (path == "/")
  894. return false;
  895. if (String.IsNullOrEmpty(bestMatch))
  896. {
  897. return false;
  898. }
  899. else
  900. {
  901. return true;
  902. }
  903. }
  904. /// <summary>
  905. /// Checks if we have an Exact path in the HTTP handlers for the path provided
  906. /// </summary>
  907. /// <param name="path">URI of the request</param>
  908. /// <returns>true if we have one, false if not</returns>
  909. private bool DoWeHaveAHTTPHandler(string path)
  910. {
  911. string[] pathbase = path.Split('/');
  912. string searchquery = "/";
  913. if (pathbase.Length < 1)
  914. return false;
  915. for (int i = 1; i < pathbase.Length; i++)
  916. {
  917. searchquery += pathbase[i];
  918. if (pathbase.Length - 1 != i)
  919. searchquery += "/";
  920. }
  921. string bestMatch = null;
  922. //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
  923. lock (m_HTTPHandlers)
  924. {
  925. foreach (string pattern in m_HTTPHandlers.Keys)
  926. {
  927. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  928. {
  929. bestMatch = pattern;
  930. }
  931. }
  932. // extra kicker to remove the default XMLRPC login case.. just in case..
  933. if (path == "/")
  934. return false;
  935. if (String.IsNullOrEmpty(bestMatch))
  936. {
  937. return false;
  938. }
  939. else
  940. {
  941. return true;
  942. }
  943. }
  944. }
  945. private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
  946. {
  947. llsdHandler = null;
  948. // Pull out the first part of the path
  949. // splitting the path by '/' means we'll get the following return..
  950. // {0}/{1}/{2}
  951. // where {0} isn't something we really control 100%
  952. string[] pathbase = path.Split('/');
  953. string searchquery = "/";
  954. if (pathbase.Length < 1)
  955. return false;
  956. for (int i=1; i<pathbase.Length; i++)
  957. {
  958. searchquery += pathbase[i];
  959. if (pathbase.Length-1 != i)
  960. searchquery += "/";
  961. }
  962. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  963. //
  964. // [] = optional
  965. // /resource/UUID/action[/action]
  966. //
  967. // now try to get the closest match to the reigstered path
  968. // at least for OGP, registered path would probably only consist of the /resource/
  969. string bestMatch = null;
  970. foreach (string pattern in m_llsdHandlers.Keys)
  971. {
  972. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  973. {
  974. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  975. {
  976. // You have to specifically register for '/' and to get it, you must specificaly request it
  977. //
  978. if (pattern == "/" && searchquery == "/" || pattern != "/")
  979. bestMatch = pattern;
  980. }
  981. }
  982. }
  983. if (String.IsNullOrEmpty(bestMatch))
  984. {
  985. llsdHandler = null;
  986. return false;
  987. }
  988. else
  989. {
  990. llsdHandler = m_llsdHandlers[bestMatch];
  991. return true;
  992. }
  993. }
  994. private OSDMap GenerateNoLLSDHandlerResponse()
  995. {
  996. OSDMap map = new OSDMap();
  997. map["reason"] = OSD.FromString("LLSDRequest");
  998. map["message"] = OSD.FromString("No handler registered for LLSD Requests");
  999. map["login"] = OSD.FromString("false");
  1000. return map;
  1001. }
  1002. /// <summary>
  1003. /// A specific agent handler was provided. Such a handler is expecetd to have an
  1004. /// intimate, and highly specific relationship with the client. Consequently,
  1005. /// nothing is done here.
  1006. /// </summary>
  1007. /// <param name="handler"></param>
  1008. /// <param name="request"></param>
  1009. /// <param name="response"></param>
  1010. private bool HandleAgentRequest(IHttpAgentHandler handler, OSHttpRequest request, OSHttpResponse response)
  1011. {
  1012. // In the case of REST, then handler is responsible for ALL aspects of
  1013. // the request/response handling. Nothing is done here, not even encoding.
  1014. try
  1015. {
  1016. return handler.Handle(request, response);
  1017. }
  1018. catch (Exception e)
  1019. {
  1020. // If the handler did in fact close the stream, then this will blow
  1021. // chunks. So that that doesn't disturb anybody we throw away any
  1022. // and all exceptions raised. We've done our best to release the
  1023. // client.
  1024. try
  1025. {
  1026. m_log.Warn("[HTTP-AGENT]: Error - " + e.Message);
  1027. response.SendChunked = false;
  1028. response.KeepAlive = true;
  1029. response.StatusCode = (int)OSHttpStatusCode.ServerErrorInternalError;
  1030. //response.OutputStream.Close();
  1031. try
  1032. {
  1033. response.Send();
  1034. //response.FreeContext();
  1035. }
  1036. catch (SocketException f)
  1037. {
  1038. // This has to be here to prevent a Linux/Mono crash
  1039. m_log.WarnFormat(
  1040. "[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", f);
  1041. }
  1042. }
  1043. catch(Exception)
  1044. {
  1045. }
  1046. }
  1047. // Indicate that the request has been "handled"
  1048. return true;
  1049. }
  1050. public void HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
  1051. {
  1052. // m_log.DebugFormat(
  1053. // "[BASE HTTP SERVER]: HandleHTTPRequest for request to {0}, method {1}",
  1054. // request.RawUrl, request.HttpMethod);
  1055. switch (request.HttpMethod)
  1056. {
  1057. case "OPTIONS":
  1058. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1059. return;
  1060. default:
  1061. HandleContentVerbs(request, response);
  1062. return;
  1063. }
  1064. }
  1065. private void HandleContentVerbs(OSHttpRequest request, OSHttpResponse response)
  1066. {
  1067. // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl);
  1068. // This is a test. There's a workable alternative.. as this way sucks.
  1069. // We'd like to put this into a text file parhaps that's easily editable.
  1070. //
  1071. // For this test to work, I used the following secondlife.exe parameters
  1072. // "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
  1073. //
  1074. // Even after all that, there's still an error, but it's a start.
  1075. //
  1076. // I depend on show_login_form being in the secondlife.exe parameters to figure out
  1077. // to display the form, or process it.
  1078. // a better way would be nifty.
  1079. Stream requestStream = request.InputStream;
  1080. Encoding encoding = Encoding.UTF8;
  1081. StreamReader reader = new StreamReader(requestStream, encoding);
  1082. string requestBody = reader.ReadToEnd();
  1083. // avoid warning for now
  1084. reader.ReadToEnd();
  1085. reader.Close();
  1086. requestStream.Close();
  1087. Hashtable keysvals = new Hashtable();
  1088. Hashtable headervals = new Hashtable();
  1089. Hashtable requestVars = new Hashtable();
  1090. string host = String.Empty;
  1091. string[] querystringkeys = request.QueryString.AllKeys;
  1092. string[] rHeaders = request.Headers.AllKeys;
  1093. keysvals.Add("body", requestBody);
  1094. keysvals.Add("uri", request.RawUrl);
  1095. keysvals.Add("content-type", request.ContentType);
  1096. keysvals.Add("http-method", request.HttpMethod);
  1097. foreach (string queryname in querystringkeys)
  1098. {
  1099. // m_log.DebugFormat(
  1100. // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
  1101. keysvals.Add(queryname, request.QueryString[queryname]);
  1102. requestVars.Add(queryname, keysvals[queryname]);
  1103. }
  1104. foreach (string headername in rHeaders)
  1105. {
  1106. // m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
  1107. headervals[headername] = request.Headers[headername];
  1108. }
  1109. if (headervals.Contains("Host"))
  1110. {
  1111. host = (string)headervals["Host"];
  1112. }
  1113. keysvals.Add("headers", headervals);
  1114. keysvals.Add("querystringkeys", querystringkeys);
  1115. keysvals.Add("requestvars", requestVars);
  1116. // keysvals.Add("form", request.Form);
  1117. if (keysvals.Contains("method"))
  1118. {
  1119. // m_log.Debug("[BASE HTTP SERVER]: Contains Method");
  1120. string method = (string) keysvals["method"];
  1121. // m_log.Debug("[BASE HTTP SERVER]: " + requestBody);
  1122. GenericHTTPMethod requestprocessor;
  1123. bool foundHandler = TryGetHTTPHandler(method, out requestprocessor);
  1124. if (foundHandler)
  1125. {
  1126. Hashtable responsedata1 = requestprocessor(keysvals);
  1127. DoHTTPGruntWork(responsedata1,response);
  1128. //SendHTML500(response);
  1129. }
  1130. else
  1131. {
  1132. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found");
  1133. SendHTML404(response, host);
  1134. }
  1135. }
  1136. else
  1137. {
  1138. GenericHTTPMethod requestprocessor;
  1139. bool foundHandler = TryGetHTTPHandlerPathBased(request.RawUrl, out requestprocessor);
  1140. if (foundHandler)
  1141. {
  1142. Hashtable responsedata2 = requestprocessor(keysvals);
  1143. DoHTTPGruntWork(responsedata2, response);
  1144. //SendHTML500(response);
  1145. }
  1146. else
  1147. {
  1148. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found2");
  1149. SendHTML404(response, host);
  1150. }
  1151. }
  1152. }
  1153. private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
  1154. {
  1155. httpHandler = null;
  1156. // Pull out the first part of the path
  1157. // splitting the path by '/' means we'll get the following return..
  1158. // {0}/{1}/{2}
  1159. // where {0} isn't something we really control 100%
  1160. string[] pathbase = path.Split('/');
  1161. string searchquery = "/";
  1162. if (pathbase.Length < 1)
  1163. return false;
  1164. for (int i = 1; i < pathbase.Length; i++)
  1165. {
  1166. searchquery += pathbase[i];
  1167. if (pathbase.Length - 1 != i)
  1168. searchquery += "/";
  1169. }
  1170. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1171. //
  1172. // [] = optional
  1173. // /resource/UUID/action[/action]
  1174. //
  1175. // now try to get the closest match to the reigstered path
  1176. // at least for OGP, registered path would probably only consist of the /resource/
  1177. string bestMatch = null;
  1178. // m_log.DebugFormat(
  1179. // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
  1180. lock (m_HTTPHandlers)
  1181. {
  1182. foreach (string pattern in m_HTTPHandlers.Keys)
  1183. {
  1184. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1185. {
  1186. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1187. {
  1188. // You have to specifically register for '/' and to get it, you must specifically request it
  1189. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1190. bestMatch = pattern;
  1191. }
  1192. }
  1193. }
  1194. if (String.IsNullOrEmpty(bestMatch))
  1195. {
  1196. httpHandler = null;
  1197. return false;
  1198. }
  1199. else
  1200. {
  1201. if (bestMatch == "/" && searchquery != "/")
  1202. return false;
  1203. httpHandler = m_HTTPHandlers[bestMatch];
  1204. return true;
  1205. }
  1206. }
  1207. }
  1208. internal void DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
  1209. {
  1210. //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
  1211. int responsecode = (int)responsedata["int_response_code"];
  1212. string responseString = (string)responsedata["str_response_string"];
  1213. string contentType = (string)responsedata["content_type"];
  1214. if (responsedata.ContainsKey("error_status_text"))
  1215. {
  1216. response.StatusDescription = (string)responsedata["error_status_text"];
  1217. }
  1218. if (responsedata.ContainsKey("http_protocol_version"))
  1219. {
  1220. response.ProtocolVersion = (string)responsedata["http_protocol_version"];
  1221. }
  1222. if (responsedata.ContainsKey("keepalive"))
  1223. {
  1224. bool keepalive = (bool)responsedata["keepalive"];
  1225. response.KeepAlive = keepalive;
  1226. }
  1227. if (responsedata.ContainsKey("reusecontext"))
  1228. response.ReuseContext = (bool) responsedata["reusecontext"];
  1229. //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
  1230. //and should check for NullReferenceExceptions
  1231. if (string.IsNullOrEmpty(contentType))
  1232. {
  1233. contentType = "text/html";
  1234. }
  1235. // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
  1236. response.StatusCode = responsecode;
  1237. if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently)
  1238. {
  1239. response.RedirectLocation = (string)responsedata["str_redirect_location"];
  1240. response.StatusCode = responsecode;
  1241. }
  1242. response.AddHeader("Content-Type", contentType);
  1243. byte[] buffer;
  1244. if (!(contentType.Contains("image")
  1245. || contentType.Contains("x-shockwave-flash")
  1246. || contentType.Contains("application/x-oar")))
  1247. {
  1248. // Text
  1249. buffer = Encoding.UTF8.GetBytes(responseString);
  1250. }
  1251. else
  1252. {
  1253. // Binary!
  1254. buffer = Convert.FromBase64String(responseString);
  1255. }
  1256. response.SendChunked = false;
  1257. response.ContentLength64 = buffer.Length;
  1258. response.ContentEncoding = Encoding.UTF8;
  1259. try
  1260. {
  1261. response.OutputStream.Write(buffer, 0, buffer.Length);
  1262. }
  1263. catch (Exception ex)
  1264. {
  1265. m_log.Warn("[HTTPD]: Error - " + ex.Message);
  1266. }
  1267. finally
  1268. {
  1269. //response.OutputStream.Close();
  1270. try
  1271. {
  1272. response.OutputStream.Flush();
  1273. response.Send();
  1274. //if (!response.KeepAlive && response.ReuseContext)
  1275. // response.FreeContext();
  1276. }
  1277. catch (SocketException e)
  1278. {
  1279. // This has to be here to prevent a Linux/Mono crash
  1280. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  1281. }
  1282. catch (IOException e)
  1283. {
  1284. m_log.Warn("[BASE HTTP SERVER]: XmlRpcRequest issue: " + e.Message);
  1285. }
  1286. }
  1287. }
  1288. public void SendHTML404(OSHttpResponse response, string host)
  1289. {
  1290. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1291. response.StatusCode = 404;
  1292. response.AddHeader("Content-type", "text/html");
  1293. string responseString = GetHTTP404(host);
  1294. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1295. response.SendChunked = false;
  1296. response.ContentLength64 = buffer.Length;
  1297. response.ContentEncoding = Encoding.UTF8;
  1298. try
  1299. {
  1300. response.OutputStream.Write(buffer, 0, buffer.Length);
  1301. }
  1302. catch (Exception ex)
  1303. {
  1304. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1305. }
  1306. finally
  1307. {
  1308. //response.OutputStream.Close();
  1309. try
  1310. {
  1311. response.Send();
  1312. //response.FreeContext();
  1313. }
  1314. catch (SocketException e)
  1315. {
  1316. // This has to be here to prevent a Linux/Mono crash
  1317. m_log.WarnFormat("[BASE HTTP SERVER]: XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  1318. }
  1319. }
  1320. }
  1321. public void SendHTML500(OSHttpResponse response)
  1322. {
  1323. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1324. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1325. response.AddHeader("Content-type", "text/html");
  1326. string responseString = GetHTTP500();
  1327. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1328. response.SendChunked = false;
  1329. response.ContentLength64 = buffer.Length;
  1330. response.ContentEncoding = Encoding.UTF8;
  1331. try
  1332. {
  1333. response.OutputStream.Write(buffer, 0, buffer.Length);
  1334. }
  1335. catch (Exception ex)
  1336. {
  1337. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1338. }
  1339. finally
  1340. {
  1341. //response.OutputStream.Close();
  1342. try
  1343. {
  1344. response.Send();
  1345. //response.FreeContext();
  1346. }
  1347. catch (SocketException e)
  1348. {
  1349. // This has to be here to prevent a Linux/Mono crash
  1350. m_log.WarnFormat("[BASE HTTP SERVER] XmlRpcRequest issue {0}.\nNOTE: this may be spurious on Linux.", e);
  1351. }
  1352. }
  1353. }
  1354. public void Start()
  1355. {
  1356. StartHTTP();
  1357. }
  1358. private void StartHTTP()
  1359. {
  1360. try
  1361. {
  1362. //m_httpListener = new HttpListener();
  1363. NotSocketErrors = 0;
  1364. if (!m_ssl)
  1365. {
  1366. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1367. //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/");
  1368. m_httpListener2 = CoolHTTPListener.Create(m_listenIPAddress, (int)m_port);
  1369. m_httpListener2.ExceptionThrown += httpServerException;
  1370. m_httpListener2.LogWriter = httpserverlog;
  1371. // Uncomment this line in addition to those in HttpServerLogWriter
  1372. // if you want more detailed trace information from the HttpServer
  1373. //m_httpListener2.UseTraceLogs = true;
  1374. //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
  1375. }
  1376. else
  1377. {
  1378. //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
  1379. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1380. }
  1381. m_httpListener2.RequestReceived += OnRequest;
  1382. //m_httpListener.Start();
  1383. m_httpListener2.Start(64);
  1384. // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events
  1385. m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000);
  1386. HTTPDRunning = true;
  1387. //HttpListenerContext context;
  1388. //while (true)
  1389. //{
  1390. // context = m_httpListener.GetContext();
  1391. // ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(HandleRequest), context);
  1392. // }
  1393. }
  1394. catch (Exception e)
  1395. {
  1396. m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
  1397. m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?");
  1398. // We want this exception to halt the entire server since in current configurations we aren't too
  1399. // useful without inbound HTTP.
  1400. throw e;
  1401. }
  1402. }
  1403. public void httpServerDisconnectMonitor(IHttpClientContext source, SocketError err)
  1404. {
  1405. switch (err)
  1406. {
  1407. case SocketError.NotSocket:
  1408. NotSocketErrors++;
  1409. break;
  1410. }
  1411. }
  1412. public void httpServerException(object source, Exception exception)
  1413. {
  1414. m_log.ErrorFormat("[BASE HTTP SERVER]: {0} had an exception {1}", source.ToString(), exception.ToString());
  1415. /*
  1416. if (HTTPDRunning)// && NotSocketErrors > 5)
  1417. {
  1418. Stop();
  1419. Thread.Sleep(200);
  1420. StartHTTP();
  1421. m_log.Warn("[HTTPSERVER]: Died. Trying to kick.....");
  1422. }
  1423. */
  1424. }
  1425. public void Stop()
  1426. {
  1427. HTTPDRunning = false;
  1428. try
  1429. {
  1430. m_httpListener2.ExceptionThrown -= httpServerException;
  1431. //m_httpListener2.DisconnectHandler = null;
  1432. m_httpListener2.LogWriter = null;
  1433. m_httpListener2.RequestReceived -= OnRequest;
  1434. m_httpListener2.Stop();
  1435. }
  1436. catch (NullReferenceException)
  1437. {
  1438. m_log.Warn("[BASE HTTP SERVER]: Null Reference when stopping HttpServer.");
  1439. }
  1440. }
  1441. public void RemoveStreamHandler(string httpMethod, string path)
  1442. {
  1443. string handlerKey = GetHandlerKey(httpMethod, path);
  1444. //m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey);
  1445. lock (m_streamHandlers) m_streamHandlers.Remove(handlerKey);
  1446. }
  1447. public void RemoveHTTPHandler(string httpMethod, string path)
  1448. {
  1449. lock (m_HTTPHandlers)
  1450. {
  1451. if (httpMethod != null && httpMethod.Length == 0)
  1452. {
  1453. m_HTTPHandlers.Remove(path);
  1454. return;
  1455. }
  1456. m_HTTPHandlers.Remove(GetHandlerKey(httpMethod, path));
  1457. }
  1458. }
  1459. public void RemovePollServiceHTTPHandler(string httpMethod, string path)
  1460. {
  1461. lock (m_pollHandlers)
  1462. {
  1463. if (m_pollHandlers.ContainsKey(httpMethod))
  1464. {
  1465. m_pollHandlers.Remove(httpMethod);
  1466. }
  1467. }
  1468. RemoveHTTPHandler(httpMethod, path);
  1469. }
  1470. public bool RemoveAgentHandler(string agent, IHttpAgentHandler handler)
  1471. {
  1472. try
  1473. {
  1474. if (handler == m_agentHandlers[agent])
  1475. {
  1476. m_agentHandlers.Remove(agent);
  1477. return true;
  1478. }
  1479. }
  1480. catch(KeyNotFoundException)
  1481. {
  1482. }
  1483. return false;
  1484. }
  1485. public void RemoveXmlRPCHandler(string method)
  1486. {
  1487. lock (m_rpcHandlers)
  1488. {
  1489. if (m_rpcHandlers.ContainsKey(method))
  1490. {
  1491. m_rpcHandlers.Remove(method);
  1492. }
  1493. }
  1494. }
  1495. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  1496. {
  1497. try
  1498. {
  1499. if (handler == m_llsdHandlers[path])
  1500. {
  1501. m_llsdHandlers.Remove(path);
  1502. return true;
  1503. }
  1504. }
  1505. catch (KeyNotFoundException)
  1506. {
  1507. // This is an exception to prevent crashing because of invalid code
  1508. }
  1509. return false;
  1510. }
  1511. public string GetHTTP404(string host)
  1512. {
  1513. string file = Path.Combine(".", "http_404.html");
  1514. if (!File.Exists(file))
  1515. return getDefaultHTTP404(host);
  1516. StreamReader sr = File.OpenText(file);
  1517. string result = sr.ReadToEnd();
  1518. sr.Close();
  1519. return result;
  1520. }
  1521. public string GetHTTP500()
  1522. {
  1523. string file = Path.Combine(".", "http_500.html");
  1524. if (!File.Exists(file))
  1525. return getDefaultHTTP500();
  1526. StreamReader sr = File.OpenText(file);
  1527. string result = sr.ReadToEnd();
  1528. sr.Close();
  1529. return result;
  1530. }
  1531. // Fallback HTTP responses in case the HTTP error response files don't exist
  1532. private static string getDefaultHTTP404(string host)
  1533. {
  1534. 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>";
  1535. }
  1536. private static string getDefaultHTTP500()
  1537. {
  1538. 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>";
  1539. }
  1540. }
  1541. public class HttpServerContextObj
  1542. {
  1543. public IHttpClientContext context = null;
  1544. public IHttpRequest req = null;
  1545. public OSHttpRequest oreq = null;
  1546. public OSHttpResponse oresp = null;
  1547. public HttpServerContextObj(IHttpClientContext contxt, IHttpRequest reqs)
  1548. {
  1549. context = contxt;
  1550. req = reqs;
  1551. }
  1552. public HttpServerContextObj(OSHttpRequest osreq, OSHttpResponse osresp)
  1553. {
  1554. oreq = osreq;
  1555. oresp = osresp;
  1556. }
  1557. }
  1558. /// <summary>
  1559. /// Relays HttpServer log messages to our own logging mechanism.
  1560. /// </summary>
  1561. /// To use this you must uncomment the switch section
  1562. ///
  1563. /// You may also be able to get additional trace information from HttpServer if you uncomment the UseTraceLogs
  1564. /// property in StartHttp() for the HttpListener
  1565. public class HttpServerLogWriter : ILogWriter
  1566. {
  1567. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1568. public void Write(object source, LogPrio priority, string message)
  1569. {
  1570. /*
  1571. switch (priority)
  1572. {
  1573. case LogPrio.Trace:
  1574. m_log.DebugFormat("[{0}]: {1}", source, message);
  1575. break;
  1576. case LogPrio.Debug:
  1577. m_log.DebugFormat("[{0}]: {1}", source, message);
  1578. break;
  1579. case LogPrio.Error:
  1580. m_log.ErrorFormat("[{0}]: {1}", source, message);
  1581. break;
  1582. case LogPrio.Info:
  1583. m_log.InfoFormat("[{0}]: {1}", source, message);
  1584. break;
  1585. case LogPrio.Warning:
  1586. m_log.WarnFormat("[{0}]: {1}", source, message);
  1587. break;
  1588. case LogPrio.Fatal:
  1589. m_log.ErrorFormat("[{0}]: FATAL! - {1}", source, message);
  1590. break;
  1591. default:
  1592. break;
  1593. }
  1594. */
  1595. return;
  1596. }
  1597. }
  1598. }