BaseHttpServer.cs 92 KB

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