1
0

BaseHttpServer.cs 92 KB

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