BaseHttpServer.cs 89 KB

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