BaseHttpServer.cs 94 KB

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