BaseHttpServer.cs 88 KB

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