BaseHttpServer.cs 78 KB

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