BaseHttpServer.cs 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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. bool nohandler = false;
  1023. if (requestBody.Length == 0)
  1024. // Get Request
  1025. {
  1026. requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>";
  1027. }
  1028. try
  1029. {
  1030. llsdRequest = OSDParser.Deserialize(requestBody);
  1031. }
  1032. catch (Exception ex)
  1033. {
  1034. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1035. }
  1036. if (llsdRequest != null)// && m_defaultLlsdHandler != null)
  1037. {
  1038. LLSDMethod llsdhandler = null;
  1039. if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV)
  1040. {
  1041. // we found a registered llsd handler to service this request
  1042. llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint.ToString());
  1043. }
  1044. else
  1045. {
  1046. // we didn't find a registered llsd handler to service this request
  1047. // check if we have a default llsd handler
  1048. if (m_defaultLlsdHandler != null)
  1049. {
  1050. // LibOMV path
  1051. llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
  1052. }
  1053. else
  1054. {
  1055. // Oops, no handler for this.. give em the failed message
  1056. llsdResponse = GenerateNoLLSDHandlerResponse();
  1057. nohandler = true;
  1058. }
  1059. }
  1060. }
  1061. else
  1062. {
  1063. llsdResponse = GenerateNoLLSDHandlerResponse();
  1064. nohandler = true;
  1065. }
  1066. byte[] buffer = new byte[0];
  1067. if (llsdResponse.ToString() == "shutdown404!" || nohandler)
  1068. {
  1069. response.ContentType = "text/plain";
  1070. response.StatusCode = 404;
  1071. response.StatusDescription = "Not Found";
  1072. response.ProtocolVersion = "HTTP/1.0";
  1073. buffer = Encoding.UTF8.GetBytes("Not found");
  1074. }
  1075. else
  1076. {
  1077. // Select an appropriate response format
  1078. buffer = BuildLLSDResponse(request, response, llsdResponse);
  1079. }
  1080. response.SendChunked = false;
  1081. response.ContentLength64 = buffer.Length;
  1082. response.ContentEncoding = Encoding.UTF8;
  1083. response.KeepAlive = true;
  1084. return buffer;
  1085. }
  1086. private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
  1087. {
  1088. if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
  1089. {
  1090. foreach (string strAccept in request.AcceptTypes)
  1091. {
  1092. switch (strAccept)
  1093. {
  1094. case "application/llsd+xml":
  1095. case "application/xml":
  1096. case "text/xml":
  1097. response.ContentType = strAccept;
  1098. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1099. case "application/llsd+json":
  1100. case "application/json":
  1101. response.ContentType = strAccept;
  1102. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1103. }
  1104. }
  1105. }
  1106. if (!String.IsNullOrEmpty(request.ContentType))
  1107. {
  1108. switch (request.ContentType)
  1109. {
  1110. case "application/llsd+xml":
  1111. case "application/xml":
  1112. case "text/xml":
  1113. response.ContentType = request.ContentType;
  1114. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1115. case "application/llsd+json":
  1116. case "application/json":
  1117. response.ContentType = request.ContentType;
  1118. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1119. }
  1120. }
  1121. // response.ContentType = "application/llsd+json";
  1122. // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1123. response.ContentType = "application/llsd+xml";
  1124. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1125. }
  1126. /// <summary>
  1127. /// Checks if we have an Exact path in the LLSD handlers for the path provided
  1128. /// </summary>
  1129. /// <param name="path">URI of the request</param>
  1130. /// <returns>true if we have one, false if not</returns>
  1131. private bool DoWeHaveALLSDHandler(string path)
  1132. {
  1133. string[] pathbase = path.Split('/');
  1134. string searchquery = "/";
  1135. if (pathbase.Length < 1)
  1136. return false;
  1137. for (int i = 1; i < pathbase.Length; i++)
  1138. {
  1139. searchquery += pathbase[i];
  1140. if (pathbase.Length - 1 != i)
  1141. searchquery += "/";
  1142. }
  1143. string bestMatch = null;
  1144. lock (m_llsdHandlers)
  1145. {
  1146. foreach (string pattern in m_llsdHandlers.Keys)
  1147. {
  1148. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1149. bestMatch = pattern;
  1150. }
  1151. }
  1152. // extra kicker to remove the default XMLRPC login case.. just in case..
  1153. if (path != "/" && bestMatch == "/" && searchquery != "/")
  1154. return false;
  1155. if (path == "/")
  1156. return false;
  1157. if (String.IsNullOrEmpty(bestMatch))
  1158. {
  1159. return false;
  1160. }
  1161. else
  1162. {
  1163. return true;
  1164. }
  1165. }
  1166. /// <summary>
  1167. /// Checks if we have an Exact path in the HTTP handlers for the path provided
  1168. /// </summary>
  1169. /// <param name="path">URI of the request</param>
  1170. /// <returns>true if we have one, false if not</returns>
  1171. private bool DoWeHaveAHTTPHandler(string path)
  1172. {
  1173. string[] pathbase = path.Split('/');
  1174. string searchquery = "/";
  1175. if (pathbase.Length < 1)
  1176. return false;
  1177. for (int i = 1; i < pathbase.Length; i++)
  1178. {
  1179. searchquery += pathbase[i];
  1180. if (pathbase.Length - 1 != i)
  1181. searchquery += "/";
  1182. }
  1183. string bestMatch = null;
  1184. //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
  1185. lock (m_HTTPHandlers)
  1186. {
  1187. foreach (string pattern in m_HTTPHandlers.Keys)
  1188. {
  1189. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1190. {
  1191. bestMatch = pattern;
  1192. }
  1193. }
  1194. // extra kicker to remove the default XMLRPC login case.. just in case..
  1195. if (path == "/")
  1196. return false;
  1197. if (String.IsNullOrEmpty(bestMatch))
  1198. {
  1199. return false;
  1200. }
  1201. else
  1202. {
  1203. return true;
  1204. }
  1205. }
  1206. }
  1207. private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
  1208. {
  1209. llsdHandler = null;
  1210. // Pull out the first part of the path
  1211. // splitting the path by '/' means we'll get the following return..
  1212. // {0}/{1}/{2}
  1213. // where {0} isn't something we really control 100%
  1214. string[] pathbase = path.Split('/');
  1215. string searchquery = "/";
  1216. if (pathbase.Length < 1)
  1217. return false;
  1218. for (int i=1; i<pathbase.Length; i++)
  1219. {
  1220. searchquery += pathbase[i];
  1221. if (pathbase.Length-1 != i)
  1222. searchquery += "/";
  1223. }
  1224. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1225. //
  1226. // [] = optional
  1227. // /resource/UUID/action[/action]
  1228. //
  1229. // now try to get the closest match to the reigstered path
  1230. // at least for OGP, registered path would probably only consist of the /resource/
  1231. string bestMatch = null;
  1232. lock (m_llsdHandlers)
  1233. {
  1234. foreach (string pattern in m_llsdHandlers.Keys)
  1235. {
  1236. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1237. {
  1238. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1239. {
  1240. // You have to specifically register for '/' and to get it, you must specificaly request it
  1241. //
  1242. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1243. bestMatch = pattern;
  1244. }
  1245. }
  1246. }
  1247. if (String.IsNullOrEmpty(bestMatch))
  1248. {
  1249. llsdHandler = null;
  1250. return false;
  1251. }
  1252. else
  1253. {
  1254. llsdHandler = m_llsdHandlers[bestMatch];
  1255. return true;
  1256. }
  1257. }
  1258. }
  1259. private OSDMap GenerateNoLLSDHandlerResponse()
  1260. {
  1261. OSDMap map = new OSDMap();
  1262. map["reason"] = OSD.FromString("LLSDRequest");
  1263. map["message"] = OSD.FromString("No handler registered for LLSD Requests");
  1264. map["login"] = OSD.FromString("false");
  1265. return map;
  1266. }
  1267. public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
  1268. {
  1269. // m_log.DebugFormat(
  1270. // "[BASE HTTP SERVER]: HandleHTTPRequest for request to {0}, method {1}",
  1271. // request.RawUrl, request.HttpMethod);
  1272. switch (request.HttpMethod)
  1273. {
  1274. case "OPTIONS":
  1275. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1276. return null;
  1277. default:
  1278. return HandleContentVerbs(request, response);
  1279. }
  1280. }
  1281. private byte[] HandleContentVerbs(OSHttpRequest request, OSHttpResponse response)
  1282. {
  1283. // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl);
  1284. // This is a test. There's a workable alternative.. as this way sucks.
  1285. // We'd like to put this into a text file parhaps that's easily editable.
  1286. //
  1287. // For this test to work, I used the following secondlife.exe parameters
  1288. // "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
  1289. //
  1290. // Even after all that, there's still an error, but it's a start.
  1291. //
  1292. // I depend on show_login_form being in the secondlife.exe parameters to figure out
  1293. // to display the form, or process it.
  1294. // a better way would be nifty.
  1295. byte[] buffer;
  1296. Stream requestStream = request.InputStream;
  1297. Encoding encoding = Encoding.UTF8;
  1298. StreamReader reader = new StreamReader(requestStream, encoding);
  1299. string requestBody = reader.ReadToEnd();
  1300. // avoid warning for now
  1301. reader.ReadToEnd();
  1302. reader.Close();
  1303. requestStream.Close();
  1304. Hashtable keysvals = new Hashtable();
  1305. Hashtable headervals = new Hashtable();
  1306. Hashtable requestVars = new Hashtable();
  1307. string host = String.Empty;
  1308. string[] querystringkeys = request.QueryString.AllKeys;
  1309. string[] rHeaders = request.Headers.AllKeys;
  1310. keysvals.Add("body", requestBody);
  1311. keysvals.Add("uri", request.RawUrl);
  1312. keysvals.Add("content-type", request.ContentType);
  1313. keysvals.Add("http-method", request.HttpMethod);
  1314. foreach (string queryname in querystringkeys)
  1315. {
  1316. // m_log.DebugFormat(
  1317. // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
  1318. keysvals.Add(queryname, request.QueryString[queryname]);
  1319. requestVars.Add(queryname, keysvals[queryname]);
  1320. }
  1321. foreach (string headername in rHeaders)
  1322. {
  1323. // m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
  1324. headervals[headername] = request.Headers[headername];
  1325. }
  1326. if (headervals.Contains("Host"))
  1327. {
  1328. host = (string)headervals["Host"];
  1329. }
  1330. keysvals.Add("headers", headervals);
  1331. keysvals.Add("querystringkeys", querystringkeys);
  1332. keysvals.Add("requestvars", requestVars);
  1333. // keysvals.Add("form", request.Form);
  1334. if (keysvals.Contains("method"))
  1335. {
  1336. // m_log.Debug("[BASE HTTP SERVER]: Contains Method");
  1337. string method = (string) keysvals["method"];
  1338. // m_log.Debug("[BASE HTTP SERVER]: " + requestBody);
  1339. GenericHTTPMethod requestprocessor;
  1340. bool foundHandler = TryGetHTTPHandler(method, out requestprocessor);
  1341. if (foundHandler)
  1342. {
  1343. Hashtable responsedata1 = requestprocessor(keysvals);
  1344. buffer = DoHTTPGruntWork(responsedata1,response);
  1345. //SendHTML500(response);
  1346. }
  1347. else
  1348. {
  1349. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found");
  1350. buffer = SendHTML404(response, host);
  1351. }
  1352. }
  1353. else
  1354. {
  1355. GenericHTTPMethod requestprocessor;
  1356. bool foundHandler = TryGetHTTPHandlerPathBased(request.RawUrl, out requestprocessor);
  1357. if (foundHandler)
  1358. {
  1359. Hashtable responsedata2 = requestprocessor(keysvals);
  1360. buffer = DoHTTPGruntWork(responsedata2, response);
  1361. //SendHTML500(response);
  1362. }
  1363. else
  1364. {
  1365. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found2");
  1366. buffer = SendHTML404(response, host);
  1367. }
  1368. }
  1369. return buffer;
  1370. }
  1371. private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
  1372. {
  1373. httpHandler = null;
  1374. // Pull out the first part of the path
  1375. // splitting the path by '/' means we'll get the following return..
  1376. // {0}/{1}/{2}
  1377. // where {0} isn't something we really control 100%
  1378. string[] pathbase = path.Split('/');
  1379. string searchquery = "/";
  1380. if (pathbase.Length < 1)
  1381. return false;
  1382. for (int i = 1; i < pathbase.Length; i++)
  1383. {
  1384. searchquery += pathbase[i];
  1385. if (pathbase.Length - 1 != i)
  1386. searchquery += "/";
  1387. }
  1388. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1389. //
  1390. // [] = optional
  1391. // /resource/UUID/action[/action]
  1392. //
  1393. // now try to get the closest match to the reigstered path
  1394. // at least for OGP, registered path would probably only consist of the /resource/
  1395. string bestMatch = null;
  1396. // m_log.DebugFormat(
  1397. // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
  1398. lock (m_HTTPHandlers)
  1399. {
  1400. foreach (string pattern in m_HTTPHandlers.Keys)
  1401. {
  1402. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1403. {
  1404. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1405. {
  1406. // You have to specifically register for '/' and to get it, you must specifically request it
  1407. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1408. bestMatch = pattern;
  1409. }
  1410. }
  1411. }
  1412. if (String.IsNullOrEmpty(bestMatch))
  1413. {
  1414. httpHandler = null;
  1415. return false;
  1416. }
  1417. else
  1418. {
  1419. if (bestMatch == "/" && searchquery != "/")
  1420. return false;
  1421. httpHandler = m_HTTPHandlers[bestMatch];
  1422. return true;
  1423. }
  1424. }
  1425. }
  1426. internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
  1427. {
  1428. //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
  1429. int responsecode = (int)responsedata["int_response_code"];
  1430. string responseString = (string)responsedata["str_response_string"];
  1431. string contentType = (string)responsedata["content_type"];
  1432. if (responsedata.ContainsKey("error_status_text"))
  1433. {
  1434. response.StatusDescription = (string)responsedata["error_status_text"];
  1435. }
  1436. if (responsedata.ContainsKey("http_protocol_version"))
  1437. {
  1438. response.ProtocolVersion = (string)responsedata["http_protocol_version"];
  1439. }
  1440. if (responsedata.ContainsKey("keepalive"))
  1441. {
  1442. bool keepalive = (bool)responsedata["keepalive"];
  1443. response.KeepAlive = keepalive;
  1444. }
  1445. if (responsedata.ContainsKey("reusecontext"))
  1446. response.ReuseContext = (bool) responsedata["reusecontext"];
  1447. // Cross-Origin Resource Sharing with simple requests
  1448. if (responsedata.ContainsKey("access_control_allow_origin"))
  1449. response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
  1450. //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
  1451. //and should check for NullReferenceExceptions
  1452. if (string.IsNullOrEmpty(contentType))
  1453. {
  1454. contentType = "text/html";
  1455. }
  1456. // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
  1457. response.StatusCode = responsecode;
  1458. if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently)
  1459. {
  1460. response.RedirectLocation = (string)responsedata["str_redirect_location"];
  1461. response.StatusCode = responsecode;
  1462. }
  1463. response.AddHeader("Content-Type", contentType);
  1464. byte[] buffer;
  1465. if (!(contentType.Contains("image")
  1466. || contentType.Contains("x-shockwave-flash")
  1467. || contentType.Contains("application/x-oar")
  1468. || contentType.Contains("application/vnd.ll.mesh")))
  1469. {
  1470. // Text
  1471. buffer = Encoding.UTF8.GetBytes(responseString);
  1472. }
  1473. else
  1474. {
  1475. // Binary!
  1476. buffer = Convert.FromBase64String(responseString);
  1477. }
  1478. response.SendChunked = false;
  1479. response.ContentLength64 = buffer.Length;
  1480. response.ContentEncoding = Encoding.UTF8;
  1481. return buffer;
  1482. }
  1483. public byte[] SendHTML404(OSHttpResponse response, string host)
  1484. {
  1485. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1486. response.StatusCode = 404;
  1487. response.AddHeader("Content-type", "text/html");
  1488. string responseString = GetHTTP404(host);
  1489. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1490. response.SendChunked = false;
  1491. response.ContentLength64 = buffer.Length;
  1492. response.ContentEncoding = Encoding.UTF8;
  1493. return buffer;
  1494. }
  1495. public byte[] SendHTML500(OSHttpResponse response)
  1496. {
  1497. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1498. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1499. response.AddHeader("Content-type", "text/html");
  1500. string responseString = GetHTTP500();
  1501. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1502. response.SendChunked = false;
  1503. response.ContentLength64 = buffer.Length;
  1504. response.ContentEncoding = Encoding.UTF8;
  1505. return buffer;
  1506. }
  1507. public void Start()
  1508. {
  1509. StartHTTP();
  1510. }
  1511. private void StartHTTP()
  1512. {
  1513. m_log.InfoFormat(
  1514. "[BASE HTTP SERVER]: Starting {0} server on port {1}", UseSSL ? "HTTPS" : "HTTP", Port);
  1515. try
  1516. {
  1517. //m_httpListener = new HttpListener();
  1518. NotSocketErrors = 0;
  1519. if (!m_ssl)
  1520. {
  1521. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1522. //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/");
  1523. m_httpListener2 = CoolHTTPListener.Create(m_listenIPAddress, (int)m_port);
  1524. m_httpListener2.ExceptionThrown += httpServerException;
  1525. m_httpListener2.LogWriter = httpserverlog;
  1526. // Uncomment this line in addition to those in HttpServerLogWriter
  1527. // if you want more detailed trace information from the HttpServer
  1528. //m_httpListener2.UseTraceLogs = true;
  1529. //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
  1530. }
  1531. else
  1532. {
  1533. //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
  1534. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1535. m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert);
  1536. m_httpListener2.ExceptionThrown += httpServerException;
  1537. m_httpListener2.LogWriter = httpserverlog;
  1538. }
  1539. m_httpListener2.RequestReceived += OnRequest;
  1540. //m_httpListener.Start();
  1541. m_httpListener2.Start(64);
  1542. // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events
  1543. m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000);
  1544. m_PollServiceManager.Start();
  1545. HTTPDRunning = true;
  1546. //HttpListenerContext context;
  1547. //while (true)
  1548. //{
  1549. // context = m_httpListener.GetContext();
  1550. // ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(HandleRequest), context);
  1551. // }
  1552. }
  1553. catch (Exception e)
  1554. {
  1555. m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
  1556. m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?");
  1557. // We want this exception to halt the entire server since in current configurations we aren't too
  1558. // useful without inbound HTTP.
  1559. throw e;
  1560. }
  1561. m_requestsProcessedStat
  1562. = new Stat(
  1563. "HTTPRequestsServed",
  1564. "Number of inbound HTTP requests processed",
  1565. "",
  1566. "requests",
  1567. "httpserver",
  1568. Port.ToString(),
  1569. StatType.Pull,
  1570. MeasuresOfInterest.AverageChangeOverTime,
  1571. stat => stat.Value = RequestNumber,
  1572. StatVerbosity.Debug);
  1573. StatsManager.RegisterStat(m_requestsProcessedStat);
  1574. }
  1575. public void httpServerDisconnectMonitor(IHttpClientContext source, SocketError err)
  1576. {
  1577. switch (err)
  1578. {
  1579. case SocketError.NotSocket:
  1580. NotSocketErrors++;
  1581. break;
  1582. }
  1583. }
  1584. public void httpServerException(object source, Exception exception)
  1585. {
  1586. m_log.Error(String.Format("[BASE HTTP SERVER]: {0} had an exception: {1} ", source.ToString(), exception.Message), exception);
  1587. /*
  1588. if (HTTPDRunning)// && NotSocketErrors > 5)
  1589. {
  1590. Stop();
  1591. Thread.Sleep(200);
  1592. StartHTTP();
  1593. m_log.Warn("[HTTPSERVER]: Died. Trying to kick.....");
  1594. }
  1595. */
  1596. }
  1597. public void Stop()
  1598. {
  1599. HTTPDRunning = false;
  1600. StatsManager.DeregisterStat(m_requestsProcessedStat);
  1601. try
  1602. {
  1603. m_PollServiceManager.Stop();
  1604. m_httpListener2.ExceptionThrown -= httpServerException;
  1605. //m_httpListener2.DisconnectHandler = null;
  1606. m_httpListener2.LogWriter = null;
  1607. m_httpListener2.RequestReceived -= OnRequest;
  1608. m_httpListener2.Stop();
  1609. }
  1610. catch (NullReferenceException)
  1611. {
  1612. m_log.Warn("[BASE HTTP SERVER]: Null Reference when stopping HttpServer.");
  1613. }
  1614. }
  1615. public void RemoveStreamHandler(string httpMethod, string path)
  1616. {
  1617. string handlerKey = GetHandlerKey(httpMethod, path);
  1618. //m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey);
  1619. lock (m_streamHandlers)
  1620. m_streamHandlers.Remove(handlerKey);
  1621. }
  1622. public void RemoveHTTPHandler(string httpMethod, string path)
  1623. {
  1624. lock (m_HTTPHandlers)
  1625. {
  1626. if (httpMethod != null && httpMethod.Length == 0)
  1627. {
  1628. m_HTTPHandlers.Remove(path);
  1629. return;
  1630. }
  1631. m_HTTPHandlers.Remove(GetHandlerKey(httpMethod, path));
  1632. }
  1633. }
  1634. public void RemovePollServiceHTTPHandler(string httpMethod, string path)
  1635. {
  1636. lock (m_pollHandlers)
  1637. m_pollHandlers.Remove(path);
  1638. }
  1639. // public bool RemoveAgentHandler(string agent, IHttpAgentHandler handler)
  1640. // {
  1641. // lock (m_agentHandlers)
  1642. // {
  1643. // IHttpAgentHandler foundHandler;
  1644. //
  1645. // if (m_agentHandlers.TryGetValue(agent, out foundHandler) && foundHandler == handler)
  1646. // {
  1647. // m_agentHandlers.Remove(agent);
  1648. // return true;
  1649. // }
  1650. // }
  1651. //
  1652. // return false;
  1653. // }
  1654. public void RemoveXmlRPCHandler(string method)
  1655. {
  1656. lock (m_rpcHandlers)
  1657. m_rpcHandlers.Remove(method);
  1658. }
  1659. public void RemoveJsonRPCHandler(string method)
  1660. {
  1661. lock(jsonRpcHandlers)
  1662. jsonRpcHandlers.Remove(method);
  1663. }
  1664. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  1665. {
  1666. lock (m_llsdHandlers)
  1667. {
  1668. LLSDMethod foundHandler;
  1669. if (m_llsdHandlers.TryGetValue(path, out foundHandler) && foundHandler == handler)
  1670. {
  1671. m_llsdHandlers.Remove(path);
  1672. return true;
  1673. }
  1674. }
  1675. return false;
  1676. }
  1677. public string GetHTTP404(string host)
  1678. {
  1679. string file = Path.Combine(".", "http_404.html");
  1680. if (!File.Exists(file))
  1681. return getDefaultHTTP404(host);
  1682. StreamReader sr = File.OpenText(file);
  1683. string result = sr.ReadToEnd();
  1684. sr.Close();
  1685. return result;
  1686. }
  1687. public string GetHTTP500()
  1688. {
  1689. string file = Path.Combine(".", "http_500.html");
  1690. if (!File.Exists(file))
  1691. return getDefaultHTTP500();
  1692. StreamReader sr = File.OpenText(file);
  1693. string result = sr.ReadToEnd();
  1694. sr.Close();
  1695. return result;
  1696. }
  1697. // Fallback HTTP responses in case the HTTP error response files don't exist
  1698. private static string getDefaultHTTP404(string host)
  1699. {
  1700. 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>";
  1701. }
  1702. private static string getDefaultHTTP500()
  1703. {
  1704. 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>";
  1705. }
  1706. }
  1707. public class HttpServerContextObj
  1708. {
  1709. public IHttpClientContext context = null;
  1710. public IHttpRequest req = null;
  1711. public OSHttpRequest oreq = null;
  1712. public OSHttpResponse oresp = null;
  1713. public HttpServerContextObj(IHttpClientContext contxt, IHttpRequest reqs)
  1714. {
  1715. context = contxt;
  1716. req = reqs;
  1717. }
  1718. public HttpServerContextObj(OSHttpRequest osreq, OSHttpResponse osresp)
  1719. {
  1720. oreq = osreq;
  1721. oresp = osresp;
  1722. }
  1723. }
  1724. /// <summary>
  1725. /// Relays HttpServer log messages to our own logging mechanism.
  1726. /// </summary>
  1727. /// To use this you must uncomment the switch section
  1728. ///
  1729. /// You may also be able to get additional trace information from HttpServer if you uncomment the UseTraceLogs
  1730. /// property in StartHttp() for the HttpListener
  1731. public class HttpServerLogWriter : ILogWriter
  1732. {
  1733. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1734. public void Write(object source, LogPrio priority, string message)
  1735. {
  1736. /*
  1737. switch (priority)
  1738. {
  1739. case LogPrio.Trace:
  1740. m_log.DebugFormat("[{0}]: {1}", source, message);
  1741. break;
  1742. case LogPrio.Debug:
  1743. m_log.DebugFormat("[{0}]: {1}", source, message);
  1744. break;
  1745. case LogPrio.Error:
  1746. m_log.ErrorFormat("[{0}]: {1}", source, message);
  1747. break;
  1748. case LogPrio.Info:
  1749. m_log.InfoFormat("[{0}]: {1}", source, message);
  1750. break;
  1751. case LogPrio.Warning:
  1752. m_log.WarnFormat("[{0}]: {1}", source, message);
  1753. break;
  1754. case LogPrio.Fatal:
  1755. m_log.ErrorFormat("[{0}]: FATAL! - {1}", source, message);
  1756. break;
  1757. default:
  1758. break;
  1759. }
  1760. */
  1761. return;
  1762. }
  1763. }
  1764. }