UrlModule.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 IHttpServer m_HttpServer = null;
  90. protected IHttpServer m_HttpsServer = null;
  91. private string m_lsl_shard = "OpenSim";
  92. private string m_lsl_user_agent = string.Empty;
  93. public string ExternalHostNameForLSL { get; protected set; }
  94. /// <summary>
  95. /// The default maximum number of urls
  96. /// </summary>
  97. public const int DefaultTotalUrls = 15000;
  98. /// <summary>
  99. /// Maximum number of external urls that can be set up by this module.
  100. /// </summary>
  101. public int TotalUrls { get; set; }
  102. public Type ReplaceableInterface
  103. {
  104. get { return typeof(IUrlModule); }
  105. }
  106. public string Name
  107. {
  108. get { return "UrlModule"; }
  109. }
  110. public void Initialise(IConfigSource config)
  111. {
  112. IConfig networkConfig = config.Configs["Network"];
  113. m_enabled = false;
  114. if (networkConfig != null)
  115. {
  116. m_lsl_shard = networkConfig.GetString("shard", m_lsl_shard);
  117. m_lsl_user_agent = networkConfig.GetString("user_agent", m_lsl_user_agent);
  118. ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", null);
  119. bool ssl_enabled = config.Configs["Network"].GetBoolean("https_listener", false);
  120. if (ssl_enabled)
  121. m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort);
  122. }
  123. else
  124. {
  125. m_ErrorStr = "[Network] configuration missing, HTTP listener for LSL disabled";
  126. m_log.Warn("[URL MODULE]: " + m_ErrorStr);
  127. return;
  128. }
  129. if (string.IsNullOrWhiteSpace(ExternalHostNameForLSL))
  130. {
  131. m_ErrorStr = "ExternalHostNameForLSL not defined in configuration, HTTP listener for LSL disabled";
  132. m_log.Warn("[URL MODULE]: " + m_ErrorStr);
  133. return;
  134. }
  135. IPAddress ia = Util.GetHostFromDNS(ExternalHostNameForLSL);
  136. if (ia == null)
  137. {
  138. m_ErrorStr = "Could not resolve ExternalHostNameForLSL, HTTP listener for LSL disabled";
  139. m_log.Warn("[URL MODULE]: " + m_ErrorStr);
  140. return;
  141. }
  142. m_enabled = true;
  143. m_ErrorStr = String.Empty;
  144. IConfig llFunctionsConfig = config.Configs["LL-Functions"];
  145. if (llFunctionsConfig != null)
  146. TotalUrls = llFunctionsConfig.GetInt("max_external_urls_per_simulator", DefaultTotalUrls);
  147. else
  148. TotalUrls = DefaultTotalUrls;
  149. }
  150. public void PostInitialise()
  151. {
  152. }
  153. public void AddRegion(Scene scene)
  154. {
  155. if (m_enabled && m_HttpServer == null)
  156. {
  157. // There can only be one
  158. //
  159. m_HttpServer = MainServer.Instance;
  160. //
  161. // We can use the https if it is enabled
  162. if (m_HttpsPort > 0)
  163. {
  164. m_HttpsServer = MainServer.GetHttpServer(m_HttpsPort);
  165. }
  166. }
  167. scene.RegisterModuleInterface<IUrlModule>(this);
  168. scene.EventManager.OnScriptReset += OnScriptReset;
  169. }
  170. public void RegionLoaded(Scene scene)
  171. {
  172. IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>();
  173. foreach (IScriptModule scriptModule in scriptModules)
  174. {
  175. scriptModule.OnScriptRemoved += ScriptRemoved;
  176. scriptModule.OnObjectRemoved += ObjectRemoved;
  177. }
  178. }
  179. public void RemoveRegion(Scene scene)
  180. {
  181. // Drop references to that scene
  182. foreach (KeyValuePair<string, UrlData> kvp in m_UrlMap)
  183. {
  184. if (kvp.Value.scene == scene)
  185. kvp.Value.scene = null;
  186. }
  187. foreach (KeyValuePair<UUID, UrlData> kvp in m_RequestMap)
  188. {
  189. if (kvp.Value.scene == scene)
  190. kvp.Value.scene = null;
  191. }
  192. }
  193. public void Close()
  194. {
  195. }
  196. public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID, Hashtable options)
  197. {
  198. UUID urlcode = UUID.Random();
  199. if(!m_enabled)
  200. {
  201. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", m_ErrorStr });
  202. return urlcode;
  203. }
  204. lock (m_UrlMap)
  205. {
  206. if (m_UrlMap.Count >= TotalUrls)
  207. {
  208. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED",
  209. "Too many URLs already open" });
  210. return urlcode;
  211. }
  212. string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString();
  213. UUID groupID = host.ParentGroup.UUID;
  214. UrlData urlData = new()
  215. {
  216. hostID = host.UUID,
  217. groupID = groupID,
  218. itemID = itemID,
  219. engine = engine,
  220. url = url,
  221. urlcode = urlcode,
  222. isSsl = false,
  223. requests = new Dictionary<UUID, RequestData>(),
  224. scene = host.ParentGroup.Scene
  225. };
  226. if (options != null && options["allowXss"] != null)
  227. urlData.allowXss = true;
  228. else
  229. urlData.allowXss = false;
  230. m_UrlMap[url] = urlData;
  231. if (m_countsPerSOG.TryGetValue(groupID, out int urlcount))
  232. m_countsPerSOG[groupID] = ++urlcount;
  233. else
  234. m_countsPerSOG[groupID] = 1;
  235. string uri = "/lslhttp/" + urlcode.ToString();
  236. PollServiceEventArgs args
  237. = new(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, Drop, urlcode, 25000);
  238. m_HttpServer.AddPollServiceHTTPHandlerVarPath(args);
  239. //m_log.DebugFormat(
  240. // "[URL MODULE]: Set up incoming request url {0} for {1} in {2} {3}",
  241. // uri, itemID, host.Name, host.LocalId);
  242. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url + "/"});
  243. }
  244. return urlcode;
  245. }
  246. public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID, Hashtable options)
  247. {
  248. UUID urlcode = UUID.Random();
  249. if(!m_enabled)
  250. {
  251. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", m_ErrorStr });
  252. return urlcode;
  253. }
  254. if (m_HttpsServer == null)
  255. {
  256. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
  257. return urlcode;
  258. }
  259. lock (m_UrlMap)
  260. {
  261. if (m_UrlMap.Count >= TotalUrls)
  262. {
  263. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED",
  264. "Too many URLs already open" });
  265. return urlcode;
  266. }
  267. string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString();
  268. UUID groupID = host.ParentGroup.UUID;
  269. UrlData urlData = new()
  270. {
  271. hostID = host.UUID,
  272. groupID = groupID,
  273. itemID = itemID,
  274. engine = engine,
  275. url = url,
  276. urlcode = urlcode,
  277. isSsl = true,
  278. requests = new Dictionary<UUID, RequestData>(),
  279. scene = host.ParentGroup.Scene
  280. };
  281. if (options != null && options["allowXss"] != null)
  282. urlData.allowXss = true;
  283. else
  284. urlData.allowXss = false;
  285. m_UrlMap[url] = urlData;
  286. if (m_countsPerSOG.TryGetValue(groupID, out int urlcount))
  287. m_countsPerSOG[groupID] = ++urlcount;
  288. else
  289. m_countsPerSOG[groupID] = 1;
  290. string uri = "/lslhttps/" + urlcode.ToString();
  291. PollServiceEventArgs args = new(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, Drop, urlcode, 25000);
  292. m_HttpsServer.AddPollServiceHTTPHandlerVarPath(args);
  293. //m_log.DebugFormat(
  294. // "[URL MODULE]: Set up incoming secure request url {0} for {1} in {2} {3}",
  295. // uri, itemID, host.Name, host.LocalId);
  296. // keep ending / because legacy
  297. engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url + "/"});
  298. }
  299. return urlcode;
  300. }
  301. public void ReleaseURL(string url)
  302. {
  303. lock (m_UrlMap)
  304. {
  305. url = url.TrimEnd(new char[] { '/' });
  306. if (!m_UrlMap.TryGetValue(url, out UrlData data))
  307. {
  308. return;
  309. }
  310. lock (m_RequestMap)
  311. {
  312. foreach (UUID req in data.requests.Keys)
  313. m_RequestMap.Remove(req);
  314. }
  315. // m_log.DebugFormat(
  316. // "[URL MODULE]: Releasing url {0} for {1} in {2}",
  317. // url, data.itemID, data.hostID);
  318. RemoveUrl(data);
  319. m_UrlMap.Remove(url);
  320. }
  321. }
  322. public void HttpContentType(UUID request, string type)
  323. {
  324. lock (m_UrlMap)
  325. {
  326. if (m_RequestMap.TryGetValue(request, out UrlData urlData) && urlData != null)
  327. {
  328. urlData.requests[request].responseType = type;
  329. }
  330. else
  331. {
  332. m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString());
  333. }
  334. }
  335. }
  336. public void HttpResponse(UUID request, int status, string body)
  337. {
  338. lock (m_RequestMap)
  339. {
  340. if (m_RequestMap.TryGetValue(request, out UrlData urlData) && urlData != null)
  341. {
  342. lock (urlData.requests)
  343. {
  344. if (urlData.requests.TryGetValue(request, out RequestData rd) && rd != null)
  345. {
  346. if (!rd.responseSent)
  347. {
  348. string responseBody = body;
  349. if (rd.responseType.Equals("text/plain"))
  350. {
  351. if (rd.headers.TryGetValue("user-agent", out string value))
  352. {
  353. if (value != null && value.Contains("MSIE", StringComparison.InvariantCultureIgnoreCase))
  354. {
  355. // wrap the html escaped response if the target client is IE
  356. // It ignores "text/plain" if the body is html
  357. responseBody = "<html>" + System.Web.HttpUtility.HtmlEncode(body) + "</html>";
  358. }
  359. }
  360. }
  361. rd.responseCode = status;
  362. rd.responseBody = responseBody;
  363. //urlData.requests[request].ev.Set();
  364. rd.requestDone = true;
  365. rd.responseSent = true;
  366. }
  367. }
  368. }
  369. }
  370. else
  371. {
  372. m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString());
  373. }
  374. }
  375. }
  376. public string GetHttpHeader(UUID requestId, string header)
  377. {
  378. lock (m_RequestMap)
  379. {
  380. if (m_RequestMap.TryGetValue(requestId, out UrlData urlData) && urlData != null)
  381. {
  382. if (urlData.requests[requestId].headers.TryGetValue(header.ToLowerInvariant(), out string value))
  383. return value;
  384. }
  385. else
  386. {
  387. m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId);
  388. }
  389. }
  390. return string.Empty;
  391. }
  392. public int GetFreeUrls()
  393. {
  394. lock (m_UrlMap)
  395. return TotalUrls - m_UrlMap.Count;
  396. }
  397. public void ScriptRemoved(UUID itemID)
  398. {
  399. // m_log.DebugFormat("[URL MODULE]: Removing script {0}", itemID);
  400. lock (m_UrlMap)
  401. {
  402. List<string> removeURLs = new();
  403. foreach (KeyValuePair<string, UrlData> url in m_UrlMap)
  404. {
  405. if (url.Value.itemID == itemID)
  406. {
  407. RemoveUrl(url.Value);
  408. removeURLs.Add(url.Key);
  409. lock (m_RequestMap)
  410. {
  411. foreach (UUID req in url.Value.requests.Keys)
  412. m_RequestMap.Remove(req);
  413. }
  414. }
  415. }
  416. foreach (string urlname in removeURLs)
  417. m_UrlMap.Remove(urlname);
  418. }
  419. }
  420. public void ObjectRemoved(UUID objectID)
  421. {
  422. lock (m_UrlMap)
  423. {
  424. List<string> removeURLs = new();
  425. foreach (KeyValuePair<string, UrlData> url in m_UrlMap)
  426. {
  427. if (url.Value.hostID == objectID)
  428. {
  429. RemoveUrl(url.Value);
  430. removeURLs.Add(url.Key);
  431. lock (m_RequestMap)
  432. {
  433. foreach (UUID req in url.Value.requests.Keys)
  434. m_RequestMap.Remove(req);
  435. }
  436. }
  437. }
  438. foreach (string urlname in removeURLs)
  439. m_UrlMap.Remove(urlname);
  440. }
  441. }
  442. protected void RemoveUrl(UrlData data)
  443. {
  444. if (data.isSsl)
  445. m_HttpsServer.RemovePollServiceHTTPHandler("", "/lslhttps/"+data.urlcode.ToString());
  446. else
  447. m_HttpServer.RemovePollServiceHTTPHandler("", "/lslhttp/"+data.urlcode.ToString());
  448. if(m_countsPerSOG.TryGetValue(data.groupID, out int count))
  449. {
  450. --count;
  451. if(count <= 0)
  452. m_countsPerSOG.Remove(data.groupID);
  453. else
  454. m_countsPerSOG[data.groupID] = count;
  455. }
  456. }
  457. protected Hashtable NoEvents(UUID requestID, UUID sessionID)
  458. {
  459. UrlData url;
  460. int startTime = 0;
  461. lock (m_RequestMap)
  462. {
  463. if (!m_RequestMap.TryGetValue(requestID, out url))
  464. return new Hashtable();
  465. startTime = url.requests[requestID].startTime;
  466. }
  467. if (System.Environment.TickCount - startTime < 25000)
  468. return new Hashtable();
  469. //remove from map
  470. lock (url.requests)
  471. {
  472. url.requests.Remove(requestID);
  473. }
  474. lock (m_RequestMap)
  475. {
  476. m_RequestMap.Remove(requestID);
  477. }
  478. return new Hashtable()
  479. {
  480. ["int_response_code"] = 500,
  481. ["str_response_string"] = "Script timeout",
  482. ["content_type"] = "text/plain",
  483. ["keepalive"] = false
  484. };
  485. }
  486. protected bool HasEvents(UUID requestID, UUID sessionID)
  487. {
  488. UrlData url;
  489. lock (m_RequestMap)
  490. {
  491. if (!m_RequestMap.TryGetValue(requestID, out url))
  492. return false;
  493. }
  494. lock (url.requests)
  495. {
  496. if (!url.requests.TryGetValue(requestID, out RequestData rd) || rd == null)
  497. return false;
  498. if (System.Environment.TickCount - rd.startTime > 25000)
  499. return true;
  500. return rd.requestDone;
  501. }
  502. }
  503. protected void Drop(UUID requestID, UUID _)
  504. {
  505. UrlData url = null;
  506. lock (m_RequestMap)
  507. {
  508. if (m_RequestMap.TryGetValue(requestID, out url))
  509. {
  510. m_RequestMap.Remove(requestID);
  511. if(url != null)
  512. {
  513. lock (url.requests)
  514. url.requests.Remove(requestID);
  515. }
  516. }
  517. }
  518. }
  519. protected Hashtable GetEvents(UUID requestID, UUID sessionID)
  520. {
  521. UrlData url = null;
  522. lock (m_RequestMap)
  523. {
  524. if (!m_RequestMap.TryGetValue(requestID, out url))
  525. return new Hashtable();
  526. }
  527. RequestData requestData = null;
  528. bool timeout = false;
  529. lock (url.requests)
  530. {
  531. requestData = url.requests[requestID];
  532. if (requestData == null)
  533. return new Hashtable();
  534. timeout = System.Environment.TickCount - requestData.startTime > 25000;
  535. if (!requestData.requestDone && !timeout)
  536. return new Hashtable();
  537. url.requests.Remove(requestID);
  538. lock (m_RequestMap)
  539. {
  540. m_RequestMap.Remove(requestID);
  541. }
  542. }
  543. if (timeout)
  544. {
  545. return new Hashtable()
  546. {
  547. ["int_response_code"] = 500,
  548. ["str_response_string"] = "Script timeout",
  549. ["content_type"] = "text/plain",
  550. ["keepalive"] = false
  551. };
  552. }
  553. Hashtable headers = new();
  554. if(url.scene is not null)
  555. {
  556. SceneObjectPart sop = url.scene.GetSceneObjectPart(url.hostID);
  557. if(sop != null)
  558. {
  559. RegionInfo ri = url.scene.RegionInfo;
  560. Vector3 position = sop.AbsolutePosition;
  561. Vector3 velocity = sop.Velocity;
  562. Quaternion rotation = sop.GetWorldRotation();
  563. headers["X-SecondLife-Object-Name"] = sop.Name;
  564. headers["X-SecondLife-Object-Key"] = sop.UUID.ToString();
  565. headers["X-SecondLife-Region"] = string.Format("{0} ({1}, {2})", ri.RegionName, ri.WorldLocX, ri.WorldLocY);
  566. headers["X-SecondLife-Local-Position"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", position.X, position.Y, position.Z);
  567. headers["X-SecondLife-Local-Velocity"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", velocity.X, velocity.Y, velocity.Z);
  568. 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);
  569. //headers["X-SecondLife-Owner-Name"] = ownerName;
  570. headers["X-SecondLife-Owner-Key"] = sop.OwnerID.ToString();
  571. }
  572. }
  573. if (!string.IsNullOrWhiteSpace(m_lsl_shard))
  574. headers["X-SecondLife-Shard"] = m_lsl_shard;
  575. if (!string.IsNullOrWhiteSpace(m_lsl_user_agent))
  576. headers["User-Agent"] = m_lsl_user_agent;
  577. if (url.isSsl)
  578. headers.Add("Accept-CH","UA");
  579. Hashtable response = new()
  580. {
  581. ["int_response_code"] = requestData.responseCode,
  582. ["str_response_string"] = requestData.responseBody,
  583. ["content_type"] = requestData.responseType,
  584. ["headers"] = headers,
  585. ["keepalive"] = false
  586. };
  587. if (url.allowXss)
  588. response["access_control_allow_origin"] = "*";
  589. return response;
  590. }
  591. private OSHttpResponse errorResponse(OSHttpRequest request, int error)
  592. {
  593. OSHttpResponse resp = new(request)
  594. {
  595. StatusCode = error
  596. };
  597. return resp;
  598. }
  599. public OSHttpResponse HttpRequestHandler(UUID requestID, OSHttpRequest request)
  600. {
  601. lock (request)
  602. {
  603. string uri = request.RawUrl;
  604. if(uri.Length < 45)
  605. {
  606. request.InputStream.Dispose();
  607. return errorResponse(request, (int)HttpStatusCode.BadRequest);
  608. }
  609. try
  610. {
  611. //string uri_full = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/";
  612. string uri_tmp;
  613. string pathInfo;
  614. int pos = uri.IndexOf('/', 45); // /lslhttp/uuid/ <-
  615. if (pos >= 45)
  616. {
  617. uri_tmp = uri[..pos];
  618. pathInfo = uri[pos..];
  619. }
  620. else
  621. {
  622. uri_tmp = uri;
  623. pathInfo = string.Empty;
  624. }
  625. string urlkey;
  626. if (uri.Contains("lslhttps"))
  627. urlkey = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + uri_tmp;
  628. //m_UrlMap[];
  629. else
  630. urlkey = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp;
  631. if (!m_UrlMap.TryGetValue(urlkey, out UrlData url))
  632. {
  633. //m_log.Warn("[HttpRequestHandler]: http-in request failed; no such url: "+urlkey.ToString());
  634. request.InputStream.Dispose();
  635. return errorResponse(request, (int)HttpStatusCode.NotFound);
  636. }
  637. //for llGetHttpHeader support we need to store original URI here
  638. //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers
  639. //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader
  640. RequestData requestData = new()
  641. {
  642. requestID = requestID,
  643. requestDone = false,
  644. startTime = System.Environment.TickCount,
  645. uri = uri,
  646. hostID = url.hostID,
  647. scene = url.scene,
  648. headers = new Dictionary<string, string>()
  649. };
  650. NameValueCollection headers = request.Headers;
  651. if (headers.Count > 0)
  652. {
  653. for(int i = 0; i < headers.Count; ++i)
  654. {
  655. string name = headers.GetKey(i);
  656. if (!string.IsNullOrEmpty(name))
  657. requestData.headers[name] = headers[i];
  658. }
  659. }
  660. NameValueCollection query = request.QueryString;
  661. if (query.Count > 0)
  662. {
  663. StringBuilder sb = new();
  664. for (int i = 0; i < query.Count; ++i)
  665. {
  666. string key = query.GetKey(i);
  667. if (string.IsNullOrEmpty(key))
  668. sb.AppendFormat("{0}&", query[i]);
  669. else
  670. sb.AppendFormat("{0}={1}&", key, query[i]);
  671. }
  672. if (sb.Length > 1)
  673. sb.Remove(sb.Length - 1, 1);
  674. requestData.headers["x-query-string"] = sb.ToString();
  675. }
  676. else
  677. requestData.headers["x-query-string"] = string.Empty;
  678. //if this machine is behind DNAT/port forwarding, currently this is being
  679. //set to address of port forwarding router
  680. requestData.headers["x-remote-ip"] = request.RemoteIPEndPoint.Address.ToString();
  681. requestData.headers["x-path-info"] = pathInfo;
  682. requestData.headers["x-script-url"] = url.url;
  683. //requestData.ev = new ManualResetEvent(false);
  684. lock (url.requests)
  685. {
  686. url.requests.Add(requestID, requestData);
  687. }
  688. lock (m_RequestMap)
  689. {
  690. //add to request map
  691. m_RequestMap.Add(requestID, url);
  692. }
  693. string requestBody;
  694. if (request.InputStream.Length > 0)
  695. {
  696. using (StreamReader reader = new(request.InputStream, Encoding.UTF8))
  697. requestBody = reader.ReadToEnd();
  698. }
  699. else
  700. requestBody = string.Empty;
  701. request.InputStream.Dispose();
  702. url.engine.PostScriptEvent(url.itemID, "http_request", new Object[] { requestID.ToString(), request.HttpMethod, requestBody });
  703. return null;
  704. }
  705. catch (Exception we)
  706. {
  707. //Hashtable response = new Hashtable();
  708. m_log.Warn("[HttpRequestHandler]: http-in request failed");
  709. m_log.Warn(we.Message);
  710. m_log.Warn(we.StackTrace);
  711. }
  712. return errorResponse(request, (int)HttpStatusCode.BadRequest);
  713. }
  714. }
  715. protected void OnScriptReset(uint localID, UUID itemID)
  716. {
  717. ScriptRemoved(itemID);
  718. }
  719. public int GetUrlCount(UUID groupID)
  720. {
  721. if (!m_enabled)
  722. return 0;
  723. lock (m_UrlMap)
  724. {
  725. m_countsPerSOG.TryGetValue(groupID, out int count);
  726. return count;
  727. }
  728. }
  729. }
  730. }