BaseHttpServer.cs 88 KB

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