BaseHttpServer.cs 93 KB

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