UrlModule.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using log4net;
  37. using Mono.Addins;
  38. using Nini.Config;
  39. using OpenMetaverse;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Servers;
  42. using OpenSim.Framework.Servers.HttpServer;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
  46. {
  47. public class UrlData
  48. {
  49. public UUID hostID;
  50. public UUID groupID;
  51. public UUID itemID;
  52. public IScriptModule engine;
  53. public string url;
  54. public UUID urlcode;
  55. public Dictionary<UUID, RequestData> requests;
  56. public bool isSsl;
  57. public Scene scene;
  58. public bool allowXss;
  59. }
  60. public class RequestData
  61. {
  62. public UUID requestID;
  63. public Dictionary<string, string> headers;
  64. public string body;
  65. public int responseCode;
  66. public string responseBody;
  67. public string responseType = "text/plain";
  68. //public ManualResetEvent ev;
  69. public bool requestDone;
  70. public int startTime;
  71. public bool responseSent;
  72. public string uri;
  73. public UUID hostID;
  74. public Scene scene;
  75. }
  76. /// <summary>
  77. /// This module provides external URLs for in-world scripts.
  78. /// </summary>
  79. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UrlModule")]
  80. public class UrlModule : ISharedRegionModule, IUrlModule
  81. {
  82. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  83. protected readonly Dictionary<UUID, UrlData> m_RequestMap = new();
  84. protected readonly Dictionary<string, UrlData> m_UrlMap = new();
  85. protected readonly Dictionary<UUID, int> m_countsPerSOG = new();
  86. protected bool m_enabled = false;
  87. protected string m_ErrorStr;
  88. protected uint m_HttpsPort = 0;
  89. protected uint m_HttpPort = 0;
  90. protected IHttpServer m_HttpServer = null;
  91. protected IHttpServer m_HttpsServer = null;
  92. private string m_lsl_shard = "OpenSim";
  93. private string m_lsl_user_agent = string.Empty;
  94. public string ExternalHostNameForLSL { get; protected set; }
  95. /// <summary>
  96. /// The default maximum number of urls
  97. /// </summary>
  98. public const int DefaultTotalUrls = 15000;
  99. /// <summary>
  100. /// Maximum number of external urls that can be set up by this module.
  101. /// </summary>
  102. public int TotalUrls { get; set; }
  103. public Type ReplaceableInterface
  104. {
  105. get { return typeof(IUrlModule); }
  106. }
  107. public string Name
  108. {
  109. get { return "UrlModule"; }
  110. }
  111. public void Initialise(IConfigSource config)
  112. {
  113. IConfig networkConfig = config.Configs["Network"];
  114. m_enabled = false;
  115. if (networkConfig != null)
  116. {
  117. m_lsl_shard = networkConfig.GetString("shard", m_lsl_shard);
  118. m_lsl_user_agent = networkConfig.GetString("user_agent", m_lsl_user_agent);
  119. ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", null);
  120. bool ssl_enabled = config.Configs["Network"].GetBoolean("https_listener", false);
  121. m_HttpPort = (uint)config.Configs["Network"].GetInt("http_listener_port", 9000);
  122. if (ssl_enabled)
  123. m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort);
  124. }
  125. else
  126. {
  127. m_ErrorStr = "[Network] configuration missing, HTTP listener for LSL disabled";
  128. m_log.Warn("[URL MODULE]: " + m_ErrorStr);
  129. return;
  130. }
  131. if (string.IsNullOrWhiteSpace(ExternalHostNameForLSL))
  132. {
  133. m_ErrorStr = "ExternalHostNameForLSL not defined in configuration, HTTP listener for LSL disabled";
  134. m_log.Warn("[URL MODULE]: " + m_ErrorStr);
  135. return;
  136. }
  137. IPAddress ia = Util.GetHostFromDNS(ExternalHostNameForLSL);
  138. if (ia == null)
  139. {
  140. m_ErrorStr = "Could not resolve ExternalHostNameForLSL, HTTP listener for LSL disabled";
  141. m_log.Warn("[URL MODULE]: " + m_ErrorStr);
  142. return;
  143. }
  144. m_enabled = true;
  145. m_ErrorStr = String.Empty;
  146. IConfig llFunctionsConfig = config.Configs["LL-Functions"];
  147. if (llFunctionsConfig != null)
  148. TotalUrls = llFunctionsConfig.GetInt("max_external_urls_per_simulator", DefaultTotalUrls);
  149. else
  150. TotalUrls = DefaultTotalUrls;
  151. }
  152. public void PostInitialise()
  153. {
  154. }
  155. public void AddRegion(Scene scene)
  156. {
  157. if (m_enabled && m_HttpServer == null)
  158. {
  159. // There can only be one
  160. //
  161. m_HttpServer = MainServer.GetHttpServer(m_HttpPort);
  162. //
  163. // We can use the https if it is enabled
  164. if (m_HttpsPort > 0)
  165. {
  166. m_HttpsServer = MainServer.GetHttpServer(m_HttpsPort);
  167. }
  168. }
  169. scene.RegisterModuleInterface<IUrlModule>(this);
  170. scene.EventManager.OnScriptReset += OnScriptReset;
  171. }
  172. public void RegionLoaded(Scene scene)
  173. {
  174. IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>();
  175. foreach (IScriptModule scriptModule in scriptModules)
  176. {
  177. scriptModule.OnScriptRemoved += ScriptRemoved;
  178. scriptModule.OnObjectRemoved += ObjectRemoved;
  179. }
  180. }
  181. public void RemoveRegion(Scene scene)
  182. {
  183. // Drop references to that scene
  184. foreach (KeyValuePair<string, UrlData> kvp in m_UrlMap)
  185. {
  186. if (kvp.Value.scene == scene)
  187. kvp.Value.scene = null;
  188. }
  189. foreach (KeyValuePair<UUID, UrlData> kvp in m_RequestMap)
  190. {
  191. if (kvp.Value.scene == scene)
  192. kvp.Value.scene = null;
  193. }
  194. }
  195. public void Close()
  196. {
  197. }
  198. public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID, Hashtable options)
  199. {
  200. UUID urlcode = UUID.Random();
  201. if(!m_enabled)
  202. {
  203. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", m_ErrorStr });
  204. return urlcode;
  205. }
  206. lock (m_UrlMap)
  207. {
  208. if (m_UrlMap.Count >= TotalUrls)
  209. {
  210. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED",
  211. "Too many URLs already open" });
  212. return urlcode;
  213. }
  214. string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString();
  215. UUID groupID = host.ParentGroup.UUID;
  216. UrlData urlData = new()
  217. {
  218. hostID = host.UUID,
  219. groupID = groupID,
  220. itemID = itemID,
  221. engine = engine,
  222. url = url,
  223. urlcode = urlcode,
  224. isSsl = false,
  225. requests = new Dictionary<UUID, RequestData>(),
  226. scene = host.ParentGroup.Scene
  227. };
  228. if (options != null && options["allowXss"] != null)
  229. urlData.allowXss = true;
  230. else
  231. urlData.allowXss = false;
  232. m_UrlMap[url] = urlData;
  233. if (m_countsPerSOG.TryGetValue(groupID, out int urlcount))
  234. m_countsPerSOG[groupID] = ++urlcount;
  235. else
  236. m_countsPerSOG[groupID] = 1;
  237. string uri = "/lslhttp/" + urlcode.ToString();
  238. PollServiceEventArgs args
  239. = new(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, Drop, urlcode, 25000);
  240. m_HttpServer.AddPollServiceHTTPHandlerVarPath(args);
  241. //m_log.DebugFormat(
  242. // "[URL MODULE]: Set up incoming request url {0} for {1} in {2} {3}",
  243. // uri, itemID, host.Name, host.LocalId);
  244. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url + "/"});
  245. }
  246. return urlcode;
  247. }
  248. public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID, Hashtable options)
  249. {
  250. UUID urlcode = UUID.Random();
  251. if(!m_enabled)
  252. {
  253. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", m_ErrorStr });
  254. return urlcode;
  255. }
  256. if (m_HttpsServer == null)
  257. {
  258. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
  259. return urlcode;
  260. }
  261. lock (m_UrlMap)
  262. {
  263. if (m_UrlMap.Count >= TotalUrls)
  264. {
  265. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED",
  266. "Too many URLs already open" });
  267. return urlcode;
  268. }
  269. string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString();
  270. UUID groupID = host.ParentGroup.UUID;
  271. UrlData urlData = new()
  272. {
  273. hostID = host.UUID,
  274. groupID = groupID,
  275. itemID = itemID,
  276. engine = engine,
  277. url = url,
  278. urlcode = urlcode,
  279. isSsl = true,
  280. requests = new Dictionary<UUID, RequestData>(),
  281. scene = host.ParentGroup.Scene
  282. };
  283. if (options != null && options["allowXss"] != null)
  284. urlData.allowXss = true;
  285. else
  286. urlData.allowXss = false;
  287. m_UrlMap[url] = urlData;
  288. if (m_countsPerSOG.TryGetValue(groupID, out int urlcount))
  289. m_countsPerSOG[groupID] = ++urlcount;
  290. else
  291. m_countsPerSOG[groupID] = 1;
  292. string uri = "/lslhttps/" + urlcode.ToString();
  293. PollServiceEventArgs args = new(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, Drop, urlcode, 25000);
  294. m_HttpsServer.AddPollServiceHTTPHandlerVarPath(args);
  295. //m_log.DebugFormat(
  296. // "[URL MODULE]: Set up incoming secure request url {0} for {1} in {2} {3}",
  297. // uri, itemID, host.Name, host.LocalId);
  298. // keep ending / because legacy
  299. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url + "/"});
  300. }
  301. return urlcode;
  302. }
  303. public void ReleaseURL(string url)
  304. {
  305. lock (m_UrlMap)
  306. {
  307. url = url.TrimEnd(new char[] { '/' });
  308. if (!m_UrlMap.TryGetValue(url, out UrlData data))
  309. {
  310. return;
  311. }
  312. lock (m_RequestMap)
  313. {
  314. foreach (UUID req in data.requests.Keys)
  315. m_RequestMap.Remove(req);
  316. }
  317. // m_log.DebugFormat(
  318. // "[URL MODULE]: Releasing url {0} for {1} in {2}",
  319. // url, data.itemID, data.hostID);
  320. RemoveUrl(data);
  321. m_UrlMap.Remove(url);
  322. }
  323. }
  324. public void HttpContentType(UUID request, string type)
  325. {
  326. lock (m_UrlMap)
  327. {
  328. if (m_RequestMap.TryGetValue(request, out UrlData urlData) && urlData != null)
  329. {
  330. urlData.requests[request].responseType = type;
  331. }
  332. else
  333. {
  334. m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString());
  335. }
  336. }
  337. }
  338. public void HttpResponse(UUID request, int status, string body)
  339. {
  340. lock (m_RequestMap)
  341. {
  342. if (m_RequestMap.TryGetValue(request, out UrlData urlData) && urlData != null)
  343. {
  344. lock (urlData.requests)
  345. {
  346. if (urlData.requests.TryGetValue(request, out RequestData rd) && rd != null)
  347. {
  348. if (!rd.responseSent)
  349. {
  350. string responseBody = body;
  351. if (rd.responseType.Equals("text/plain"))
  352. {
  353. if (rd.headers.TryGetValue("user-agent", out string value))
  354. {
  355. if (value != null && value.Contains("MSIE", StringComparison.InvariantCultureIgnoreCase))
  356. {
  357. // wrap the html escaped response if the target client is IE
  358. // It ignores "text/plain" if the body is html
  359. responseBody = "<html>" + System.Web.HttpUtility.HtmlEncode(body) + "</html>";
  360. }
  361. }
  362. }
  363. rd.responseCode = status;
  364. rd.responseBody = responseBody;
  365. //urlData.requests[request].ev.Set();
  366. rd.requestDone = true;
  367. rd.responseSent = true;
  368. }
  369. }
  370. }
  371. }
  372. else
  373. {
  374. m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString());
  375. }
  376. }
  377. }
  378. public string GetHttpHeader(UUID requestId, string header)
  379. {
  380. lock (m_RequestMap)
  381. {
  382. if (m_RequestMap.TryGetValue(requestId, out UrlData urlData) && urlData != null)
  383. {
  384. if (urlData.requests[requestId].headers.TryGetValue(header.ToLowerInvariant(), out string value))
  385. return value;
  386. }
  387. else
  388. {
  389. m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId);
  390. }
  391. }
  392. return string.Empty;
  393. }
  394. public int GetFreeUrls()
  395. {
  396. lock (m_UrlMap)
  397. return TotalUrls - m_UrlMap.Count;
  398. }
  399. public void ScriptRemoved(UUID itemID)
  400. {
  401. // m_log.DebugFormat("[URL MODULE]: Removing script {0}", itemID);
  402. lock (m_UrlMap)
  403. {
  404. List<string> removeURLs = new();
  405. foreach (KeyValuePair<string, UrlData> url in m_UrlMap)
  406. {
  407. if (url.Value.itemID == itemID)
  408. {
  409. RemoveUrl(url.Value);
  410. removeURLs.Add(url.Key);
  411. lock (m_RequestMap)
  412. {
  413. foreach (UUID req in url.Value.requests.Keys)
  414. m_RequestMap.Remove(req);
  415. }
  416. }
  417. }
  418. foreach (string urlname in removeURLs)
  419. m_UrlMap.Remove(urlname);
  420. }
  421. }
  422. public void ObjectRemoved(UUID objectID)
  423. {
  424. lock (m_UrlMap)
  425. {
  426. List<string> removeURLs = new();
  427. foreach (KeyValuePair<string, UrlData> url in m_UrlMap)
  428. {
  429. if (url.Value.hostID == objectID)
  430. {
  431. RemoveUrl(url.Value);
  432. removeURLs.Add(url.Key);
  433. lock (m_RequestMap)
  434. {
  435. foreach (UUID req in url.Value.requests.Keys)
  436. m_RequestMap.Remove(req);
  437. }
  438. }
  439. }
  440. foreach (string urlname in removeURLs)
  441. m_UrlMap.Remove(urlname);
  442. }
  443. }
  444. protected void RemoveUrl(UrlData data)
  445. {
  446. if (data.isSsl)
  447. m_HttpsServer.RemovePollServiceHTTPHandler("", "/lslhttps/"+data.urlcode.ToString());
  448. else
  449. m_HttpServer.RemovePollServiceHTTPHandler("", "/lslhttp/"+data.urlcode.ToString());
  450. if(m_countsPerSOG.TryGetValue(data.groupID, out int count))
  451. {
  452. --count;
  453. if(count <= 0)
  454. m_countsPerSOG.Remove(data.groupID);
  455. else
  456. m_countsPerSOG[data.groupID] = count;
  457. }
  458. }
  459. protected Hashtable NoEvents(UUID requestID, UUID sessionID)
  460. {
  461. UrlData url;
  462. int startTime = 0;
  463. lock (m_RequestMap)
  464. {
  465. if (!m_RequestMap.TryGetValue(requestID, out url))
  466. return new Hashtable();
  467. startTime = url.requests[requestID].startTime;
  468. }
  469. if (System.Environment.TickCount - startTime < 25000)
  470. return new Hashtable();
  471. //remove from map
  472. lock (url.requests)
  473. {
  474. url.requests.Remove(requestID);
  475. }
  476. lock (m_RequestMap)
  477. {
  478. m_RequestMap.Remove(requestID);
  479. }
  480. return new Hashtable()
  481. {
  482. ["int_response_code"] = 500,
  483. ["str_response_string"] = "Script timeout",
  484. ["content_type"] = "text/plain",
  485. ["keepalive"] = false
  486. };
  487. }
  488. protected bool HasEvents(UUID requestID, UUID sessionID)
  489. {
  490. UrlData url;
  491. lock (m_RequestMap)
  492. {
  493. if (!m_RequestMap.TryGetValue(requestID, out url))
  494. return false;
  495. }
  496. lock (url.requests)
  497. {
  498. if (!url.requests.TryGetValue(requestID, out RequestData rd) || rd == null)
  499. return false;
  500. if (System.Environment.TickCount - rd.startTime > 25000)
  501. return true;
  502. return rd.requestDone;
  503. }
  504. }
  505. protected void Drop(UUID requestID, UUID _)
  506. {
  507. UrlData url = null;
  508. lock (m_RequestMap)
  509. {
  510. if (m_RequestMap.TryGetValue(requestID, out url))
  511. {
  512. m_RequestMap.Remove(requestID);
  513. if(url != null)
  514. {
  515. lock (url.requests)
  516. url.requests.Remove(requestID);
  517. }
  518. }
  519. }
  520. }
  521. protected Hashtable GetEvents(UUID requestID, UUID sessionID)
  522. {
  523. UrlData url = null;
  524. lock (m_RequestMap)
  525. {
  526. if (!m_RequestMap.TryGetValue(requestID, out url))
  527. return new Hashtable();
  528. }
  529. RequestData requestData = null;
  530. bool timeout = false;
  531. lock (url.requests)
  532. {
  533. requestData = url.requests[requestID];
  534. if (requestData == null)
  535. return new Hashtable();
  536. timeout = System.Environment.TickCount - requestData.startTime > 25000;
  537. if (!requestData.requestDone && !timeout)
  538. return new Hashtable();
  539. url.requests.Remove(requestID);
  540. lock (m_RequestMap)
  541. {
  542. m_RequestMap.Remove(requestID);
  543. }
  544. }
  545. if (timeout)
  546. {
  547. return new Hashtable()
  548. {
  549. ["int_response_code"] = 500,
  550. ["str_response_string"] = "Script timeout",
  551. ["content_type"] = "text/plain",
  552. ["keepalive"] = false
  553. };
  554. }
  555. Hashtable headers = new();
  556. if(url.scene is not null)
  557. {
  558. SceneObjectPart sop = url.scene.GetSceneObjectPart(url.hostID);
  559. if(sop != null)
  560. {
  561. RegionInfo ri = url.scene.RegionInfo;
  562. Vector3 position = sop.AbsolutePosition;
  563. Vector3 velocity = sop.Velocity;
  564. Quaternion rotation = sop.GetWorldRotation();
  565. headers["X-SecondLife-Object-Name"] = sop.Name;
  566. headers["X-SecondLife-Object-Key"] = sop.UUID.ToString();
  567. headers["X-SecondLife-Region"] = string.Format("{0} ({1}, {2})", ri.RegionName, ri.WorldLocX, ri.WorldLocY);
  568. headers["X-SecondLife-Local-Position"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", position.X, position.Y, position.Z);
  569. headers["X-SecondLife-Local-Velocity"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", velocity.X, velocity.Y, velocity.Z);
  570. headers["X-SecondLife-Local-Rotation"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000}, {3:0.000000})", rotation.X, rotation.Y, rotation.Z, rotation.W);
  571. //headers["X-SecondLife-Owner-Name"] = ownerName;
  572. headers["X-SecondLife-Owner-Key"] = sop.OwnerID.ToString();
  573. }
  574. }
  575. if (!string.IsNullOrWhiteSpace(m_lsl_shard))
  576. headers["X-SecondLife-Shard"] = m_lsl_shard;
  577. if (!string.IsNullOrWhiteSpace(m_lsl_user_agent))
  578. headers["User-Agent"] = m_lsl_user_agent;
  579. if (url.isSsl)
  580. headers.Add("Accept-CH","UA");
  581. Hashtable response = new()
  582. {
  583. ["int_response_code"] = requestData.responseCode,
  584. ["str_response_string"] = requestData.responseBody,
  585. ["content_type"] = requestData.responseType,
  586. ["headers"] = headers,
  587. ["keepalive"] = false
  588. };
  589. if (url.allowXss)
  590. response["access_control_allow_origin"] = "*";
  591. return response;
  592. }
  593. private OSHttpResponse errorResponse(OSHttpRequest request, int error)
  594. {
  595. OSHttpResponse resp = new(request)
  596. {
  597. StatusCode = error
  598. };
  599. return resp;
  600. }
  601. public OSHttpResponse HttpRequestHandler(UUID requestID, OSHttpRequest request)
  602. {
  603. lock (request)
  604. {
  605. string uri = request.RawUrl;
  606. if(uri.Length < 45)
  607. {
  608. request.InputStream.Dispose();
  609. return errorResponse(request, (int)HttpStatusCode.BadRequest);
  610. }
  611. try
  612. {
  613. //string uri_full = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/";
  614. string uri_tmp;
  615. string pathInfo;
  616. int pos = uri.IndexOf('/', 45); // /lslhttp/uuid/ <-
  617. if (pos >= 45)
  618. {
  619. uri_tmp = uri[..pos];
  620. pathInfo = uri[pos..];
  621. }
  622. else
  623. {
  624. uri_tmp = uri;
  625. pathInfo = string.Empty;
  626. }
  627. string urlkey;
  628. if (uri.Contains("lslhttps"))
  629. urlkey = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + uri_tmp;
  630. //m_UrlMap[];
  631. else
  632. urlkey = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp;
  633. if (!m_UrlMap.TryGetValue(urlkey, out UrlData url))
  634. {
  635. //m_log.Warn("[HttpRequestHandler]: http-in request failed; no such url: "+urlkey.ToString());
  636. request.InputStream.Dispose();
  637. return errorResponse(request, (int)HttpStatusCode.NotFound);
  638. }
  639. //for llGetHttpHeader support we need to store original URI here
  640. //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers
  641. //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader
  642. RequestData requestData = new()
  643. {
  644. requestID = requestID,
  645. requestDone = false,
  646. startTime = System.Environment.TickCount,
  647. uri = uri,
  648. hostID = url.hostID,
  649. scene = url.scene,
  650. headers = new Dictionary<string, string>()
  651. };
  652. NameValueCollection headers = request.Headers;
  653. if (headers.Count > 0)
  654. {
  655. for(int i = 0; i < headers.Count; ++i)
  656. {
  657. string name = headers.GetKey(i);
  658. if (!string.IsNullOrEmpty(name))
  659. requestData.headers[name] = headers[i];
  660. }
  661. }
  662. NameValueCollection query = request.QueryString;
  663. if (query.Count > 0)
  664. {
  665. StringBuilder sb = new();
  666. for (int i = 0; i < query.Count; ++i)
  667. {
  668. string key = query.GetKey(i);
  669. if (string.IsNullOrEmpty(key))
  670. sb.AppendFormat("{0}&", query[i]);
  671. else
  672. sb.AppendFormat("{0}={1}&", key, query[i]);
  673. }
  674. if (sb.Length > 1)
  675. sb.Remove(sb.Length - 1, 1);
  676. requestData.headers["x-query-string"] = sb.ToString();
  677. }
  678. else
  679. requestData.headers["x-query-string"] = string.Empty;
  680. //if this machine is behind DNAT/port forwarding, currently this is being
  681. //set to address of port forwarding router
  682. requestData.headers["x-remote-ip"] = request.RemoteIPEndPoint.Address.ToString();
  683. requestData.headers["x-path-info"] = pathInfo;
  684. requestData.headers["x-script-url"] = url.url;
  685. //requestData.ev = new ManualResetEvent(false);
  686. lock (url.requests)
  687. {
  688. url.requests.Add(requestID, requestData);
  689. }
  690. lock (m_RequestMap)
  691. {
  692. //add to request map
  693. m_RequestMap.Add(requestID, url);
  694. }
  695. string requestBody;
  696. if (request.InputStream.Length > 0)
  697. {
  698. using (StreamReader reader = new(request.InputStream, Encoding.UTF8))
  699. requestBody = reader.ReadToEnd();
  700. }
  701. else
  702. requestBody = string.Empty;
  703. request.InputStream.Dispose();
  704. url.engine.PostScriptEvent(url.itemID, "http_request", new Object[] { requestID.ToString(), request.HttpMethod, requestBody });
  705. return null;
  706. }
  707. catch (Exception we)
  708. {
  709. //Hashtable response = new Hashtable();
  710. m_log.Warn("[HttpRequestHandler]: http-in request failed");
  711. m_log.Warn(we.Message);
  712. m_log.Warn(we.StackTrace);
  713. }
  714. return errorResponse(request, (int)HttpStatusCode.BadRequest);
  715. }
  716. }
  717. protected void OnScriptReset(uint localID, UUID itemID)
  718. {
  719. ScriptRemoved(itemID);
  720. }
  721. public int GetUrlCount(UUID groupID)
  722. {
  723. if (!m_enabled)
  724. return 0;
  725. lock (m_UrlMap)
  726. {
  727. m_countsPerSOG.TryGetValue(groupID, out int count);
  728. return count;
  729. }
  730. }
  731. }
  732. }