BaseHttpServer.cs 89 KB

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