BaseHttpServer.cs 91 KB

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