1
0

BaseHttpServer.cs 88 KB

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