1
0

BaseHttpServer.cs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  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),context);
  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. response.SendChunked = false;
  589. string path = request.RawUrl;
  590. string handlerKey = GetHandlerKey(request.HttpMethod, path);
  591. byte[] buffer = null;
  592. if (TryGetStreamHandler(handlerKey, out requestHandler))
  593. {
  594. if (DebugLevel >= 3)
  595. LogIncomingToStreamHandler(request, requestHandler);
  596. response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type.
  597. if (requestHandler is IStreamedRequestHandler)
  598. {
  599. IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler;
  600. buffer = streamedRequestHandler.Handle(path, request.InputStream, request, response);
  601. }
  602. else if (requestHandler is IGenericHTTPHandler)
  603. {
  604. //m_log.Debug("[BASE HTTP SERVER]: Found Caps based HTTP Handler");
  605. IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler;
  606. string requestBody;
  607. Encoding encoding = Encoding.UTF8;
  608. using(StreamReader reader = new StreamReader(request.InputStream, encoding))
  609. requestBody = reader.ReadToEnd();
  610. Hashtable keysvals = new Hashtable();
  611. Hashtable headervals = new Hashtable();
  612. //string host = String.Empty;
  613. string[] querystringkeys = request.QueryString.AllKeys;
  614. string[] rHeaders = request.Headers.AllKeys;
  615. foreach (string queryname in querystringkeys)
  616. {
  617. keysvals.Add(queryname, request.QueryString[queryname]);
  618. }
  619. foreach (string headername in rHeaders)
  620. {
  621. //m_log.Warn("[HEADER]: " + headername + "=" + request.Headers[headername]);
  622. headervals[headername] = request.Headers[headername];
  623. }
  624. // if (headervals.Contains("Host"))
  625. // {
  626. // host = (string)headervals["Host"];
  627. // }
  628. keysvals.Add("requestbody", requestBody);
  629. keysvals.Add("headers",headervals);
  630. if (keysvals.Contains("method"))
  631. {
  632. //m_log.Warn("[HTTP]: Contains Method");
  633. //string method = (string)keysvals["method"];
  634. //m_log.Warn("[HTTP]: " + requestBody);
  635. }
  636. buffer = DoHTTPGruntWork(HTTPRequestHandler.Handle(path, keysvals), response);
  637. }
  638. else
  639. {
  640. IStreamHandler streamHandler = (IStreamHandler)requestHandler;
  641. using (MemoryStream memoryStream = new MemoryStream())
  642. {
  643. streamHandler.Handle(path, request.InputStream, memoryStream, request, response);
  644. buffer = memoryStream.ToArray();
  645. }
  646. }
  647. }
  648. else
  649. {
  650. switch (request.ContentType)
  651. {
  652. case null:
  653. case "text/html":
  654. if (DebugLevel >= 3)
  655. LogIncomingToContentTypeHandler(request);
  656. buffer = HandleHTTPRequest(request, response);
  657. break;
  658. case "application/llsd+xml":
  659. case "application/xml+llsd":
  660. case "application/llsd+json":
  661. if (DebugLevel >= 3)
  662. LogIncomingToContentTypeHandler(request);
  663. buffer = HandleLLSDRequests(request, response);
  664. break;
  665. case "application/json-rpc":
  666. if (DebugLevel >= 3)
  667. LogIncomingToContentTypeHandler(request);
  668. buffer = HandleJsonRpcRequests(request, response);
  669. break;
  670. case "text/xml":
  671. case "application/xml":
  672. case "application/json":
  673. default:
  674. //m_log.Info("[Debug BASE HTTP SERVER]: in default handler");
  675. // Point of note.. the DoWeHaveA methods check for an EXACT path
  676. // if (request.RawUrl.Contains("/CAPS/EQG"))
  677. // {
  678. // int i = 1;
  679. // }
  680. //m_log.Info("[Debug BASE HTTP SERVER]: Checking for LLSD Handler");
  681. if (DoWeHaveALLSDHandler(request.RawUrl))
  682. {
  683. if (DebugLevel >= 3)
  684. LogIncomingToContentTypeHandler(request);
  685. buffer = HandleLLSDRequests(request, response);
  686. }
  687. // m_log.DebugFormat("[BASE HTTP SERVER]: Checking for HTTP Handler for request {0}", request.RawUrl);
  688. else if (DoWeHaveAHTTPHandler(request.RawUrl))
  689. {
  690. if (DebugLevel >= 3)
  691. LogIncomingToContentTypeHandler(request);
  692. buffer = HandleHTTPRequest(request, response);
  693. }
  694. else
  695. {
  696. if (DebugLevel >= 3)
  697. LogIncomingToXmlRpcHandler(request);
  698. // generic login request.
  699. buffer = HandleXmlRpcRequests(request, response);
  700. }
  701. break;
  702. }
  703. }
  704. if(request.InputStream != null && request.InputStream.CanRead)
  705. request.InputStream.Dispose();
  706. if (buffer != null)
  707. {
  708. if (WebUtil.DebugLevel >= 5)
  709. {
  710. string output = System.Text.Encoding.UTF8.GetString(buffer);
  711. if (WebUtil.DebugLevel >= 6)
  712. {
  713. // Always truncate binary blobs. We don't have a ContentType, so detect them using the request name.
  714. if ((requestHandler != null && requestHandler.Name == "GetMesh"))
  715. {
  716. if (output.Length > WebUtil.MaxRequestDiagLength)
  717. output = output.Substring(0, WebUtil.MaxRequestDiagLength) + "...";
  718. }
  719. }
  720. WebUtil.LogResponseDetail(RequestNumber, output);
  721. }
  722. if (!response.SendChunked && response.ContentLength64 <= 0)
  723. response.ContentLength64 = buffer.LongLength;
  724. response.OutputStream.Write(buffer, 0, buffer.Length);
  725. }
  726. // Do not include the time taken to actually send the response to the caller in the measurement
  727. // time. This is to avoid logging when it's the client that is slow to process rather than the
  728. // server
  729. requestEndTick = Environment.TickCount;
  730. response.Send();
  731. }
  732. catch (SocketException e)
  733. {
  734. // At least on linux, it appears that if the client makes a request without requiring the response,
  735. // an unconnected socket exception is thrown when we close the response output stream. There's no
  736. // obvious way to tell if the client didn't require the response, so instead we'll catch and ignore
  737. // the exception instead.
  738. //
  739. // An alternative may be to turn off all response write exceptions on the HttpListener, but let's go
  740. // with the minimum first
  741. m_log.Warn(String.Format("[BASE HTTP SERVER]: HandleRequest threw {0}.\nNOTE: this may be spurious on Linux ", e.Message), e);
  742. }
  743. catch (IOException e)
  744. {
  745. m_log.Error("[BASE HTTP SERVER]: HandleRequest() threw exception ", e);
  746. }
  747. catch (Exception e)
  748. {
  749. m_log.Error("[BASE HTTP SERVER]: HandleRequest() threw exception ", e);
  750. try
  751. {
  752. byte[] buffer500 = SendHTML500(response);
  753. response.OutputStream.Write(buffer500, 0, buffer500.Length);
  754. response.Send();
  755. }
  756. catch
  757. {
  758. }
  759. }
  760. finally
  761. {
  762. if(request.InputStream != null && request.InputStream.CanRead)
  763. request.InputStream.Close();
  764. // Every month or so this will wrap and give bad numbers, not really a problem
  765. // since its just for reporting
  766. int tickdiff = requestEndTick - requestStartTick;
  767. if (tickdiff > 3000 && (requestHandler == null || requestHandler.Name == null || requestHandler.Name != "GetTexture"))
  768. {
  769. m_log.InfoFormat(
  770. "[LOGHTTP] Slow handling of {0} {1} {2} {3} {4} from {5} took {6}ms",
  771. RequestNumber,
  772. requestMethod,
  773. uriString,
  774. requestHandler != null ? requestHandler.Name : "",
  775. requestHandler != null ? requestHandler.Description : "",
  776. request.RemoteIPEndPoint,
  777. tickdiff);
  778. }
  779. else if (DebugLevel >= 4)
  780. {
  781. m_log.DebugFormat(
  782. "[LOGHTTP] HTTP IN {0} :{1} took {2}ms",
  783. RequestNumber,
  784. Port,
  785. tickdiff);
  786. }
  787. }
  788. }
  789. private void LogIncomingToStreamHandler(OSHttpRequest request, IRequestHandler requestHandler)
  790. {
  791. m_log.DebugFormat(
  792. "[LOGHTTP] HTTP IN {0} :{1} stream handler {2} {3} {4} {5} from {6}",
  793. RequestNumber,
  794. Port,
  795. request.HttpMethod,
  796. request.Url.PathAndQuery,
  797. requestHandler.Name,
  798. requestHandler.Description,
  799. request.RemoteIPEndPoint);
  800. if (DebugLevel >= 5)
  801. LogIncomingInDetail(request);
  802. }
  803. private void LogIncomingToContentTypeHandler(OSHttpRequest request)
  804. {
  805. m_log.DebugFormat(
  806. "[LOGHTTP] HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}",
  807. RequestNumber,
  808. Port,
  809. string.IsNullOrEmpty(request.ContentType) ? "not set" : request.ContentType,
  810. request.HttpMethod,
  811. request.Url.PathAndQuery,
  812. request.RemoteIPEndPoint);
  813. if (DebugLevel >= 5)
  814. LogIncomingInDetail(request);
  815. }
  816. private void LogIncomingToXmlRpcHandler(OSHttpRequest request)
  817. {
  818. m_log.DebugFormat(
  819. "[LOGHTTP] HTTP IN {0} :{1} assumed generic XMLRPC request {2} {3} from {4}",
  820. RequestNumber,
  821. Port,
  822. request.HttpMethod,
  823. request.Url.PathAndQuery,
  824. request.RemoteIPEndPoint);
  825. if (DebugLevel >= 5)
  826. LogIncomingInDetail(request);
  827. }
  828. private void LogIncomingInDetail(OSHttpRequest request)
  829. {
  830. if (request.ContentType == "application/octet-stream")
  831. return; // never log these; they're just binary data
  832. Stream inputStream = Util.Copy(request.InputStream);
  833. Stream innerStream = null;
  834. try
  835. {
  836. if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
  837. {
  838. innerStream = inputStream;
  839. inputStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress);
  840. }
  841. using (StreamReader reader = new StreamReader(inputStream, Encoding.UTF8))
  842. {
  843. string output;
  844. if (DebugLevel == 5)
  845. {
  846. char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed
  847. int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1);
  848. output = new string(chars, 0, Math.Min(len, WebUtil.MaxRequestDiagLength));
  849. if (len > WebUtil.MaxRequestDiagLength)
  850. output += "...";
  851. }
  852. else
  853. {
  854. output = reader.ReadToEnd();
  855. }
  856. m_log.DebugFormat("[LOGHTTP] {0}", Util.BinaryToASCII(output));
  857. }
  858. }
  859. finally
  860. {
  861. if (innerStream != null)
  862. innerStream.Dispose();
  863. inputStream.Dispose();
  864. }
  865. }
  866. private readonly string HANDLER_SEPARATORS = "/?&#-";
  867. private bool TryGetStreamHandler(string handlerKey, out IRequestHandler streamHandler)
  868. {
  869. string bestMatch = null;
  870. lock (m_streamHandlers)
  871. {
  872. foreach (string pattern in m_streamHandlers.Keys)
  873. {
  874. if ((handlerKey == pattern)
  875. || (handlerKey.StartsWith(pattern) && (HANDLER_SEPARATORS.IndexOf(handlerKey[pattern.Length]) >= 0)))
  876. {
  877. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  878. {
  879. bestMatch = pattern;
  880. }
  881. }
  882. }
  883. if (String.IsNullOrEmpty(bestMatch))
  884. {
  885. streamHandler = null;
  886. return false;
  887. }
  888. else
  889. {
  890. streamHandler = m_streamHandlers[bestMatch];
  891. return true;
  892. }
  893. }
  894. }
  895. private bool TryGetPollServiceHTTPHandler(string handlerKey, out PollServiceEventArgs oServiceEventArgs)
  896. {
  897. string bestMatch = null;
  898. lock (m_pollHandlers)
  899. {
  900. foreach (string pattern in m_pollHandlers.Keys)
  901. {
  902. if ((handlerKey == pattern)
  903. || (handlerKey.StartsWith(pattern) && (HANDLER_SEPARATORS.IndexOf(handlerKey[pattern.Length]) >= 0)))
  904. {
  905. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  906. {
  907. bestMatch = pattern;
  908. }
  909. }
  910. }
  911. if (String.IsNullOrEmpty(bestMatch))
  912. {
  913. oServiceEventArgs = null;
  914. return false;
  915. }
  916. else
  917. {
  918. oServiceEventArgs = m_pollHandlers[bestMatch];
  919. return true;
  920. }
  921. }
  922. }
  923. private bool TryGetHTTPHandler(string handlerKey, out GenericHTTPMethod HTTPHandler)
  924. {
  925. // m_log.DebugFormat("[BASE HTTP HANDLER]: Looking for HTTP handler for {0}", handlerKey);
  926. string bestMatch = null;
  927. lock (m_HTTPHandlers)
  928. {
  929. foreach (string pattern in m_HTTPHandlers.Keys)
  930. {
  931. if ((handlerKey == pattern)
  932. || (handlerKey.StartsWith(pattern) && (HANDLER_SEPARATORS.IndexOf(handlerKey[pattern.Length]) >= 0)))
  933. {
  934. if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
  935. {
  936. bestMatch = pattern;
  937. }
  938. }
  939. }
  940. if (String.IsNullOrEmpty(bestMatch))
  941. {
  942. HTTPHandler = null;
  943. return false;
  944. }
  945. else
  946. {
  947. HTTPHandler = m_HTTPHandlers[bestMatch];
  948. return true;
  949. }
  950. }
  951. }
  952. // private bool TryGetAgentHandler(OSHttpRequest request, OSHttpResponse response, out IHttpAgentHandler agentHandler)
  953. // {
  954. // agentHandler = null;
  955. //
  956. // lock (m_agentHandlers)
  957. // {
  958. // foreach (IHttpAgentHandler handler in m_agentHandlers.Values)
  959. // {
  960. // if (handler.Match(request, response))
  961. // {
  962. // agentHandler = handler;
  963. // return true;
  964. // }
  965. // }
  966. // }
  967. //
  968. // return false;
  969. // }
  970. /// <summary>
  971. /// Try all the registered xmlrpc handlers when an xmlrpc request is received.
  972. /// Sends back an XMLRPC unknown request response if no handler is registered for the requested method.
  973. /// </summary>
  974. /// <param name="request"></param>
  975. /// <param name="response"></param>
  976. private byte[] HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
  977. {
  978. String requestBody;
  979. Stream requestStream = Util.Copy(request.InputStream);
  980. Stream innerStream = null;
  981. try
  982. {
  983. if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
  984. {
  985. innerStream = requestStream;
  986. requestStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress);
  987. }
  988. using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8))
  989. requestBody = reader.ReadToEnd();
  990. }
  991. finally
  992. {
  993. if (innerStream != null && innerStream.CanRead)
  994. innerStream.Dispose();
  995. if (requestStream.CanRead)
  996. requestStream.Dispose();
  997. }
  998. //m_log.Debug(requestBody);
  999. requestBody = requestBody.Replace("<base64></base64>", "");
  1000. string responseString = String.Empty;
  1001. XmlRpcRequest xmlRprcRequest = null;
  1002. bool gridproxy = false;
  1003. if (requestBody.Contains("encoding=\"utf-8"))
  1004. {
  1005. int channelindx = -1;
  1006. int optionsindx = requestBody.IndexOf(">options<");
  1007. if(optionsindx >0)
  1008. {
  1009. channelindx = requestBody.IndexOf(">channel<");
  1010. if (optionsindx < channelindx)
  1011. gridproxy = true;
  1012. }
  1013. }
  1014. try
  1015. {
  1016. xmlRprcRequest = (XmlRpcRequest) (new XmlRpcRequestDeserializer()).Deserialize(requestBody);
  1017. }
  1018. catch (XmlException e)
  1019. {
  1020. if (DebugLevel >= 1)
  1021. {
  1022. if (DebugLevel >= 2)
  1023. m_log.Warn(
  1024. string.Format(
  1025. "[BASE HTTP SERVER]: Got XMLRPC request with invalid XML from {0}. XML was '{1}'. Sending blank response. Exception ",
  1026. request.RemoteIPEndPoint, requestBody),
  1027. e);
  1028. else
  1029. {
  1030. m_log.WarnFormat(
  1031. "[BASE HTTP SERVER]: Got XMLRPC request with invalid XML from {0}, length {1}. Sending blank response.",
  1032. request.RemoteIPEndPoint, requestBody.Length);
  1033. }
  1034. }
  1035. }
  1036. if (xmlRprcRequest != null)
  1037. {
  1038. string methodName = xmlRprcRequest.MethodName;
  1039. if (methodName != null)
  1040. {
  1041. xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
  1042. XmlRpcResponse xmlRpcResponse;
  1043. XmlRpcMethod method;
  1044. bool methodWasFound;
  1045. bool keepAlive = false;
  1046. lock (m_rpcHandlers)
  1047. {
  1048. methodWasFound = m_rpcHandlers.TryGetValue(methodName, out method);
  1049. if (methodWasFound)
  1050. keepAlive = m_rpcHandlersKeepAlive[methodName];
  1051. }
  1052. if (methodWasFound)
  1053. {
  1054. xmlRprcRequest.Params.Add(request.Url); // Param[2]
  1055. string xff = "X-Forwarded-For";
  1056. string xfflower = xff.ToLower();
  1057. foreach (string s in request.Headers.AllKeys)
  1058. {
  1059. if (s != null && s.Equals(xfflower))
  1060. {
  1061. xff = xfflower;
  1062. break;
  1063. }
  1064. }
  1065. xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3]
  1066. if (gridproxy)
  1067. xmlRprcRequest.Params.Add("gridproxy"); // Param[4]
  1068. // reserve this for
  1069. // ... by Fumi.Iseki for DTLNSLMoneyServer
  1070. // BUT make its presence possible to detect/parse
  1071. string rcn = request.IHttpClientContext.SSLCommonName;
  1072. if(!string.IsNullOrWhiteSpace(rcn))
  1073. {
  1074. rcn = "SSLCN:" + rcn;
  1075. xmlRprcRequest.Params.Add(rcn); // Param[4] or Param[5]
  1076. }
  1077. try
  1078. {
  1079. xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
  1080. }
  1081. catch(Exception e)
  1082. {
  1083. string errorMessage
  1084. = String.Format(
  1085. "Requested method [{0}] from {1} threw exception: {2} {3}",
  1086. methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace);
  1087. m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
  1088. // if the registered XmlRpc method threw an exception, we pass a fault-code along
  1089. xmlRpcResponse = new XmlRpcResponse();
  1090. // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1091. xmlRpcResponse.SetFault(-32603, errorMessage);
  1092. }
  1093. // if the method wasn't found, we can't determine KeepAlive state anyway, so lets do it only here
  1094. response.KeepAlive = keepAlive;
  1095. }
  1096. else
  1097. {
  1098. xmlRpcResponse = new XmlRpcResponse();
  1099. // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1100. xmlRpcResponse.SetFault(
  1101. XmlRpcErrorCodes.SERVER_ERROR_METHOD,
  1102. String.Format("Requested method [{0}] not found", methodName));
  1103. }
  1104. response.ContentType = "text/xml";
  1105. using (MemoryStream outs = new MemoryStream())
  1106. using (XmlTextWriter writer = new XmlTextWriter(outs, UTF8NoBOM))
  1107. {
  1108. writer.Formatting = Formatting.None;
  1109. XmlRpcResponseSerializer.Singleton.Serialize(writer, xmlRpcResponse);
  1110. writer.Flush();
  1111. outs.Flush();
  1112. outs.Position = 0;
  1113. using (StreamReader sr = new StreamReader(outs))
  1114. {
  1115. responseString = sr.ReadToEnd();
  1116. }
  1117. }
  1118. }
  1119. else
  1120. {
  1121. //HandleLLSDRequests(request, response);
  1122. response.ContentType = "text/plain";
  1123. response.StatusCode = 404;
  1124. response.StatusDescription = "Not Found";
  1125. response.ProtocolVersion = "HTTP/1.0";
  1126. responseString = "Not found";
  1127. response.KeepAlive = false;
  1128. m_log.ErrorFormat(
  1129. "[BASE HTTP SERVER]: Handler not found for http request {0} {1}",
  1130. request.HttpMethod, request.Url.PathAndQuery);
  1131. }
  1132. }
  1133. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1134. response.SendChunked = false;
  1135. response.ContentLength64 = buffer.Length;
  1136. response.ContentEncoding = Encoding.UTF8;
  1137. return buffer;
  1138. }
  1139. // JsonRpc (v2.0 only)
  1140. // Batch requests not yet supported
  1141. private byte[] HandleJsonRpcRequests(OSHttpRequest request, OSHttpResponse response)
  1142. {
  1143. Stream requestStream = request.InputStream;
  1144. JsonRpcResponse jsonRpcResponse = new JsonRpcResponse();
  1145. OSDMap jsonRpcRequest = null;
  1146. try
  1147. {
  1148. jsonRpcRequest = (OSDMap)OSDParser.DeserializeJson(requestStream);
  1149. }
  1150. catch (LitJson.JsonException e)
  1151. {
  1152. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1153. jsonRpcResponse.Error.Message = e.Message;
  1154. }
  1155. requestStream.Close();
  1156. if (jsonRpcRequest != null)
  1157. {
  1158. if (jsonRpcRequest.ContainsKey("jsonrpc") || jsonRpcRequest["jsonrpc"].AsString() == "2.0")
  1159. {
  1160. jsonRpcResponse.JsonRpc = "2.0";
  1161. // If we have no id, then it's a "notification"
  1162. if (jsonRpcRequest.ContainsKey("id"))
  1163. {
  1164. jsonRpcResponse.Id = jsonRpcRequest["id"].AsString();
  1165. }
  1166. string methodname = jsonRpcRequest["method"];
  1167. JsonRPCMethod method;
  1168. if (jsonRpcHandlers.ContainsKey(methodname))
  1169. {
  1170. lock(jsonRpcHandlers)
  1171. {
  1172. jsonRpcHandlers.TryGetValue(methodname, out method);
  1173. }
  1174. bool res = false;
  1175. try
  1176. {
  1177. res = method(jsonRpcRequest, ref jsonRpcResponse);
  1178. if(!res)
  1179. {
  1180. // The handler sent back an unspecified error
  1181. if(jsonRpcResponse.Error.Code == 0)
  1182. {
  1183. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1184. }
  1185. }
  1186. }
  1187. catch (Exception e)
  1188. {
  1189. string ErrorMessage = string.Format("[BASE HTTP SERVER]: Json-Rpc Handler Error method {0} - {1}", methodname, e.Message);
  1190. m_log.Error(ErrorMessage);
  1191. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1192. jsonRpcResponse.Error.Message = ErrorMessage;
  1193. }
  1194. }
  1195. else // Error no hanlder defined for requested method
  1196. {
  1197. jsonRpcResponse.Error.Code = ErrorCode.InvalidRequest;
  1198. jsonRpcResponse.Error.Message = string.Format ("No handler defined for {0}", methodname);
  1199. }
  1200. }
  1201. else // not json-rpc 2.0 could be v1
  1202. {
  1203. jsonRpcResponse.Error.Code = ErrorCode.InvalidRequest;
  1204. jsonRpcResponse.Error.Message = "Must be valid json-rpc 2.0 see: http://www.jsonrpc.org/specification";
  1205. if (jsonRpcRequest.ContainsKey("id"))
  1206. jsonRpcResponse.Id = jsonRpcRequest["id"].AsString();
  1207. }
  1208. }
  1209. response.KeepAlive = true;
  1210. string responseData = string.Empty;
  1211. responseData = jsonRpcResponse.Serialize();
  1212. byte[] buffer = Encoding.UTF8.GetBytes(responseData);
  1213. return buffer;
  1214. }
  1215. private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response)
  1216. {
  1217. //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
  1218. Stream requestStream = request.InputStream;
  1219. string requestBody;
  1220. Encoding encoding = Encoding.UTF8;
  1221. using(StreamReader reader = new StreamReader(requestStream, encoding))
  1222. requestBody= reader.ReadToEnd();
  1223. //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
  1224. OSD llsdRequest = null;
  1225. OSD llsdResponse = null;
  1226. bool LegacyLLSDLoginLibOMV = (requestBody.Contains("passwd") && requestBody.Contains("mac") && requestBody.Contains("viewer_digest"));
  1227. if (requestBody.Length == 0)
  1228. // Get Request
  1229. {
  1230. requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>";
  1231. }
  1232. try
  1233. {
  1234. llsdRequest = OSDParser.Deserialize(requestBody);
  1235. }
  1236. catch (Exception ex)
  1237. {
  1238. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1239. }
  1240. if (llsdRequest != null)// && m_defaultLlsdHandler != null)
  1241. {
  1242. LLSDMethod llsdhandler = null;
  1243. if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV)
  1244. {
  1245. // we found a registered llsd handler to service this request
  1246. llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint.ToString());
  1247. }
  1248. else
  1249. {
  1250. // we didn't find a registered llsd handler to service this request
  1251. // check if we have a default llsd handler
  1252. if (m_defaultLlsdHandler != null)
  1253. {
  1254. // LibOMV path
  1255. llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
  1256. }
  1257. else
  1258. {
  1259. // Oops, no handler for this.. give em the failed message
  1260. llsdResponse = GenerateNoLLSDHandlerResponse();
  1261. }
  1262. }
  1263. }
  1264. else
  1265. {
  1266. llsdResponse = GenerateNoLLSDHandlerResponse();
  1267. }
  1268. byte[] buffer = new byte[0];
  1269. if (llsdResponse.ToString() == "shutdown404!")
  1270. {
  1271. response.ContentType = "text/plain";
  1272. response.StatusCode = 404;
  1273. response.StatusDescription = "Not Found";
  1274. response.ProtocolVersion = "HTTP/1.0";
  1275. buffer = Encoding.UTF8.GetBytes("Not found");
  1276. }
  1277. else
  1278. {
  1279. // Select an appropriate response format
  1280. buffer = BuildLLSDResponse(request, response, llsdResponse);
  1281. }
  1282. response.SendChunked = false;
  1283. response.ContentLength64 = buffer.Length;
  1284. response.ContentEncoding = Encoding.UTF8;
  1285. response.KeepAlive = true;
  1286. return buffer;
  1287. }
  1288. private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
  1289. {
  1290. if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
  1291. {
  1292. foreach (string strAccept in request.AcceptTypes)
  1293. {
  1294. switch (strAccept)
  1295. {
  1296. case "application/llsd+xml":
  1297. case "application/xml":
  1298. case "text/xml":
  1299. response.ContentType = strAccept;
  1300. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1301. case "application/llsd+json":
  1302. case "application/json":
  1303. response.ContentType = strAccept;
  1304. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1305. }
  1306. }
  1307. }
  1308. if (!String.IsNullOrEmpty(request.ContentType))
  1309. {
  1310. switch (request.ContentType)
  1311. {
  1312. case "application/llsd+xml":
  1313. case "application/xml":
  1314. case "text/xml":
  1315. response.ContentType = request.ContentType;
  1316. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1317. case "application/llsd+json":
  1318. case "application/json":
  1319. response.ContentType = request.ContentType;
  1320. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1321. }
  1322. }
  1323. // response.ContentType = "application/llsd+json";
  1324. // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1325. response.ContentType = "application/llsd+xml";
  1326. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1327. }
  1328. /// <summary>
  1329. /// Checks if we have an Exact path in the LLSD handlers for the path provided
  1330. /// </summary>
  1331. /// <param name="path">URI of the request</param>
  1332. /// <returns>true if we have one, false if not</returns>
  1333. private bool DoWeHaveALLSDHandler(string path)
  1334. {
  1335. string[] pathbase = path.Split('/');
  1336. string searchquery = "/";
  1337. if (pathbase.Length < 1)
  1338. return false;
  1339. for (int i = 1; i < pathbase.Length; i++)
  1340. {
  1341. searchquery += pathbase[i];
  1342. if (pathbase.Length - 1 != i)
  1343. searchquery += "/";
  1344. }
  1345. string bestMatch = null;
  1346. lock (m_llsdHandlers)
  1347. {
  1348. foreach (string pattern in m_llsdHandlers.Keys)
  1349. {
  1350. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1351. bestMatch = pattern;
  1352. }
  1353. }
  1354. // extra kicker to remove the default XMLRPC login case.. just in case..
  1355. if (path != "/" && bestMatch == "/" && searchquery != "/")
  1356. return false;
  1357. if (path == "/")
  1358. return false;
  1359. if (String.IsNullOrEmpty(bestMatch))
  1360. {
  1361. return false;
  1362. }
  1363. else
  1364. {
  1365. return true;
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// Checks if we have an Exact path in the HTTP handlers for the path provided
  1370. /// </summary>
  1371. /// <param name="path">URI of the request</param>
  1372. /// <returns>true if we have one, false if not</returns>
  1373. private bool DoWeHaveAHTTPHandler(string path)
  1374. {
  1375. string[] pathbase = path.Split('/');
  1376. string searchquery = "/";
  1377. if (pathbase.Length < 1)
  1378. return false;
  1379. for (int i = 1; i < pathbase.Length; i++)
  1380. {
  1381. searchquery += pathbase[i];
  1382. if (pathbase.Length - 1 != i)
  1383. searchquery += "/";
  1384. }
  1385. string bestMatch = null;
  1386. //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
  1387. lock (m_HTTPHandlers)
  1388. {
  1389. foreach (string pattern in m_HTTPHandlers.Keys)
  1390. {
  1391. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1392. {
  1393. bestMatch = pattern;
  1394. }
  1395. }
  1396. // extra kicker to remove the default XMLRPC login case.. just in case..
  1397. if (path == "/")
  1398. return false;
  1399. if (String.IsNullOrEmpty(bestMatch))
  1400. {
  1401. return false;
  1402. }
  1403. else
  1404. {
  1405. return true;
  1406. }
  1407. }
  1408. }
  1409. private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
  1410. {
  1411. llsdHandler = null;
  1412. // Pull out the first part of the path
  1413. // splitting the path by '/' means we'll get the following return..
  1414. // {0}/{1}/{2}
  1415. // where {0} isn't something we really control 100%
  1416. string[] pathbase = path.Split('/');
  1417. string searchquery = "/";
  1418. if (pathbase.Length < 1)
  1419. return false;
  1420. for (int i=1; i<pathbase.Length; i++)
  1421. {
  1422. searchquery += pathbase[i];
  1423. if (pathbase.Length-1 != i)
  1424. searchquery += "/";
  1425. }
  1426. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1427. //
  1428. // [] = optional
  1429. // /resource/UUID/action[/action]
  1430. //
  1431. // now try to get the closest match to the reigstered path
  1432. // at least for OGP, registered path would probably only consist of the /resource/
  1433. string bestMatch = null;
  1434. lock (m_llsdHandlers)
  1435. {
  1436. foreach (string pattern in m_llsdHandlers.Keys)
  1437. {
  1438. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1439. {
  1440. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1441. {
  1442. // You have to specifically register for '/' and to get it, you must specificaly request it
  1443. //
  1444. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1445. bestMatch = pattern;
  1446. }
  1447. }
  1448. }
  1449. if (String.IsNullOrEmpty(bestMatch))
  1450. {
  1451. llsdHandler = null;
  1452. return false;
  1453. }
  1454. else
  1455. {
  1456. llsdHandler = m_llsdHandlers[bestMatch];
  1457. return true;
  1458. }
  1459. }
  1460. }
  1461. private OSDMap GenerateNoLLSDHandlerResponse()
  1462. {
  1463. OSDMap map = new OSDMap();
  1464. map["reason"] = OSD.FromString("LLSDRequest");
  1465. map["message"] = OSD.FromString("No handler registered for LLSD Requests");
  1466. map["login"] = OSD.FromString("false");
  1467. return map;
  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.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1478. return null;
  1479. default:
  1480. return HandleContentVerbs(request, response);
  1481. }
  1482. }
  1483. private byte[] HandleContentVerbs(OSHttpRequest request, OSHttpResponse response)
  1484. {
  1485. // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl);
  1486. // This is a test. There's a workable alternative.. as this way sucks.
  1487. // We'd like to put this into a text file parhaps that's easily editable.
  1488. //
  1489. // For this test to work, I used the following secondlife.exe parameters
  1490. // "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
  1491. //
  1492. // Even after all that, there's still an error, but it's a start.
  1493. //
  1494. // I depend on show_login_form being in the secondlife.exe parameters to figure out
  1495. // to display the form, or process it.
  1496. // a better way would be nifty.
  1497. byte[] buffer;
  1498. Stream requestStream = request.InputStream;
  1499. string requestBody;
  1500. Encoding encoding = Encoding.UTF8;
  1501. using(StreamReader reader = new StreamReader(requestStream, encoding))
  1502. requestBody = reader.ReadToEnd();
  1503. Hashtable keysvals = new Hashtable();
  1504. Hashtable headervals = new Hashtable();
  1505. Hashtable requestVars = new Hashtable();
  1506. string host = String.Empty;
  1507. string[] querystringkeys = request.QueryString.AllKeys;
  1508. string[] rHeaders = request.Headers.AllKeys;
  1509. keysvals.Add("body", requestBody);
  1510. keysvals.Add("uri", request.RawUrl);
  1511. keysvals.Add("content-type", request.ContentType);
  1512. keysvals.Add("http-method", request.HttpMethod);
  1513. foreach (string queryname in querystringkeys)
  1514. {
  1515. // m_log.DebugFormat(
  1516. // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
  1517. keysvals.Add(queryname, request.QueryString[queryname]);
  1518. requestVars.Add(queryname, keysvals[queryname]);
  1519. }
  1520. foreach (string headername in rHeaders)
  1521. {
  1522. // m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
  1523. headervals[headername] = request.Headers[headername];
  1524. }
  1525. if (headervals.Contains("Host"))
  1526. {
  1527. host = (string)headervals["Host"];
  1528. }
  1529. keysvals.Add("headers", headervals);
  1530. keysvals.Add("querystringkeys", querystringkeys);
  1531. keysvals.Add("requestvars", requestVars);
  1532. // keysvals.Add("form", request.Form);
  1533. if (keysvals.Contains("method"))
  1534. {
  1535. // m_log.Debug("[BASE HTTP SERVER]: Contains Method");
  1536. string method = (string) keysvals["method"];
  1537. // m_log.Debug("[BASE HTTP SERVER]: " + requestBody);
  1538. GenericHTTPMethod requestprocessor;
  1539. bool foundHandler = TryGetHTTPHandler(method, out requestprocessor);
  1540. if (foundHandler)
  1541. {
  1542. Hashtable responsedata1 = requestprocessor(keysvals);
  1543. buffer = DoHTTPGruntWork(responsedata1,response);
  1544. //SendHTML500(response);
  1545. }
  1546. else
  1547. {
  1548. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found");
  1549. buffer = SendHTML404(response, host);
  1550. }
  1551. }
  1552. else
  1553. {
  1554. GenericHTTPMethod requestprocessor;
  1555. bool foundHandler = TryGetHTTPHandlerPathBased(request.RawUrl, out requestprocessor);
  1556. if (foundHandler)
  1557. {
  1558. Hashtable responsedata2 = requestprocessor(keysvals);
  1559. buffer = DoHTTPGruntWork(responsedata2, response);
  1560. //SendHTML500(response);
  1561. }
  1562. else
  1563. {
  1564. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found2");
  1565. buffer = SendHTML404(response, host);
  1566. }
  1567. }
  1568. return buffer;
  1569. }
  1570. private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
  1571. {
  1572. httpHandler = null;
  1573. // Pull out the first part of the path
  1574. // splitting the path by '/' means we'll get the following return..
  1575. // {0}/{1}/{2}
  1576. // where {0} isn't something we really control 100%
  1577. string[] pathbase = path.Split('/');
  1578. string searchquery = "/";
  1579. if (pathbase.Length < 1)
  1580. return false;
  1581. for (int i = 1; i < pathbase.Length; i++)
  1582. {
  1583. searchquery += pathbase[i];
  1584. if (pathbase.Length - 1 != i)
  1585. searchquery += "/";
  1586. }
  1587. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1588. //
  1589. // [] = optional
  1590. // /resource/UUID/action[/action]
  1591. //
  1592. // now try to get the closest match to the reigstered path
  1593. // at least for OGP, registered path would probably only consist of the /resource/
  1594. string bestMatch = null;
  1595. // m_log.DebugFormat(
  1596. // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
  1597. lock (m_HTTPHandlers)
  1598. {
  1599. foreach (string pattern in m_HTTPHandlers.Keys)
  1600. {
  1601. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1602. {
  1603. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1604. {
  1605. // You have to specifically register for '/' and to get it, you must specifically request it
  1606. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1607. bestMatch = pattern;
  1608. }
  1609. }
  1610. }
  1611. if (String.IsNullOrEmpty(bestMatch))
  1612. {
  1613. httpHandler = null;
  1614. return false;
  1615. }
  1616. else
  1617. {
  1618. if (bestMatch == "/" && searchquery != "/")
  1619. return false;
  1620. httpHandler = m_HTTPHandlers[bestMatch];
  1621. return true;
  1622. }
  1623. }
  1624. }
  1625. internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
  1626. {
  1627. int responsecode;
  1628. string responseString = String.Empty;
  1629. byte[] responseData = null;
  1630. string contentType;
  1631. if (responsedata == null)
  1632. {
  1633. responsecode = 500;
  1634. responseString = "No response could be obtained";
  1635. contentType = "text/plain";
  1636. responsedata = new Hashtable();
  1637. }
  1638. else
  1639. {
  1640. try
  1641. {
  1642. //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
  1643. responsecode = (int)responsedata["int_response_code"];
  1644. if (responsedata["bin_response_data"] != null)
  1645. responseData = (byte[])responsedata["bin_response_data"];
  1646. else
  1647. responseString = (string)responsedata["str_response_string"];
  1648. contentType = (string)responsedata["content_type"];
  1649. if (responseString == null)
  1650. responseString = String.Empty;
  1651. }
  1652. catch
  1653. {
  1654. responsecode = 500;
  1655. responseString = "No response could be obtained";
  1656. contentType = "text/plain";
  1657. responsedata = new Hashtable();
  1658. }
  1659. }
  1660. if (responsedata.ContainsKey("error_status_text"))
  1661. {
  1662. response.StatusDescription = (string)responsedata["error_status_text"];
  1663. }
  1664. if (responsedata.ContainsKey("http_protocol_version"))
  1665. {
  1666. response.ProtocolVersion = (string)responsedata["http_protocol_version"];
  1667. }
  1668. if (responsedata.ContainsKey("keepalive"))
  1669. {
  1670. bool keepalive = (bool)responsedata["keepalive"];
  1671. response.KeepAlive = keepalive;
  1672. }
  1673. // Cross-Origin Resource Sharing with simple requests
  1674. if (responsedata.ContainsKey("access_control_allow_origin"))
  1675. response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
  1676. //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
  1677. //and should check for NullReferenceExceptions
  1678. if (string.IsNullOrEmpty(contentType))
  1679. {
  1680. contentType = "text/html";
  1681. }
  1682. // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
  1683. response.StatusCode = responsecode;
  1684. if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently)
  1685. {
  1686. response.RedirectLocation = (string)responsedata["str_redirect_location"];
  1687. response.StatusCode = responsecode;
  1688. }
  1689. response.AddHeader("Content-Type", contentType);
  1690. if (responsedata.ContainsKey("headers"))
  1691. {
  1692. Hashtable headerdata = (Hashtable)responsedata["headers"];
  1693. foreach (string header in headerdata.Keys)
  1694. response.AddHeader(header, headerdata[header].ToString());
  1695. }
  1696. byte[] buffer;
  1697. if (responseData != null)
  1698. {
  1699. buffer = responseData;
  1700. }
  1701. else
  1702. {
  1703. if (!(contentType.Contains("image")
  1704. || contentType.Contains("x-shockwave-flash")
  1705. || contentType.Contains("application/x-oar")
  1706. || contentType.Contains("application/vnd.ll.mesh")))
  1707. {
  1708. // Text
  1709. buffer = Encoding.UTF8.GetBytes(responseString);
  1710. }
  1711. else
  1712. {
  1713. // Binary!
  1714. buffer = Convert.FromBase64String(responseString);
  1715. }
  1716. response.SendChunked = false;
  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.SendChunked = false;
  1730. response.ContentLength64 = buffer.Length;
  1731. response.ContentEncoding = Encoding.UTF8;
  1732. return buffer;
  1733. }
  1734. public byte[] SendHTML500(OSHttpResponse response)
  1735. {
  1736. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1737. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1738. response.AddHeader("Content-type", "text/html");
  1739. string responseString = GetHTTP500();
  1740. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1741. response.SendChunked = false;
  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. }