BaseHttpServer.cs 77 KB

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