BaseHttpServer.cs 83 KB

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