BaseHttpServer.cs 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335
  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. }
  1100. else
  1101. {
  1102. xmlRpcResponse = new XmlRpcResponse();
  1103. // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
  1104. xmlRpcResponse.SetFault(
  1105. XmlRpcErrorCodes.SERVER_ERROR_METHOD,
  1106. String.Format("Requested method [{0}] not found", methodName));
  1107. }
  1108. response.ContentType = "text/xml";
  1109. using (MemoryStream outs = new MemoryStream())
  1110. using (XmlTextWriter writer = new XmlTextWriter(outs, UTF8NoBOM))
  1111. {
  1112. writer.Formatting = Formatting.None;
  1113. XmlRpcResponseSerializer.Singleton.Serialize(writer, xmlRpcResponse);
  1114. writer.Flush();
  1115. outs.Flush();
  1116. outs.Position = 0;
  1117. using (StreamReader sr = new StreamReader(outs))
  1118. {
  1119. responseString = sr.ReadToEnd();
  1120. }
  1121. }
  1122. }
  1123. else
  1124. {
  1125. //HandleLLSDRequests(request, response);
  1126. response.ContentType = "text/plain";
  1127. response.StatusCode = 404;
  1128. response.StatusDescription = "Not Found";
  1129. response.ProtocolVersion = "HTTP/1.0";
  1130. responseString = "Not found";
  1131. response.KeepAlive = false;
  1132. m_log.ErrorFormat(
  1133. "[BASE HTTP SERVER]: Handler not found for http request {0} {1}",
  1134. request.HttpMethod, request.Url.PathAndQuery);
  1135. }
  1136. }
  1137. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1138. response.ContentLength64 = buffer.Length;
  1139. response.ContentEncoding = Encoding.UTF8;
  1140. return buffer;
  1141. }
  1142. // JsonRpc (v2.0 only)
  1143. // Batch requests not yet supported
  1144. private byte[] HandleJsonRpcRequests(OSHttpRequest request, OSHttpResponse response)
  1145. {
  1146. Stream requestStream = request.InputStream;
  1147. JsonRpcResponse jsonRpcResponse = new JsonRpcResponse();
  1148. OSDMap jsonRpcRequest = null;
  1149. try
  1150. {
  1151. jsonRpcRequest = (OSDMap)OSDParser.DeserializeJson(requestStream);
  1152. }
  1153. catch (LitJson.JsonException e)
  1154. {
  1155. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1156. jsonRpcResponse.Error.Message = e.Message;
  1157. }
  1158. requestStream.Close();
  1159. if (jsonRpcRequest != null)
  1160. {
  1161. if (jsonRpcRequest.ContainsKey("jsonrpc") || jsonRpcRequest["jsonrpc"].AsString() == "2.0")
  1162. {
  1163. jsonRpcResponse.JsonRpc = "2.0";
  1164. // If we have no id, then it's a "notification"
  1165. if (jsonRpcRequest.ContainsKey("id"))
  1166. {
  1167. jsonRpcResponse.Id = jsonRpcRequest["id"].AsString();
  1168. }
  1169. string methodname = jsonRpcRequest["method"];
  1170. JsonRPCMethod method;
  1171. if (jsonRpcHandlers.ContainsKey(methodname))
  1172. {
  1173. lock(jsonRpcHandlers)
  1174. {
  1175. jsonRpcHandlers.TryGetValue(methodname, out method);
  1176. }
  1177. bool res = false;
  1178. try
  1179. {
  1180. res = method(jsonRpcRequest, ref jsonRpcResponse);
  1181. if(!res)
  1182. {
  1183. // The handler sent back an unspecified error
  1184. if(jsonRpcResponse.Error.Code == 0)
  1185. {
  1186. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1187. }
  1188. }
  1189. }
  1190. catch (Exception e)
  1191. {
  1192. string ErrorMessage = string.Format("[BASE HTTP SERVER]: Json-Rpc Handler Error method {0} - {1}", methodname, e.Message);
  1193. m_log.Error(ErrorMessage);
  1194. jsonRpcResponse.Error.Code = ErrorCode.InternalError;
  1195. jsonRpcResponse.Error.Message = ErrorMessage;
  1196. }
  1197. }
  1198. else // Error no hanlder defined for requested method
  1199. {
  1200. jsonRpcResponse.Error.Code = ErrorCode.InvalidRequest;
  1201. jsonRpcResponse.Error.Message = string.Format ("No handler defined for {0}", methodname);
  1202. }
  1203. }
  1204. else // not json-rpc 2.0 could be v1
  1205. {
  1206. jsonRpcResponse.Error.Code = ErrorCode.InvalidRequest;
  1207. jsonRpcResponse.Error.Message = "Must be valid json-rpc 2.0 see: http://www.jsonrpc.org/specification";
  1208. if (jsonRpcRequest.ContainsKey("id"))
  1209. jsonRpcResponse.Id = jsonRpcRequest["id"].AsString();
  1210. }
  1211. }
  1212. string responseData = string.Empty;
  1213. responseData = jsonRpcResponse.Serialize();
  1214. byte[] buffer = Encoding.UTF8.GetBytes(responseData);
  1215. return buffer;
  1216. }
  1217. private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response)
  1218. {
  1219. //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
  1220. bool notfound = false;
  1221. Stream requestStream = request.InputStream;
  1222. string requestBody;
  1223. Encoding encoding = Encoding.UTF8;
  1224. using(StreamReader reader = new StreamReader(requestStream, encoding))
  1225. requestBody= reader.ReadToEnd();
  1226. //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
  1227. OSD llsdRequest = null;
  1228. OSD llsdResponse = null;
  1229. bool LegacyLLSDLoginLibOMV = (requestBody.Contains("passwd") && requestBody.Contains("mac") && requestBody.Contains("viewer_digest"));
  1230. if (requestBody.Length == 0)
  1231. // Get Request
  1232. {
  1233. requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>";
  1234. }
  1235. try
  1236. {
  1237. llsdRequest = OSDParser.Deserialize(requestBody);
  1238. }
  1239. catch (Exception ex)
  1240. {
  1241. m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
  1242. }
  1243. if (llsdRequest != null)// && m_defaultLlsdHandler != null)
  1244. {
  1245. LLSDMethod llsdhandler = null;
  1246. if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV)
  1247. {
  1248. // we found a registered llsd handler to service this request
  1249. llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint.ToString());
  1250. }
  1251. else
  1252. {
  1253. // we didn't find a registered llsd handler to service this request
  1254. // check if we have a default llsd handler
  1255. if (m_defaultLlsdHandler != null)
  1256. {
  1257. // LibOMV path
  1258. llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
  1259. }
  1260. else
  1261. {
  1262. // Oops, no handler for this.. give em the failed message
  1263. notfound = true;
  1264. }
  1265. }
  1266. }
  1267. else
  1268. {
  1269. notfound = true;
  1270. }
  1271. if(notfound)
  1272. {
  1273. response.StatusCode = (int)HttpStatusCode.NotFound;
  1274. response.StatusDescription = "Not found";
  1275. return null;
  1276. }
  1277. byte[] buffer = new byte[0];
  1278. if (llsdResponse.ToString() == "shutdown404!")
  1279. {
  1280. response.ContentType = "text/plain";
  1281. response.StatusCode = 404;
  1282. response.StatusDescription = "Not Found";
  1283. response.ProtocolVersion = "HTTP/1.0";
  1284. buffer = Encoding.UTF8.GetBytes("Not found");
  1285. }
  1286. else
  1287. {
  1288. // Select an appropriate response format
  1289. buffer = BuildLLSDResponse(request, response, llsdResponse);
  1290. }
  1291. response.ContentLength64 = buffer.Length;
  1292. response.ContentEncoding = Encoding.UTF8;
  1293. return buffer;
  1294. }
  1295. private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
  1296. {
  1297. if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
  1298. {
  1299. foreach (string strAccept in request.AcceptTypes)
  1300. {
  1301. switch (strAccept)
  1302. {
  1303. case "application/llsd+xml":
  1304. case "application/xml":
  1305. case "text/xml":
  1306. response.ContentType = strAccept;
  1307. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1308. case "application/llsd+json":
  1309. case "application/json":
  1310. response.ContentType = strAccept;
  1311. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1312. }
  1313. }
  1314. }
  1315. if (!String.IsNullOrEmpty(request.ContentType))
  1316. {
  1317. switch (request.ContentType)
  1318. {
  1319. case "application/llsd+xml":
  1320. case "application/xml":
  1321. case "text/xml":
  1322. response.ContentType = request.ContentType;
  1323. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1324. case "application/llsd+json":
  1325. case "application/json":
  1326. response.ContentType = request.ContentType;
  1327. return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1328. }
  1329. }
  1330. // response.ContentType = "application/llsd+json";
  1331. // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
  1332. response.ContentType = "application/llsd+xml";
  1333. return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
  1334. }
  1335. /// <summary>
  1336. /// Checks if we have an Exact path in the LLSD handlers for the path provided
  1337. /// </summary>
  1338. /// <param name="path">URI of the request</param>
  1339. /// <returns>true if we have one, false if not</returns>
  1340. private bool DoWeHaveALLSDHandler(string path)
  1341. {
  1342. string[] pathbase = path.Split('/');
  1343. string searchquery = "/";
  1344. if (pathbase.Length < 1)
  1345. return false;
  1346. for (int i = 1; i < pathbase.Length; i++)
  1347. {
  1348. searchquery += pathbase[i];
  1349. if (pathbase.Length - 1 != i)
  1350. searchquery += "/";
  1351. }
  1352. string bestMatch = null;
  1353. lock (m_llsdHandlers)
  1354. {
  1355. foreach (string pattern in m_llsdHandlers.Keys)
  1356. {
  1357. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1358. bestMatch = pattern;
  1359. }
  1360. }
  1361. // extra kicker to remove the default XMLRPC login case.. just in case..
  1362. if (path != "/" && bestMatch == "/" && searchquery != "/")
  1363. return false;
  1364. if (path == "/")
  1365. return false;
  1366. if (String.IsNullOrEmpty(bestMatch))
  1367. {
  1368. return false;
  1369. }
  1370. else
  1371. {
  1372. return true;
  1373. }
  1374. }
  1375. /// <summary>
  1376. /// Checks if we have an Exact path in the HTTP handlers for the path provided
  1377. /// </summary>
  1378. /// <param name="path">URI of the request</param>
  1379. /// <returns>true if we have one, false if not</returns>
  1380. private bool DoWeHaveAHTTPHandler(string path)
  1381. {
  1382. string[] pathbase = path.Split('/');
  1383. string searchquery = "/";
  1384. if (pathbase.Length < 1)
  1385. return false;
  1386. for (int i = 1; i < pathbase.Length; i++)
  1387. {
  1388. searchquery += pathbase[i];
  1389. if (pathbase.Length - 1 != i)
  1390. searchquery += "/";
  1391. }
  1392. string bestMatch = null;
  1393. //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
  1394. lock (m_HTTPHandlers)
  1395. {
  1396. foreach (string pattern in m_HTTPHandlers.Keys)
  1397. {
  1398. if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
  1399. {
  1400. bestMatch = pattern;
  1401. }
  1402. }
  1403. // extra kicker to remove the default XMLRPC login case.. just in case..
  1404. if (path == "/")
  1405. return false;
  1406. if (String.IsNullOrEmpty(bestMatch))
  1407. {
  1408. return false;
  1409. }
  1410. else
  1411. {
  1412. return true;
  1413. }
  1414. }
  1415. }
  1416. private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
  1417. {
  1418. llsdHandler = null;
  1419. // Pull out the first part of the path
  1420. // splitting the path by '/' means we'll get the following return..
  1421. // {0}/{1}/{2}
  1422. // where {0} isn't something we really control 100%
  1423. string[] pathbase = path.Split('/');
  1424. string searchquery = "/";
  1425. if (pathbase.Length < 1)
  1426. return false;
  1427. for (int i=1; i<pathbase.Length; i++)
  1428. {
  1429. searchquery += pathbase[i];
  1430. if (pathbase.Length-1 != i)
  1431. searchquery += "/";
  1432. }
  1433. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1434. //
  1435. // [] = optional
  1436. // /resource/UUID/action[/action]
  1437. //
  1438. // now try to get the closest match to the reigstered path
  1439. // at least for OGP, registered path would probably only consist of the /resource/
  1440. string bestMatch = null;
  1441. lock (m_llsdHandlers)
  1442. {
  1443. foreach (string pattern in m_llsdHandlers.Keys)
  1444. {
  1445. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1446. {
  1447. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1448. {
  1449. // You have to specifically register for '/' and to get it, you must specificaly request it
  1450. //
  1451. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1452. bestMatch = pattern;
  1453. }
  1454. }
  1455. }
  1456. if (String.IsNullOrEmpty(bestMatch))
  1457. {
  1458. llsdHandler = null;
  1459. return false;
  1460. }
  1461. else
  1462. {
  1463. llsdHandler = m_llsdHandlers[bestMatch];
  1464. return true;
  1465. }
  1466. }
  1467. }
  1468. public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
  1469. {
  1470. // m_log.DebugFormat(
  1471. // "[BASE HTTP SERVER]: HandleHTTPRequest for request to {0}, method {1}",
  1472. // request.RawUrl, request.HttpMethod);
  1473. switch (request.HttpMethod)
  1474. {
  1475. case "OPTIONS":
  1476. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1477. return null;
  1478. default:
  1479. return HandleContentVerbs(request, response);
  1480. }
  1481. }
  1482. private byte[] HandleContentVerbs(OSHttpRequest request, OSHttpResponse response)
  1483. {
  1484. // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl);
  1485. // This is a test. There's a workable alternative.. as this way sucks.
  1486. // We'd like to put this into a text file parhaps that's easily editable.
  1487. //
  1488. // For this test to work, I used the following secondlife.exe parameters
  1489. // "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
  1490. //
  1491. // Even after all that, there's still an error, but it's a start.
  1492. //
  1493. // I depend on show_login_form being in the secondlife.exe parameters to figure out
  1494. // to display the form, or process it.
  1495. // a better way would be nifty.
  1496. byte[] buffer;
  1497. Stream requestStream = request.InputStream;
  1498. string requestBody;
  1499. Encoding encoding = Encoding.UTF8;
  1500. using(StreamReader reader = new StreamReader(requestStream, encoding))
  1501. requestBody = reader.ReadToEnd();
  1502. Hashtable keysvals = new Hashtable();
  1503. Hashtable headervals = new Hashtable();
  1504. Hashtable requestVars = new Hashtable();
  1505. string host = String.Empty;
  1506. string[] querystringkeys = request.QueryString.AllKeys;
  1507. string[] rHeaders = request.Headers.AllKeys;
  1508. keysvals.Add("body", requestBody);
  1509. keysvals.Add("uri", request.RawUrl);
  1510. keysvals.Add("content-type", request.ContentType);
  1511. keysvals.Add("http-method", request.HttpMethod);
  1512. foreach (string queryname in querystringkeys)
  1513. {
  1514. // m_log.DebugFormat(
  1515. // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
  1516. keysvals.Add(queryname, request.QueryString[queryname]);
  1517. requestVars.Add(queryname, keysvals[queryname]);
  1518. }
  1519. foreach (string headername in rHeaders)
  1520. {
  1521. // m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
  1522. headervals[headername] = request.Headers[headername];
  1523. }
  1524. if (headervals.Contains("Host"))
  1525. {
  1526. host = (string)headervals["Host"];
  1527. }
  1528. keysvals.Add("headers", headervals);
  1529. keysvals.Add("querystringkeys", querystringkeys);
  1530. keysvals.Add("requestvars", requestVars);
  1531. // keysvals.Add("form", request.Form);
  1532. if (keysvals.Contains("method"))
  1533. {
  1534. // m_log.Debug("[BASE HTTP SERVER]: Contains Method");
  1535. string method = (string) keysvals["method"];
  1536. // m_log.Debug("[BASE HTTP SERVER]: " + requestBody);
  1537. GenericHTTPMethod requestprocessor;
  1538. bool foundHandler = TryGetHTTPHandler(method, out requestprocessor);
  1539. if (foundHandler)
  1540. {
  1541. Hashtable responsedata1 = requestprocessor(keysvals);
  1542. buffer = DoHTTPGruntWork(responsedata1,response);
  1543. //SendHTML500(response);
  1544. }
  1545. else
  1546. {
  1547. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found");
  1548. buffer = SendHTML404(response, host);
  1549. }
  1550. }
  1551. else
  1552. {
  1553. GenericHTTPMethod requestprocessor;
  1554. bool foundHandler = TryGetHTTPHandlerPathBased(request.RawUrl, out requestprocessor);
  1555. if (foundHandler)
  1556. {
  1557. Hashtable responsedata2 = requestprocessor(keysvals);
  1558. buffer = DoHTTPGruntWork(responsedata2, response);
  1559. //SendHTML500(response);
  1560. }
  1561. else
  1562. {
  1563. // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found2");
  1564. buffer = SendHTML404(response, host);
  1565. }
  1566. }
  1567. return buffer;
  1568. }
  1569. private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
  1570. {
  1571. httpHandler = null;
  1572. // Pull out the first part of the path
  1573. // splitting the path by '/' means we'll get the following return..
  1574. // {0}/{1}/{2}
  1575. // where {0} isn't something we really control 100%
  1576. string[] pathbase = path.Split('/');
  1577. string searchquery = "/";
  1578. if (pathbase.Length < 1)
  1579. return false;
  1580. for (int i = 1; i < pathbase.Length; i++)
  1581. {
  1582. searchquery += pathbase[i];
  1583. if (pathbase.Length - 1 != i)
  1584. searchquery += "/";
  1585. }
  1586. // while the matching algorithm below doesn't require it, we're expecting a query in the form
  1587. //
  1588. // [] = optional
  1589. // /resource/UUID/action[/action]
  1590. //
  1591. // now try to get the closest match to the reigstered path
  1592. // at least for OGP, registered path would probably only consist of the /resource/
  1593. string bestMatch = null;
  1594. // m_log.DebugFormat(
  1595. // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
  1596. lock (m_HTTPHandlers)
  1597. {
  1598. foreach (string pattern in m_HTTPHandlers.Keys)
  1599. {
  1600. if (searchquery.ToLower().StartsWith(pattern.ToLower()))
  1601. {
  1602. if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
  1603. {
  1604. // You have to specifically register for '/' and to get it, you must specifically request it
  1605. if (pattern == "/" && searchquery == "/" || pattern != "/")
  1606. bestMatch = pattern;
  1607. }
  1608. }
  1609. }
  1610. if (String.IsNullOrEmpty(bestMatch))
  1611. {
  1612. httpHandler = null;
  1613. return false;
  1614. }
  1615. else
  1616. {
  1617. if (bestMatch == "/" && searchquery != "/")
  1618. return false;
  1619. httpHandler = m_HTTPHandlers[bestMatch];
  1620. return true;
  1621. }
  1622. }
  1623. }
  1624. internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
  1625. {
  1626. int responsecode;
  1627. string responseString = String.Empty;
  1628. byte[] responseData = null;
  1629. string contentType;
  1630. if (responsedata == null)
  1631. {
  1632. responsecode = 500;
  1633. responseString = "No response could be obtained";
  1634. contentType = "text/plain";
  1635. responsedata = new Hashtable();
  1636. }
  1637. else
  1638. {
  1639. try
  1640. {
  1641. //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
  1642. responsecode = (int)responsedata["int_response_code"];
  1643. if (responsedata["bin_response_data"] != null)
  1644. responseData = (byte[])responsedata["bin_response_data"];
  1645. else
  1646. responseString = (string)responsedata["str_response_string"];
  1647. contentType = (string)responsedata["content_type"];
  1648. if (responseString == null)
  1649. responseString = String.Empty;
  1650. }
  1651. catch
  1652. {
  1653. responsecode = 500;
  1654. responseString = "No response could be obtained";
  1655. contentType = "text/plain";
  1656. responsedata = new Hashtable();
  1657. }
  1658. }
  1659. if (responsedata.ContainsKey("error_status_text"))
  1660. {
  1661. response.StatusDescription = (string)responsedata["error_status_text"];
  1662. }
  1663. if (responsedata.ContainsKey("http_protocol_version"))
  1664. {
  1665. response.ProtocolVersion = (string)responsedata["http_protocol_version"];
  1666. }
  1667. if (responsedata.ContainsKey("keepalive"))
  1668. {
  1669. bool keepalive = (bool)responsedata["keepalive"];
  1670. response.KeepAlive = keepalive;
  1671. }
  1672. // Cross-Origin Resource Sharing with simple requests
  1673. if (responsedata.ContainsKey("access_control_allow_origin"))
  1674. response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
  1675. //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
  1676. //and should check for NullReferenceExceptions
  1677. if (string.IsNullOrEmpty(contentType))
  1678. {
  1679. contentType = "text/html";
  1680. }
  1681. // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
  1682. response.StatusCode = responsecode;
  1683. if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently)
  1684. {
  1685. response.RedirectLocation = (string)responsedata["str_redirect_location"];
  1686. response.StatusCode = responsecode;
  1687. }
  1688. response.AddHeader("Content-Type", contentType);
  1689. if (responsedata.ContainsKey("headers"))
  1690. {
  1691. Hashtable headerdata = (Hashtable)responsedata["headers"];
  1692. foreach (string header in headerdata.Keys)
  1693. response.AddHeader(header, headerdata[header].ToString());
  1694. }
  1695. byte[] buffer;
  1696. if (responseData != null)
  1697. {
  1698. buffer = responseData;
  1699. }
  1700. else
  1701. {
  1702. if (!(contentType.Contains("image")
  1703. || contentType.Contains("x-shockwave-flash")
  1704. || contentType.Contains("application/x-oar")
  1705. || contentType.Contains("application/vnd.ll.mesh")))
  1706. {
  1707. // Text
  1708. buffer = Encoding.UTF8.GetBytes(responseString);
  1709. }
  1710. else
  1711. {
  1712. // Binary!
  1713. buffer = Convert.FromBase64String(responseString);
  1714. }
  1715. response.ContentLength64 = buffer.Length;
  1716. response.ContentEncoding = Encoding.UTF8;
  1717. }
  1718. return buffer;
  1719. }
  1720. public byte[] SendHTML404(OSHttpResponse response, string host)
  1721. {
  1722. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1723. response.StatusCode = 404;
  1724. response.AddHeader("Content-type", "text/html");
  1725. string responseString = GetHTTP404(host);
  1726. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1727. response.ContentLength64 = buffer.Length;
  1728. response.ContentEncoding = Encoding.UTF8;
  1729. return buffer;
  1730. }
  1731. public byte[] SendHTML500(OSHttpResponse response)
  1732. {
  1733. // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s
  1734. response.StatusCode = (int)OSHttpStatusCode.SuccessOk;
  1735. response.AddHeader("Content-type", "text/html");
  1736. string responseString = GetHTTP500();
  1737. byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  1738. response.ContentLength64 = buffer.Length;
  1739. response.ContentEncoding = Encoding.UTF8;
  1740. return buffer;
  1741. }
  1742. public void Start()
  1743. {
  1744. Start(true, true);
  1745. }
  1746. /// <summary>
  1747. /// Start the http server
  1748. /// </summary>
  1749. /// <param name='processPollRequestsAsync'>
  1750. /// If true then poll responses are performed asynchronsly.
  1751. /// Option exists to allow regression tests to perform processing synchronously.
  1752. /// </param>
  1753. public void Start(bool performPollResponsesAsync, bool runPool)
  1754. {
  1755. m_log.InfoFormat(
  1756. "[BASE HTTP SERVER]: Starting {0} server on port {1}", UseSSL ? "HTTPS" : "HTTP", Port);
  1757. try
  1758. {
  1759. //m_httpListener = new HttpListener();
  1760. NotSocketErrors = 0;
  1761. if (!m_ssl)
  1762. {
  1763. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1764. //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/");
  1765. m_httpListener2 = CoolHTTPListener.Create(m_listenIPAddress, (int)m_port);
  1766. m_httpListener2.ExceptionThrown += httpServerException;
  1767. m_httpListener2.LogWriter = httpserverlog;
  1768. // Uncomment this line in addition to those in HttpServerLogWriter
  1769. // if you want more detailed trace information from the HttpServer
  1770. //m_httpListener2.UseTraceLogs = true;
  1771. //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
  1772. }
  1773. else
  1774. {
  1775. //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
  1776. //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
  1777. m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert);
  1778. if(m_certificateValidationCallback != null)
  1779. m_httpListener2.CertificateValidationCallback = m_certificateValidationCallback;
  1780. m_httpListener2.ExceptionThrown += httpServerException;
  1781. m_httpListener2.LogWriter = httpserverlog;
  1782. }
  1783. m_httpListener2.RequestReceived += OnRequest;
  1784. //m_httpListener.Start();
  1785. m_httpListener2.Start(64);
  1786. lock(m_generalLock)
  1787. {
  1788. if (runPool)
  1789. {
  1790. if(m_pollServiceManager == null)
  1791. m_pollServiceManager = new PollServiceRequestManager(performPollResponsesAsync, 2, 25000);
  1792. m_pollServiceManager.Start();
  1793. }
  1794. }
  1795. HTTPDRunning = true;
  1796. //HttpListenerContext context;
  1797. //while (true)
  1798. //{
  1799. // context = m_httpListener.GetContext();
  1800. // ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(HandleRequest), context);
  1801. // }
  1802. }
  1803. catch (Exception e)
  1804. {
  1805. m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
  1806. m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + "?");
  1807. // We want this exception to halt the entire server since in current configurations we aren't too
  1808. // useful without inbound HTTP.
  1809. throw e;
  1810. }
  1811. m_requestsProcessedStat
  1812. = new Stat(
  1813. "HTTPRequestsServed",
  1814. "Number of inbound HTTP requests processed",
  1815. "",
  1816. "requests",
  1817. "httpserver",
  1818. Port.ToString(),
  1819. StatType.Pull,
  1820. MeasuresOfInterest.AverageChangeOverTime,
  1821. stat => stat.Value = RequestNumber,
  1822. StatVerbosity.Debug);
  1823. StatsManager.RegisterStat(m_requestsProcessedStat);
  1824. }
  1825. public void httpServerDisconnectMonitor(IHttpClientContext source, SocketError err)
  1826. {
  1827. switch (err)
  1828. {
  1829. case SocketError.NotSocket:
  1830. NotSocketErrors++;
  1831. break;
  1832. }
  1833. }
  1834. public void httpServerException(object source, Exception exception)
  1835. {
  1836. if (source.ToString() == "HttpServer.HttpListener" && exception.ToString().StartsWith("Mono.Security.Protocol.Tls.TlsException"))
  1837. return;
  1838. m_log.ErrorFormat("[BASE HTTP SERVER]: {0} had an exception {1}", source.ToString(), exception.ToString());
  1839. }
  1840. public void Stop(bool stopPool = false)
  1841. {
  1842. HTTPDRunning = false;
  1843. StatsManager.DeregisterStat(m_requestsProcessedStat);
  1844. try
  1845. {
  1846. lock(m_generalLock)
  1847. {
  1848. if (stopPool && m_pollServiceManager != null)
  1849. m_pollServiceManager.Stop();
  1850. }
  1851. m_httpListener2.ExceptionThrown -= httpServerException;
  1852. //m_httpListener2.DisconnectHandler = null;
  1853. m_httpListener2.LogWriter = null;
  1854. m_httpListener2.RequestReceived -= OnRequest;
  1855. m_httpListener2.Stop();
  1856. }
  1857. catch (NullReferenceException)
  1858. {
  1859. m_log.Warn("[BASE HTTP SERVER]: Null Reference when stopping HttpServer.");
  1860. }
  1861. }
  1862. public void RemoveStreamHandler(string httpMethod, string path)
  1863. {
  1864. string handlerKey = GetHandlerKey(httpMethod, path);
  1865. //m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey);
  1866. lock (m_streamHandlers)
  1867. m_streamHandlers.Remove(handlerKey);
  1868. }
  1869. public void RemoveHTTPHandler(string httpMethod, string path)
  1870. {
  1871. if (path == null) return; // Caps module isn't loaded, tries to remove handler where path = null
  1872. lock (m_HTTPHandlers)
  1873. {
  1874. if (httpMethod != null && httpMethod.Length == 0)
  1875. {
  1876. m_HTTPHandlers.Remove(path);
  1877. return;
  1878. }
  1879. m_HTTPHandlers.Remove(GetHandlerKey(httpMethod, path));
  1880. }
  1881. }
  1882. public void RemovePollServiceHTTPHandler(string httpMethod, string path)
  1883. {
  1884. lock (m_pollHandlers)
  1885. m_pollHandlers.Remove(path);
  1886. }
  1887. // public bool RemoveAgentHandler(string agent, IHttpAgentHandler handler)
  1888. // {
  1889. // lock (m_agentHandlers)
  1890. // {
  1891. // IHttpAgentHandler foundHandler;
  1892. //
  1893. // if (m_agentHandlers.TryGetValue(agent, out foundHandler) && foundHandler == handler)
  1894. // {
  1895. // m_agentHandlers.Remove(agent);
  1896. // return true;
  1897. // }
  1898. // }
  1899. //
  1900. // return false;
  1901. // }
  1902. public void RemoveXmlRPCHandler(string method)
  1903. {
  1904. lock (m_rpcHandlers)
  1905. m_rpcHandlers.Remove(method);
  1906. }
  1907. public void RemoveJsonRPCHandler(string method)
  1908. {
  1909. lock(jsonRpcHandlers)
  1910. jsonRpcHandlers.Remove(method);
  1911. }
  1912. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  1913. {
  1914. lock (m_llsdHandlers)
  1915. {
  1916. LLSDMethod foundHandler;
  1917. if (m_llsdHandlers.TryGetValue(path, out foundHandler) && foundHandler == handler)
  1918. {
  1919. m_llsdHandlers.Remove(path);
  1920. return true;
  1921. }
  1922. }
  1923. return false;
  1924. }
  1925. public string GetHTTP404(string host)
  1926. {
  1927. string file = Path.Combine(".", "http_404.html");
  1928. if (!File.Exists(file))
  1929. return getDefaultHTTP404(host);
  1930. StreamReader sr = File.OpenText(file);
  1931. string result = sr.ReadToEnd();
  1932. sr.Close();
  1933. return result;
  1934. }
  1935. public string GetHTTP500()
  1936. {
  1937. string file = Path.Combine(".", "http_500.html");
  1938. if (!File.Exists(file))
  1939. return getDefaultHTTP500();
  1940. string result;
  1941. using(StreamReader sr = File.OpenText(file))
  1942. result = sr.ReadToEnd();
  1943. return result;
  1944. }
  1945. // Fallback HTTP responses in case the HTTP error response files don't exist
  1946. private static string getDefaultHTTP404(string host)
  1947. {
  1948. 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>";
  1949. }
  1950. private static string getDefaultHTTP500()
  1951. {
  1952. 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>";
  1953. }
  1954. }
  1955. public class HttpServerContextObj
  1956. {
  1957. public IHttpClientContext context = null;
  1958. public IHttpRequest req = null;
  1959. public OSHttpRequest oreq = null;
  1960. public OSHttpResponse oresp = null;
  1961. public HttpServerContextObj(IHttpClientContext contxt, IHttpRequest reqs)
  1962. {
  1963. context = contxt;
  1964. req = reqs;
  1965. }
  1966. public HttpServerContextObj(OSHttpRequest osreq, OSHttpResponse osresp)
  1967. {
  1968. oreq = osreq;
  1969. oresp = osresp;
  1970. }
  1971. }
  1972. /// <summary>
  1973. /// Relays HttpServer log messages to our own logging mechanism.
  1974. /// </summary>
  1975. /// To use this you must uncomment the switch section
  1976. ///
  1977. /// You may also be able to get additional trace information from HttpServer if you uncomment the UseTraceLogs
  1978. /// property in StartHttp() for the HttpListener
  1979. public class HttpServerLogWriter : ILogWriter
  1980. {
  1981. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1982. public void Write(object source, LogPrio priority, string message)
  1983. {
  1984. /*
  1985. switch (priority)
  1986. {
  1987. case LogPrio.Trace:
  1988. m_log.DebugFormat("[{0}]: {1}", source, message);
  1989. break;
  1990. case LogPrio.Debug:
  1991. m_log.DebugFormat("[{0}]: {1}", source, message);
  1992. break;
  1993. case LogPrio.Error:
  1994. m_log.ErrorFormat("[{0}]: {1}", source, message);
  1995. break;
  1996. case LogPrio.Info:
  1997. m_log.InfoFormat("[{0}]: {1}", source, message);
  1998. break;
  1999. case LogPrio.Warning:
  2000. m_log.WarnFormat("[{0}]: {1}", source, message);
  2001. break;
  2002. case LogPrio.Fatal:
  2003. m_log.ErrorFormat("[{0}]: FATAL! - {1}", source, message);
  2004. break;
  2005. default:
  2006. break;
  2007. }
  2008. */
  2009. return;
  2010. }
  2011. }
  2012. }