BaseHttpServer.cs 81 KB

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