1
0

BaseHttpServer.cs 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348
  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. if (WebUtil.DebugLevel >= 6)
  714. {
  715. // Always truncate binary blobs. We don't have a ContentType, so detect them using the request name.
  716. if (requestHandler is not null && requestHandler.Name.Equals("GetMesh"))
  717. {
  718. if (output.Length > WebUtil.MaxRequestDiagLength)
  719. output = string.Concat(output.AsSpan(0, WebUtil.MaxRequestDiagLength), "...");
  720. }
  721. }
  722. WebUtil.LogResponseDetail(RequestNumber, output);
  723. }
  724. if (!response.SendChunked && response.ContentLength64 <= 0)
  725. response.ContentLength64 = buffer.LongLength;
  726. //response.OutputStream.Write(buffer, 0, buffer.Length);
  727. response.RawBufferStart = 0;
  728. response.RawBufferLen = buffer.Length;
  729. response.RawBuffer = buffer;
  730. }
  731. // Do not include the time taken to actually send the response to the caller in the measurement
  732. // time. This is to avoid logging when it's the client that is slow to process rather than the
  733. // server
  734. requestEndTick = Environment.TickCount;
  735. buffer = null;
  736. responseData = response.RawBuffer;
  737. response.Send();
  738. }
  739. catch (SocketException e)
  740. {
  741. // At least on linux, it appears that if the client makes a request without requiring the response,
  742. // an unconnected socket exception is thrown when we close the response output stream. There's no
  743. // obvious way to tell if the client didn't require the response, so instead we'll catch and ignore
  744. // the exception instead.
  745. //
  746. // An alternative may be to turn off all response write exceptions on the HttpListener, but let's go
  747. // with the minimum first
  748. m_log.Warn($"[BASE HTTP SERVER]: HandleRequest threw {e.Message}.\nNOTE: this may be spurious on Linux");
  749. }
  750. catch (IOException e)
  751. {
  752. m_log.Error("[BASE HTTP SERVER]: HandleRequest() threw exception ", e);
  753. }
  754. catch (Exception e)
  755. {
  756. m_log.Error("[BASE HTTP SERVER]: HandleRequest() threw exception ", e);
  757. try
  758. {
  759. response.StatusCode =(int)HttpStatusCode.InternalServerError;
  760. responseData = response.RawBuffer;
  761. response.Send();
  762. }
  763. catch {}
  764. }
  765. finally
  766. {
  767. if(request.InputStream is not null && request.InputStream.CanRead)
  768. request.InputStream.Close();
  769. int tickdiff = requestEndTick - requestStartTick;
  770. if (tickdiff > 3000)
  771. {
  772. m_log.InfoFormat(
  773. "[LOGHTTP] Slow handling of {0} {1} {2} {3} {4} from {5} took {6}ms",
  774. RequestNumber,
  775. request.HttpMethod,
  776. request.RawUrl,
  777. requestHandler is null ? "" : requestHandler.Name,
  778. requestHandler is null ? "" : requestHandler.Description,
  779. request.RemoteIPEndPoint,
  780. tickdiff);
  781. }
  782. else if (DebugLevel >= 4)
  783. {
  784. m_log.DebugFormat(
  785. "[LOGHTTP] HTTP IN {0} :{1} took {2}ms",
  786. RequestNumber,
  787. Port,
  788. tickdiff);
  789. }
  790. if ((DebugLevel >= 5) && (responseData != null))
  791. {
  792. string output = Encoding.UTF8.GetString(responseData);
  793. if (DebugLevel == 5)
  794. {
  795. if (output.Length > WebUtil.MaxRequestDiagLength)
  796. output = string.Concat(output.AsSpan(0, WebUtil.MaxRequestDiagLength), "...");
  797. }
  798. m_log.DebugFormat("[LOGHTTP] RESPONSE {0}: {1}", RequestNumber, output);
  799. }
  800. }
  801. }
  802. private void LogIncomingToStreamHandler(OSHttpRequest request, IRequestHandler requestHandler)
  803. {
  804. m_log.DebugFormat(
  805. "[LOGHTTP] HTTP IN {0} :{1} stream handler {2} {3} {4} {5} from {6}",
  806. RequestNumber,
  807. Port,
  808. request.HttpMethod,
  809. request.Url.PathAndQuery,
  810. requestHandler.Name,
  811. requestHandler.Description,
  812. request.RemoteIPEndPoint);
  813. if (DebugLevel >= 5)
  814. LogIncomingInDetail(request);
  815. }
  816. private void LogIncomingToStreamHandler(OSHttpRequest request, ISimpleStreamHandler requestHandler)
  817. {
  818. m_log.DebugFormat(
  819. "[LOGHTTP] HTTP IN {0} :{1} stream handler {2} {3} {4} from {5}",
  820. RequestNumber,
  821. Port,
  822. request.HttpMethod,
  823. request.Url.PathAndQuery,
  824. requestHandler.Name,
  825. request.RemoteIPEndPoint);
  826. if (DebugLevel >= 5)
  827. LogIncomingInDetail(request);
  828. }
  829. private void LogIncomingToContentTypeHandler(OSHttpRequest request)
  830. {
  831. m_log.DebugFormat(
  832. "[LOGHTTP] HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}",
  833. RequestNumber,
  834. Port,
  835. string.IsNullOrEmpty(request.ContentType) ? "not set" : request.ContentType,
  836. request.HttpMethod,
  837. request.Url.PathAndQuery,
  838. request.RemoteIPEndPoint);
  839. if (DebugLevel >= 5)
  840. LogIncomingInDetail(request);
  841. }
  842. private void LogIncomingToXmlRpcHandler(OSHttpRequest request)
  843. {
  844. m_log.DebugFormat(
  845. "[LOGHTTP] HTTP IN {0} :{1} assumed generic XMLRPC request {2} {3} from {4}",
  846. RequestNumber,
  847. Port,
  848. request.HttpMethod,
  849. request.Url.PathAndQuery,
  850. request.RemoteIPEndPoint);
  851. if (DebugLevel >= 5)
  852. LogIncomingInDetail(request);
  853. }
  854. private void LogIncomingInDetail(OSHttpRequest request)
  855. {
  856. if (request.ContentType == "application/octet-stream")
  857. return; // never log these; they're just binary data
  858. Stream inputStream = Util.Copy(request.InputStream);
  859. Stream innerStream = null;
  860. try
  861. {
  862. if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
  863. {
  864. innerStream = inputStream;
  865. inputStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress);
  866. }
  867. using (StreamReader reader = new StreamReader(inputStream, Encoding.UTF8))
  868. {
  869. string output;
  870. if (DebugLevel == 5)
  871. {
  872. char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed
  873. int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1);
  874. output = new string(chars, 0, Math.Min(len, WebUtil.MaxRequestDiagLength));
  875. if (len > WebUtil.MaxRequestDiagLength)
  876. output += "...";
  877. }
  878. else
  879. {
  880. output = reader.ReadToEnd();
  881. }
  882. m_log.DebugFormat("[LOGHTTP] {0}", Util.BinaryToASCII(output));
  883. }
  884. }
  885. finally
  886. {
  887. if (innerStream != null)
  888. innerStream.Dispose();
  889. inputStream.Dispose();
  890. }
  891. }
  892. private bool TryGetStreamHandler(string handlerKey, out IRequestHandler streamHandler)
  893. {
  894. if(m_streamHandlers.TryGetValue(handlerKey, out streamHandler))
  895. return true;
  896. string bestMatch = null;
  897. bool hasbest=false;
  898. lock (m_streamHandlers)
  899. {
  900. foreach (string pattern in m_streamHandlers.Keys)
  901. {
  902. if (handlerKey.StartsWith(pattern))
  903. {
  904. if (!hasbest || pattern.Length > bestMatch.Length)
  905. {
  906. bestMatch = pattern;
  907. hasbest = true;
  908. }
  909. }
  910. }
  911. }
  912. if (hasbest)
  913. {
  914. streamHandler = m_streamHandlers[bestMatch];
  915. return true;
  916. }
  917. streamHandler = null;
  918. return false;
  919. }
  920. private bool TryGetPollServiceHTTPHandler(string handlerKey, out PollServiceEventArgs oServiceEventArgs)
  921. {
  922. if(m_pollHandlers.TryGetValue(handlerKey, out oServiceEventArgs))
  923. return true;
  924. if(!m_pollHandlersVarPath.IsEmpty && handlerKey.Length >= 45)
  925. {
  926. // tuned for lsl requests, the only ones that should reach this, so be strict (/lslhttp/uuid.ToString())
  927. int indx = handlerKey.IndexOf('/', 44);
  928. if (indx < 44) //lsl requests
  929. {
  930. if(m_pollHandlersVarPath.TryGetValue(handlerKey, out oServiceEventArgs))
  931. return true;
  932. }
  933. else if(m_pollHandlersVarPath.TryGetValue(handlerKey[..indx], out oServiceEventArgs))
  934. return true;
  935. }
  936. oServiceEventArgs = null;
  937. return false;
  938. }
  939. private bool TryGetHTTPHandler(string handlerKey, out GenericHTTPMethod HTTPHandler)
  940. {
  941. // m_log.DebugFormat("[BASE HTTP HANDLER]: Looking for HTTP handler for {0}", handlerKey);
  942. if(m_HTTPHandlers.TryGetValue(handlerKey, out HTTPHandler))
  943. return true;
  944. string bestMatch = null;
  945. bool hasmatch = false;
  946. lock (m_HTTPHandlers)
  947. {
  948. foreach (string pattern in m_HTTPHandlers.Keys)
  949. {
  950. if (handlerKey.StartsWith(pattern))
  951. {
  952. if (!hasmatch || pattern.Length > bestMatch.Length)
  953. {
  954. bestMatch = pattern;
  955. hasmatch = true;
  956. }
  957. }
  958. }
  959. }
  960. if (hasmatch)
  961. {
  962. HTTPHandler = m_HTTPHandlers[bestMatch];
  963. return true;
  964. }
  965. HTTPHandler = null;
  966. return false;
  967. }
  968. private bool TryGetSimpleStreamHandler(string uripath, out ISimpleStreamHandler handler)
  969. {
  970. if(m_simpleStreamHandlers.TryGetValue(uripath, out handler))
  971. return true;
  972. // look only for keyword before second slash ( /keyword/someparameter/... )
  973. handler = null;
  974. if(uripath.Length < 3)
  975. return false;
  976. int indx = uripath.IndexOf('/', 2);
  977. if(indx < 0 || indx == uripath.Length - 1)
  978. return false;
  979. return m_simpleStreamVarPath.TryGetValue(uripath[..indx], out handler);
  980. }
  981. /// <summary>
  982. /// Try all the registered xmlrpc handlers when an xmlrpc request is received.
  983. /// Sends back an XMLRPC unknown request response if no handler is registered for the requested method.
  984. /// </summary>
  985. /// <param name="request"></param>
  986. /// <param name="response"></param>
  987. public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
  988. {
  989. Stream requestStream = request.InputStream;
  990. response.StatusCode = (int)HttpStatusCode.NotFound;
  991. response.KeepAlive = false;
  992. try
  993. {
  994. if (!requestStream.CanRead)
  995. return;
  996. if (requestStream.Length == 0)
  997. {
  998. requestStream.Dispose();
  999. return;
  1000. }
  1001. }
  1002. catch
  1003. {
  1004. return;
  1005. }
  1006. Stream innerStream = null;
  1007. try
  1008. {
  1009. if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
  1010. {
  1011. innerStream = requestStream;
  1012. requestStream = new GZipStream(innerStream, CompressionMode.Decompress);
  1013. }
  1014. }
  1015. catch
  1016. {
  1017. if (requestStream.CanRead)
  1018. requestStream.Dispose();
  1019. if (innerStream is not null && innerStream.CanRead)
  1020. innerStream.Dispose();
  1021. response.StatusCode = (int)HttpStatusCode.BadRequest;
  1022. return;
  1023. }
  1024. XmlRpcRequest xmlRprcRequest = null;
  1025. try
  1026. {
  1027. using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8))
  1028. {
  1029. var xmlDes = new XmlRpcRequestDeserializer();
  1030. xmlRprcRequest = (XmlRpcRequest)xmlDes.Deserialize(reader);
  1031. }
  1032. }
  1033. catch (Exception e)
  1034. {
  1035. m_log.WarnFormat(
  1036. "[BASE HTTP SERVER]: Fail to decode XMLRPC request {0}: {1}",
  1037. request.RemoteIPEndPoint, e.Message);
  1038. }
  1039. finally
  1040. {
  1041. if (requestStream.CanRead)
  1042. requestStream.Dispose();
  1043. if (innerStream is not null && innerStream.CanRead)
  1044. innerStream.Dispose();
  1045. }
  1046. if (xmlRprcRequest is null)
  1047. return;
  1048. string methodName = xmlRprcRequest.MethodName;
  1049. if (string.IsNullOrWhiteSpace(methodName))
  1050. return;
  1051. XmlRpcMethod method;
  1052. bool methodWasFound;
  1053. bool keepAlive = false;
  1054. lock (m_rpcHandlers)
  1055. {
  1056. methodWasFound = m_rpcHandlers.TryGetValue(methodName, out method);
  1057. if (methodWasFound)
  1058. keepAlive = m_rpcHandlersKeepAlive[methodName];
  1059. }
  1060. XmlRpcResponse xmlRpcResponse;
  1061. if (methodWasFound)
  1062. {
  1063. xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
  1064. xmlRprcRequest.Params.Add(request.Url); // Param[2]
  1065. string xff = "X-Forwarded-For";
  1066. string xfflower = xff.ToLower();
  1067. foreach (string s in request.Headers.AllKeys)
  1068. {
  1069. if (s is not null && s.Equals(xfflower))
  1070. {
  1071. xff = xfflower;
  1072. break;
  1073. }
  1074. }
  1075. xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3]
  1076. // reserve this for
  1077. // ... by Fumi.Iseki for DTLNSLMoneyServer
  1078. // BUT make its presence possible to detect/parse
  1079. string rcn = request.IHttpClientContext.SSLCommonName;
  1080. if(!string.IsNullOrWhiteSpace(rcn))
  1081. {
  1082. rcn = "SSLCN:" + rcn;
  1083. xmlRprcRequest.Params.Add(rcn); // Param[4] or Param[5]
  1084. }
  1085. try
  1086. {
  1087. xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
  1088. }
  1089. catch(Exception e)
  1090. {
  1091. string errorMessage = $"Requested method [{methodName}] from {request.RemoteIPEndPoint.Address} threw exception: {e.Message}";
  1092. m_log.Error($"[BASE HTTP SERVER]: {errorMessage}");
  1093. // if the registered XmlRpc method threw an exception, we pass a fault-code along
  1094. xmlRpcResponse = new XmlRpcResponse();
  1095. // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1096. xmlRpcResponse.SetFault(-32603, errorMessage);
  1097. }
  1098. response.AddHeader("Access-Control-Allow-Origin", "*");
  1099. }
  1100. else
  1101. {
  1102. xmlRpcResponse = new XmlRpcResponse();
  1103. // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1104. xmlRpcResponse.SetFault(
  1105. XmlRpcErrorCodes.SERVER_ERROR_METHOD,
  1106. String.Format("Requested method [{0}] not found", methodName));
  1107. }
  1108. using (MemoryStream outs = new MemoryStream(64 * 1024))
  1109. {
  1110. using (XmlTextWriter writer = new XmlTextWriter(outs, UTF8NoBOM))
  1111. {
  1112. writer.Formatting = Formatting.None;
  1113. var xmlrpcSer = new XmlRpcResponseSerializer();
  1114. xmlrpcSer.Serialize(writer, xmlRpcResponse);
  1115. writer.Flush();
  1116. response.RawBuffer = outs.GetBuffer();
  1117. response.RawBufferLen = (int)outs.Length;
  1118. }
  1119. }
  1120. response.StatusCode = (int)HttpStatusCode.OK;
  1121. response.KeepAlive = keepAlive;
  1122. response.ContentType = "text/xml";
  1123. }
  1124. public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response, Dictionary<string, XmlRpcMethod> rpcHandlers)
  1125. {
  1126. Stream requestStream = request.InputStream;
  1127. Stream innerStream = null;
  1128. try
  1129. {
  1130. if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
  1131. {
  1132. innerStream = requestStream;
  1133. requestStream = new GZipStream(innerStream, CompressionMode.Decompress);
  1134. }
  1135. }
  1136. catch
  1137. {
  1138. if (requestStream.CanRead)
  1139. requestStream.Dispose();
  1140. if (innerStream is not null && innerStream.CanRead)
  1141. innerStream.Dispose();
  1142. response.StatusCode = (int)HttpStatusCode.BadRequest;
  1143. response.KeepAlive = false;
  1144. return;
  1145. }
  1146. XmlRpcRequest xmlRprcRequest = null;
  1147. try
  1148. {
  1149. using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8))
  1150. {
  1151. var xmlDes = new XmlRpcRequestDeserializer();
  1152. xmlRprcRequest = (XmlRpcRequest)xmlDes.Deserialize(reader);
  1153. }
  1154. }
  1155. catch (Exception e)
  1156. {
  1157. m_log.WarnFormat(
  1158. "[BASE HTTP SERVER]: Fail to decode XMLRPC request {0}: {1}",
  1159. request.RemoteIPEndPoint, e.Message);
  1160. }
  1161. finally
  1162. {
  1163. if (requestStream.CanRead)
  1164. requestStream.Dispose();
  1165. if (innerStream is not null && innerStream.CanRead)
  1166. innerStream.Dispose();
  1167. }
  1168. if (xmlRprcRequest is null)
  1169. {
  1170. response.StatusCode = (int)HttpStatusCode.NotFound;
  1171. response.KeepAlive = false;
  1172. return;
  1173. }
  1174. string methodName = xmlRprcRequest.MethodName;
  1175. if (string.IsNullOrWhiteSpace(methodName))
  1176. {
  1177. response.StatusCode = (int)HttpStatusCode.NotFound;
  1178. response.KeepAlive = false;
  1179. return;
  1180. }
  1181. bool methodWasFound;
  1182. methodWasFound = rpcHandlers.TryGetValue(methodName, out XmlRpcMethod method);
  1183. XmlRpcResponse xmlRpcResponse;
  1184. if (methodWasFound)
  1185. {
  1186. xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
  1187. xmlRprcRequest.Params.Add(request.Url); // Param[2]
  1188. foreach (string s in request.Headers.AllKeys)
  1189. {
  1190. if (s is not null && s.Equals("x-forwarded-for", StringComparison.OrdinalIgnoreCase))
  1191. {
  1192. xmlRprcRequest.Params.Add(request.Headers.Get(s)); // Param[3]
  1193. break;
  1194. }
  1195. }
  1196. // reserve this for
  1197. // ... by Fumi.Iseki for DTLNSLMoneyServer
  1198. // BUT make its presence possible to detect/parse
  1199. if (!string.IsNullOrWhiteSpace(request.IHttpClientContext.SSLCommonName))
  1200. xmlRprcRequest.Params.Add("SSLCN:" + request.IHttpClientContext.SSLCommonName); // Param[4] or Param[5]
  1201. try
  1202. {
  1203. xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
  1204. }
  1205. catch (Exception e)
  1206. {
  1207. string errorMessage = string.Format(
  1208. "Requested method [{0}] from {1} threw exception: {2}",
  1209. methodName, request.RemoteIPEndPoint.Address, e.Message);
  1210. m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
  1211. // if the registered XmlRpc method threw an exception, we pass a fault-code along
  1212. xmlRpcResponse = new XmlRpcResponse();
  1213. // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1214. xmlRpcResponse.SetFault(-32603, errorMessage);
  1215. }
  1216. response.AddHeader("Access-Control-Allow-Origin", "*");
  1217. }
  1218. else
  1219. {
  1220. xmlRpcResponse = new XmlRpcResponse();
  1221. // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1222. xmlRpcResponse.SetFault(
  1223. XmlRpcErrorCodes.SERVER_ERROR_METHOD,
  1224. String.Format("Requested method [{0}] not found", methodName));
  1225. }
  1226. using (MemoryStream outs = new MemoryStream(64 * 1024))
  1227. {
  1228. using (XmlTextWriter writer = new XmlTextWriter(outs, UTF8NoBOM))
  1229. {
  1230. writer.Formatting = Formatting.None;
  1231. var xmlrpcSer = new XmlRpcResponseSerializer();
  1232. xmlrpcSer.Serialize(writer, xmlRpcResponse);
  1233. writer.Flush();
  1234. response.RawBuffer = outs.GetBuffer();
  1235. response.RawBufferLen = (int)outs.Length;
  1236. }
  1237. }
  1238. response.StatusCode = (int)HttpStatusCode.OK;
  1239. response.KeepAlive = false;
  1240. response.ContentType = "text/xml";
  1241. }
  1242. // JsonRpc (v2.0 only)
  1243. // Batch requests not yet supported
  1244. private void HandleJsonRpcRequests(OSHttpRequest request, OSHttpResponse response)
  1245. {
  1246. JsonRpcResponse jsonRpcResponse = new JsonRpcResponse();
  1247. OSDMap jsonRpcRequest = null;
  1248. try
  1249. {
  1250. jsonRpcRequest = (OSDMap)OSDParser.DeserializeJson(request.InputStream);
  1251. }
  1252. catch (LitJson.JsonException e)
  1253. {
  1254. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1255. jsonRpcResponse.Error.Message = e.Message;
  1256. }
  1257. if (request.InputStream is not null && request.InputStream.CanRead)
  1258. request.InputStream.Dispose();
  1259. if (jsonRpcRequest is not null)
  1260. {
  1261. // If we have no id, then it's a "notification"
  1262. if (jsonRpcRequest.TryGetValue("id", out OSD val))
  1263. jsonRpcResponse.Id = val.AsString();
  1264. if (jsonRpcRequest.TryGetValue("jsonrpc", out OSD ver) && ver.AsString() == "2.0")
  1265. {
  1266. jsonRpcResponse.JsonRpc = "2.0";
  1267. string methodname = jsonRpcRequest["method"];
  1268. if (!string.IsNullOrWhiteSpace(methodname) && jsonRpcHandlers.TryGetValue(methodname, out JsonRPCMethod method))
  1269. {
  1270. try
  1271. {
  1272. if(!method(jsonRpcRequest, ref jsonRpcResponse))
  1273. {
  1274. // The handler sent back an unspecified error
  1275. if(jsonRpcResponse.Error.Code == 0)
  1276. {
  1277. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1278. }
  1279. }
  1280. }
  1281. catch (Exception e)
  1282. {
  1283. string ErrorMessage = string.Format("[BASE HTTP SERVER]: Json-Rpc Handler Error method {0} - {1}", methodname, e.Message);
  1284. m_log.Error(ErrorMessage);
  1285. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1286. jsonRpcResponse.Error.Message = ErrorMessage;
  1287. }
  1288. }
  1289. else // Error no handler defined for requested method
  1290. {
  1291. jsonRpcResponse.Error.Code = ErrorCode.InvalidRequest;
  1292. jsonRpcResponse.Error.Message = string.Format ("No handler defined for {0}", methodname);
  1293. }
  1294. }
  1295. else // not json-rpc 2.0
  1296. {
  1297. jsonRpcResponse.Error.Code = ErrorCode.InvalidRequest;
  1298. jsonRpcResponse.Error.Message = "Must be valid json-rpc 2.0 see: http://www.jsonrpc.org/specification";
  1299. }
  1300. }
  1301. string responseData = jsonRpcResponse.Serialize();
  1302. response.RawBuffer = Util.UTF8NBGetbytes(responseData);
  1303. response.StatusCode = (int)HttpStatusCode.OK;
  1304. }
  1305. private void HandleLLSDLogin(OSHttpRequest request, OSHttpResponse response)
  1306. {
  1307. if (m_defaultLlsdHandler is null)
  1308. return;
  1309. response.StatusCode = (int)HttpStatusCode.BadRequest;
  1310. try
  1311. {
  1312. OSD llsdRequest = OSDParser.DeserializeLLSDXml(request.InputStream);
  1313. if (llsdRequest is not OSDMap)
  1314. return;
  1315. OSD llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
  1316. if (llsdResponse is not null)
  1317. {
  1318. response.ContentType = "application/llsd+xml";
  1319. response.RawBuffer = OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1320. response.StatusCode = (int)HttpStatusCode.OK;
  1321. return;
  1322. }
  1323. }
  1324. catch {}
  1325. response.StatusCode = (int)HttpStatusCode.BadRequest;
  1326. }
  1327. private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response)
  1328. {
  1329. //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
  1330. if (!TryGetLLSDHandler(request.RawUrl, out LLSDMethod llsdhandler))
  1331. {
  1332. response.StatusCode = (int)HttpStatusCode.NotFound;
  1333. response.KeepAlive = false;
  1334. return null;
  1335. }
  1336. //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
  1337. OSD llsdRequest = null;
  1338. try
  1339. {
  1340. llsdRequest = OSDParser.Deserialize(request.InputStream);
  1341. }
  1342. catch (Exception ex)
  1343. {
  1344. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1345. }
  1346. if (llsdRequest is null)
  1347. {
  1348. response.StatusCode = (int)HttpStatusCode.BadRequest;
  1349. return null;
  1350. }
  1351. OSD llsdResponse = null;
  1352. try
  1353. {
  1354. llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint.ToString());
  1355. }
  1356. catch
  1357. {
  1358. llsdResponse = null;
  1359. }
  1360. if (llsdResponse is null)
  1361. {
  1362. response.StatusCode = (int)HttpStatusCode.BadRequest;
  1363. return null;
  1364. }
  1365. byte[] buffer = Array.Empty<byte>();
  1366. if (llsdResponse.ToString().Equals("shutdown404!"))
  1367. {
  1368. response.ContentType = "text/plain";
  1369. response.StatusCode = (int)HttpStatusCode.NotFound;
  1370. }
  1371. else
  1372. {
  1373. // Select an appropriate response format
  1374. buffer = BuildLLSDResponse(request, response, llsdResponse);
  1375. }
  1376. response.StatusCode = (int)HttpStatusCode.OK;
  1377. response.ContentLength64 = buffer.Length;
  1378. response.ContentEncoding = Encoding.UTF8;
  1379. return buffer;
  1380. }
  1381. private static byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
  1382. {
  1383. if (request.AcceptTypes is not null && request.AcceptTypes.Length > 0)
  1384. {
  1385. foreach (string strAccept in request.AcceptTypes)
  1386. {
  1387. switch (strAccept)
  1388. {
  1389. case "application/llsd+xml":
  1390. case "application/xml":
  1391. case "text/xml":
  1392. response.ContentType = strAccept;
  1393. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1394. case "application/llsd+json":
  1395. case "application/json":
  1396. response.ContentType = strAccept;
  1397. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1398. }
  1399. }
  1400. }
  1401. if (!string.IsNullOrEmpty(request.ContentType))
  1402. {
  1403. switch (request.ContentType)
  1404. {
  1405. case "application/llsd+xml":
  1406. case "application/xml":
  1407. case "text/xml":
  1408. response.ContentType = request.ContentType;
  1409. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1410. case "application/llsd+json":
  1411. case "application/json":
  1412. response.ContentType = request.ContentType;
  1413. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1414. }
  1415. }
  1416. // response.ContentType = "application/llsd+json";
  1417. // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1418. response.ContentType = "application/llsd+xml";
  1419. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1420. }
  1421. private ReadOnlySpan<char> CleanSearchPath(ReadOnlySpan<char> path)
  1422. {
  1423. path = path.Trim().TrimEnd('/');
  1424. if (path[0] == '/')
  1425. return path;
  1426. return ("/" + path.ToString()).AsSpan();
  1427. }
  1428. /// <summary>
  1429. /// Checks if we have an Exact path in the LLSD handlers for the path provided
  1430. /// </summary>
  1431. /// <param name="path">URI of the request</param>
  1432. /// <returns>true if we have one, false if not</returns>
  1433. private bool DoWeHaveALLSDHandler(string path)
  1434. {
  1435. if(m_llsdHandlers.Count == 0)
  1436. {
  1437. return false;
  1438. }
  1439. var searchquery = CleanSearchPath(path.AsSpan());
  1440. lock (m_llsdHandlers)
  1441. {
  1442. foreach (string pattern in m_llsdHandlers.Keys)
  1443. {
  1444. if (searchquery.Length >= pattern.Length && searchquery.StartsWith(pattern))
  1445. return true;
  1446. }
  1447. }
  1448. return false;
  1449. }
  1450. /// <summary>
  1451. /// Checks if we have an Exact path in the HTTP handlers for the path provided
  1452. /// </summary>
  1453. /// <param name="path">URI of the request</param>
  1454. /// <returns>true if we have one, false if not</returns>
  1455. private bool DoWeHaveAHTTPHandler(string path)
  1456. {
  1457. var searchquery = CleanSearchPath(path.AsSpan());
  1458. //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
  1459. lock (m_HTTPHandlers)
  1460. {
  1461. foreach (string pattern in m_HTTPHandlers.Keys)
  1462. {
  1463. if (searchquery.Length >= pattern.Length && searchquery.StartsWith(pattern))
  1464. return true;
  1465. }
  1466. }
  1467. return false;
  1468. }
  1469. private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
  1470. {
  1471. if(m_llsdHandlers.Count == 0)
  1472. {
  1473. llsdHandler = null;
  1474. return false;
  1475. }
  1476. // Pull out the first part of the path
  1477. // splitting the path by '/' means we'll get the following return..
  1478. // {0}/{1}/{2}
  1479. // where {0} isn't something we really control 100%
  1480. var searchquery = CleanSearchPath(path.AsSpan());
  1481. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1482. //
  1483. // [] = optional
  1484. // /resource/UUID/action[/action]
  1485. //
  1486. // now try to get the closest match to the reigstered path
  1487. // at least for OGP, registered path would probably only consist of the /resource/
  1488. string bestMatch = null;
  1489. bool nomatch = true;
  1490. lock (m_llsdHandlers)
  1491. {
  1492. foreach (string pattern in m_llsdHandlers.Keys)
  1493. {
  1494. if (searchquery.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase))
  1495. {
  1496. if (nomatch || searchquery.Length > bestMatch.Length)
  1497. {
  1498. bestMatch = pattern;
  1499. nomatch = false;
  1500. }
  1501. }
  1502. }
  1503. if (nomatch)
  1504. {
  1505. llsdHandler = null;
  1506. return false;
  1507. }
  1508. if (bestMatch == "/" && searchquery != "/")
  1509. {
  1510. llsdHandler = null;
  1511. return false;
  1512. }
  1513. llsdHandler = m_llsdHandlers[bestMatch];
  1514. return true;
  1515. }
  1516. }
  1517. // legacy should go
  1518. public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
  1519. {
  1520. // m_log.DebugFormat(
  1521. // "[BASE HTTP SERVER]: HandleHTTPRequest for request to {0}, method {1}",
  1522. // request.RawUrl, request.HttpMethod);
  1523. if (!TryGetHTTPHandlerPathBased(request.RawUrl, out GenericHTTPMethod requestprocessor))
  1524. {
  1525. return SendHTML404(response);
  1526. }
  1527. // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl);
  1528. // This is a test. There's a workable alternative.. as this way sucks.
  1529. // We'd like to put this into a text file parhaps that's easily editable.
  1530. //
  1531. // For this test to work, I used the following secondlife.exe parameters
  1532. // "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
  1533. //
  1534. // Even after all that, there's still an error, but it's a start.
  1535. //
  1536. // I depend on show_login_form being in the secondlife.exe parameters to figure out
  1537. // to display the form, or process it.
  1538. // a better way would be nifty.
  1539. string requestBody;
  1540. using(StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8))
  1541. requestBody = reader.ReadToEnd();
  1542. Hashtable keysvals = new Hashtable();
  1543. Hashtable headervals = new Hashtable();
  1544. Hashtable requestVars = new Hashtable();
  1545. string host = string.Empty;
  1546. string[] querystringkeys = request.QueryString.AllKeys;
  1547. string[] rHeaders = request.Headers.AllKeys;
  1548. keysvals.Add("body", requestBody);
  1549. keysvals.Add("uri", request.RawUrl);
  1550. keysvals.Add("content-type", request.ContentType);
  1551. keysvals.Add("http-method", request.HttpMethod);
  1552. foreach (string queryname in querystringkeys)
  1553. {
  1554. //m_log.DebugFormat(
  1555. // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
  1556. if(!string.IsNullOrEmpty(queryname))
  1557. {
  1558. keysvals.Add(queryname, request.QueryString[queryname]);
  1559. requestVars.Add(queryname, keysvals[queryname]);
  1560. }
  1561. }
  1562. foreach (string headername in rHeaders)
  1563. {
  1564. //m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
  1565. headervals[headername] = request.Headers[headername];
  1566. }
  1567. keysvals.Add("headers", headervals);
  1568. keysvals.Add("querystringkeys", querystringkeys);
  1569. keysvals.Add("requestvars", requestVars);
  1570. //keysvals.Add("form", request.Form);
  1571. Hashtable responsedata2 = requestprocessor(keysvals);
  1572. return DoHTTPGruntWork(responsedata2, response);
  1573. }
  1574. private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
  1575. {
  1576. if(m_HTTPHandlers.Count == 0)
  1577. {
  1578. httpHandler = null;
  1579. return false;
  1580. }
  1581. var searchquery = CleanSearchPath(path);
  1582. string bestMatch = null;
  1583. bool nomatch = true;
  1584. //m_log.DebugFormat(
  1585. // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
  1586. lock (m_HTTPHandlers)
  1587. {
  1588. foreach (string pattern in m_HTTPHandlers.Keys)
  1589. {
  1590. if (searchquery.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase))
  1591. {
  1592. if (nomatch || searchquery.Length > bestMatch.Length)
  1593. {
  1594. bestMatch = pattern;
  1595. nomatch = false;
  1596. }
  1597. }
  1598. }
  1599. if (nomatch)
  1600. {
  1601. httpHandler = null;
  1602. return false;
  1603. }
  1604. if (bestMatch == "/" && searchquery != "/")
  1605. {
  1606. httpHandler = null;
  1607. return false;
  1608. }
  1609. httpHandler = m_HTTPHandlers[bestMatch];
  1610. return true;
  1611. }
  1612. }
  1613. internal static byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
  1614. {
  1615. int responsecode;
  1616. string responseString = string.Empty;
  1617. byte[] responseData = null;
  1618. string contentType;
  1619. if (responsedata is null)
  1620. {
  1621. responsecode = 500;
  1622. responseString = "No response could be obtained";
  1623. contentType = "text/plain";
  1624. responsedata = new Hashtable();
  1625. }
  1626. else
  1627. {
  1628. try
  1629. {
  1630. //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
  1631. responsecode = (int)responsedata["int_response_code"];
  1632. contentType = (string)responsedata["content_type"];
  1633. if (responsedata["bin_response_data"] is byte[] b)
  1634. responseData = b;
  1635. else
  1636. responseString = (string)responsedata["str_response_string"];
  1637. }
  1638. catch
  1639. {
  1640. responsecode = 500;
  1641. responseString = "No response could be obtained";
  1642. contentType = "text/plain";
  1643. responsedata = new Hashtable();
  1644. }
  1645. }
  1646. if (responsedata.ContainsKey("error_status_text"))
  1647. response.StatusDescription = (string)responsedata["error_status_text"];
  1648. if (responsedata.ContainsKey("http_protocol_version"))
  1649. response.ProtocolVersion = (string)responsedata["http_protocol_version"];
  1650. if (responsedata.ContainsKey("keepalive"))
  1651. {
  1652. bool keepalive = (bool)responsedata["keepalive"];
  1653. response.KeepAlive = keepalive;
  1654. }
  1655. // Cross-Origin Resource Sharing with simple requests
  1656. if (responsedata.ContainsKey("access_control_allow_origin"))
  1657. response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
  1658. //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
  1659. //and should check for NullReferenceExceptions
  1660. if (string.IsNullOrEmpty(contentType))
  1661. {
  1662. contentType = "text/html";
  1663. }
  1664. // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
  1665. response.StatusCode = responsecode;
  1666. if (responsecode == (int)HttpStatusCode.Moved)
  1667. {
  1668. response.Redirect((string)responsedata["str_redirect_location"], HttpStatusCode.Moved);
  1669. }
  1670. response.AddHeader("Content-Type", contentType);
  1671. if (responsedata.ContainsKey("headers"))
  1672. {
  1673. Hashtable headerdata = (Hashtable)responsedata["headers"];
  1674. foreach (string header in headerdata.Keys)
  1675. response.AddHeader(header, headerdata[header].ToString());
  1676. }
  1677. byte[] buffer;
  1678. if (responseData is not null)
  1679. {
  1680. buffer = responseData;
  1681. }
  1682. else
  1683. {
  1684. if(string.IsNullOrEmpty(responseString))
  1685. return null;
  1686. if (!(contentType.Contains("image")
  1687. || contentType.Contains("x-shockwave-flash")
  1688. || contentType.Contains("application/x-oar")
  1689. || contentType.Contains("application/vnd.ll.mesh")))
  1690. {
  1691. // Text
  1692. buffer = Encoding.UTF8.GetBytes(responseString);
  1693. }
  1694. else
  1695. {
  1696. // Binary!
  1697. buffer = Convert.FromBase64String(responseString);
  1698. }
  1699. response.ContentLength64 = buffer.Length;
  1700. response.ContentEncoding = Encoding.UTF8;
  1701. }
  1702. return buffer;
  1703. }
  1704. public byte[] SendHTML404(OSHttpResponse response)
  1705. {
  1706. response.StatusCode = 404;
  1707. response.ContentType = "text/html";
  1708. string responseString = GetHTTP404();
  1709. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1710. response.ContentLength64 = buffer.Length;
  1711. response.ContentEncoding = Encoding.UTF8;
  1712. return buffer;
  1713. }
  1714. public void Start()
  1715. {
  1716. Start(true, true);
  1717. }
  1718. /// <summary>
  1719. /// Start the http server
  1720. /// </summary>
  1721. /// <param name='processPollRequestsAsync'>
  1722. /// If true then poll responses are performed asynchronsly.
  1723. /// Option exists to allow regression tests to perform processing synchronously.
  1724. /// </param>
  1725. public void Start(bool performPollResponsesAsync, bool runPool)
  1726. {
  1727. m_log.Info($"[BASE HTTP SERVER]: Starting HTTP{(UseSSL ? "S" : "")} server on port {Port}");
  1728. try
  1729. {
  1730. //m_httpListener = new HttpListener();
  1731. if (!m_ssl)
  1732. {
  1733. m_httpListener = tinyHTTPListener.Create(m_listenIPAddress, (int)m_port);
  1734. m_httpListener.ExceptionThrown += httpServerException;
  1735. if (DebugLevel > 0)
  1736. {
  1737. m_httpListener.LogWriter = httpserverlog;
  1738. httpserverlog.DebugLevel = 1;
  1739. }
  1740. // Uncomment this line in addition to those in HttpServerLogWriter
  1741. // if you want more detailed trace information from the HttpServer
  1742. //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
  1743. }
  1744. else
  1745. {
  1746. m_httpListener = tinyHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert);
  1747. if(m_certificateValidationCallback is not null)
  1748. m_httpListener.CertificateValidationCallback = m_certificateValidationCallback;
  1749. m_httpListener.ExceptionThrown += httpServerException;
  1750. if (DebugLevel > 0)
  1751. {
  1752. m_httpListener.LogWriter = httpserverlog;
  1753. httpserverlog.DebugLevel = 1;
  1754. }
  1755. }
  1756. m_httpListener.RequestReceived += OnRequest;
  1757. m_httpListener.Start(64);
  1758. lock(m_generalLock)
  1759. {
  1760. if (runPool)
  1761. {
  1762. m_pollServiceManager ??= new PollServiceRequestManager(performPollResponsesAsync, 2, 25000);
  1763. m_pollServiceManager.Start();
  1764. }
  1765. }
  1766. HTTPDRunning = true;
  1767. }
  1768. catch (Exception e)
  1769. {
  1770. m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
  1771. m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + "?");
  1772. // We want this exception to halt the entire server since in current configurations we aren't too
  1773. // useful without inbound HTTP.
  1774. throw;
  1775. }
  1776. m_requestsProcessedStat = new Stat(
  1777. "HTTPRequestsServed",
  1778. "Number of inbound HTTP requests processed",
  1779. "",
  1780. "requests",
  1781. "httpserver",
  1782. Port.ToString(),
  1783. StatType.Pull,
  1784. MeasuresOfInterest.AverageChangeOverTime,
  1785. stat => stat.Value = RequestNumber,
  1786. StatVerbosity.Debug);
  1787. StatsManager.RegisterStat(m_requestsProcessedStat);
  1788. }
  1789. public static void httpServerException(object source, Exception exception)
  1790. {
  1791. if (source.ToString().Equals("HttpServer.HttpListener") && exception.ToString().StartsWith("Mono.Security.Protocol.Tls.TlsException"))
  1792. return;
  1793. m_log.ErrorFormat("[BASE HTTP SERVER]: {0} had an exception {1}", source.ToString(), exception.ToString());
  1794. }
  1795. public void Stop(bool stopPool = false)
  1796. {
  1797. HTTPDRunning = false;
  1798. StatsManager.DeregisterStat(m_requestsProcessedStat);
  1799. try
  1800. {
  1801. lock(m_generalLock)
  1802. {
  1803. if (stopPool && m_pollServiceManager != null)
  1804. m_pollServiceManager.Stop();
  1805. }
  1806. m_httpListener.ExceptionThrown -= httpServerException;
  1807. //m_httpListener2.DisconnectHandler = null;
  1808. m_httpListener.LogWriter = null;
  1809. m_httpListener.RequestReceived -= OnRequest;
  1810. m_httpListener.Stop();
  1811. }
  1812. catch (NullReferenceException)
  1813. {
  1814. m_log.Warn("[BASE HTTP SERVER]: Null Reference when stopping HttpServer.");
  1815. }
  1816. }
  1817. public void RemoveStreamHandler(string httpMethod, string path)
  1818. {
  1819. if (m_streamHandlers.TryRemove(path, out _))
  1820. return;
  1821. string handlerKey = GetHandlerKey(httpMethod, path);
  1822. //m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey);
  1823. m_streamHandlers.TryRemove(handlerKey, out _);
  1824. }
  1825. public void RemoveStreamHandler(string path)
  1826. {
  1827. m_streamHandlers.TryRemove(path, out IRequestHandler _);
  1828. }
  1829. public void RemoveSimpleStreamHandler(string path)
  1830. {
  1831. if(m_simpleStreamHandlers.TryRemove(path, out _))
  1832. return;
  1833. m_simpleStreamVarPath.TryRemove(path, out _);
  1834. }
  1835. public void RemoveHTTPHandler(string httpMethod, string path)
  1836. {
  1837. if (string.IsNullOrEmpty(path))
  1838. return; // Caps module isn't loaded, tries to remove handler where path = null
  1839. lock (m_HTTPHandlers)
  1840. {
  1841. if (httpMethod is not null && httpMethod.Length == 0)
  1842. {
  1843. m_HTTPHandlers.Remove(path);
  1844. return;
  1845. }
  1846. m_HTTPHandlers.Remove(GetHandlerKey(httpMethod, path));
  1847. }
  1848. }
  1849. public void RemovePollServiceHTTPHandler(string httpMethod, string path)
  1850. {
  1851. if(!m_pollHandlers.TryRemove(path, out _))
  1852. m_pollHandlersVarPath.TryRemove(path, out _);
  1853. }
  1854. public void RemovePollServiceHTTPHandler(string path)
  1855. {
  1856. if(!m_pollHandlers.TryRemove(path, out _))
  1857. m_pollHandlersVarPath.TryRemove(path, out _);
  1858. }
  1859. //public bool RemoveAgentHandler(string agent, IHttpAgentHandler handler)
  1860. //{
  1861. // lock (m_agentHandlers)
  1862. // {
  1863. // IHttpAgentHandler foundHandler;
  1864. // if (m_agentHandlers.TryGetValue(agent, out foundHandler) && foundHandler == handler)
  1865. // {
  1866. // m_agentHandlers.Remove(agent);
  1867. // return true;
  1868. // }
  1869. // }
  1870. //
  1871. // return false;
  1872. //}
  1873. public void RemoveXmlRPCHandler(string method)
  1874. {
  1875. lock (m_rpcHandlers)
  1876. m_rpcHandlers.Remove(method);
  1877. }
  1878. public void RemoveJsonRPCHandler(string method)
  1879. {
  1880. lock(jsonRpcHandlers)
  1881. jsonRpcHandlers.Remove(method);
  1882. }
  1883. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  1884. {
  1885. lock (m_llsdHandlers)
  1886. {
  1887. if (m_llsdHandlers.TryGetValue(path, out LLSDMethod foundHandler) && foundHandler == handler)
  1888. {
  1889. m_llsdHandlers.Remove(path);
  1890. return true;
  1891. }
  1892. }
  1893. return false;
  1894. }
  1895. // Fallback HTTP responses in case the HTTP error response files don't exist
  1896. private static string getDefaultHTTP404()
  1897. {
  1898. 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>";
  1899. }
  1900. public void SetHTTP404()
  1901. {
  1902. string file = Path.Combine(".", "http_404.html");
  1903. try
  1904. {
  1905. if (File.Exists(file))
  1906. {
  1907. using (StreamReader sr = File.OpenText(file))
  1908. HTTP404 = sr.ReadToEnd();
  1909. if(string.IsNullOrWhiteSpace(HTTP404))
  1910. HTTP404 = getDefaultHTTP404();
  1911. return;
  1912. }
  1913. }
  1914. catch { }
  1915. HTTP404 = getDefaultHTTP404();
  1916. }
  1917. public string GetHTTP404()
  1918. {
  1919. return HTTP404;
  1920. }
  1921. }
  1922. public class HttpServerContextObj
  1923. {
  1924. public IHttpClientContext context = null;
  1925. public IHttpRequest req = null;
  1926. public OSHttpRequest oreq = null;
  1927. public OSHttpResponse oresp = null;
  1928. public HttpServerContextObj(IHttpClientContext contxt, IHttpRequest reqs)
  1929. {
  1930. context = contxt;
  1931. req = reqs;
  1932. }
  1933. public HttpServerContextObj(OSHttpRequest osreq, OSHttpResponse osresp)
  1934. {
  1935. oreq = osreq;
  1936. oresp = osresp;
  1937. }
  1938. }
  1939. /// <summary>
  1940. /// Relays HttpServer log messages to our own logging mechanism.
  1941. /// </summary>
  1942. /// To use this you must uncomment the switch section
  1943. ///
  1944. /// You may also be able to get additional trace information from HttpServer if you uncomment the UseTraceLogs
  1945. /// property in StartHttp() for the HttpListener
  1946. ///
  1947. public class HttpServerLogWriter : ILogWriter
  1948. {
  1949. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1950. public int DebugLevel {get; set;} = (int)LogPrio.Error;
  1951. public void Write(object source, LogPrio priority, string message)
  1952. {
  1953. if((int)priority < DebugLevel)
  1954. return;
  1955. switch (priority)
  1956. {
  1957. case LogPrio.Trace:
  1958. m_log.DebugFormat("[{0}]: {1}", source, message);
  1959. break;
  1960. case LogPrio.Debug:
  1961. m_log.DebugFormat("[{0}]: {1}", source, message);
  1962. break;
  1963. case LogPrio.Error:
  1964. m_log.ErrorFormat("[{0}]: {1}", source, message);
  1965. break;
  1966. case LogPrio.Info:
  1967. m_log.InfoFormat("[{0}]: {1}", source, message);
  1968. break;
  1969. case LogPrio.Warning:
  1970. m_log.WarnFormat("[{0}]: {1}", source, message);
  1971. break;
  1972. case LogPrio.Fatal:
  1973. m_log.ErrorFormat("[{0}]: FATAL! - {1}", source, message);
  1974. break;
  1975. default:
  1976. break;
  1977. }
  1978. return;
  1979. }
  1980. }
  1981. public class IndexPHPHandler : SimpleStreamHandler
  1982. {
  1983. readonly BaseHttpServer m_server;
  1984. public IndexPHPHandler(BaseHttpServer server)
  1985. : base("/index.php")
  1986. {
  1987. m_server = server;
  1988. }
  1989. protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1990. {
  1991. httpResponse.KeepAlive = false;
  1992. if (m_server is null || !m_server.HTTPDRunning)
  1993. {
  1994. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1995. return;
  1996. }
  1997. if (httpRequest.QueryString.Count == 0)
  1998. {
  1999. httpResponse.Redirect("http://opensimulator.org");
  2000. return;
  2001. }
  2002. if (httpRequest.QueryFlags.Contains("about"))
  2003. {
  2004. httpResponse.Redirect("http://opensimulator.org/wiki/0.9.3.0_Release");
  2005. return;
  2006. }
  2007. if (!httpRequest.QueryAsDictionary.TryGetValue("method", out string method) || string.IsNullOrWhiteSpace(method))
  2008. {
  2009. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  2010. return;
  2011. }
  2012. int indx = method.IndexOf(',');
  2013. if(indx > 0)
  2014. method = method[..indx];
  2015. if (string.IsNullOrWhiteSpace(method))
  2016. {
  2017. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  2018. return;
  2019. }
  2020. SimpleStreamMethod sh = m_server.TryGetIndexPHPMethodHandler(method);
  2021. if (sh is null)
  2022. {
  2023. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  2024. return;
  2025. }
  2026. try
  2027. {
  2028. sh?.Invoke(httpRequest, httpResponse);
  2029. }
  2030. catch
  2031. {
  2032. httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
  2033. }
  2034. }
  2035. }
  2036. }