OSSL_Api.cs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  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.Runtime.Remoting.Lifetime;
  31. using System.Text;
  32. using System.Net;
  33. using OpenMetaverse;
  34. using Nini.Config;
  35. using OpenSim;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Communications.Cache;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Region.Framework.Scenes.Hypergrid;
  42. using OpenSim.Region.ScriptEngine.Shared;
  43. using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
  44. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  45. using OpenSim.Region.ScriptEngine.Interfaces;
  46. using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
  47. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  48. using System.Text.RegularExpressions;
  49. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  50. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  51. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  52. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  53. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  54. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  55. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  56. namespace OpenSim.Region.ScriptEngine.Shared.Api
  57. {
  58. //////////////////////////////////////////////////////////////
  59. //
  60. // Level description
  61. //
  62. // None - Function is no threat at all. It doesn't constitute
  63. // an threat to either users or the system and has no
  64. // known side effects
  65. //
  66. // Nuisance - Abuse of this command can cause a nuisance to the
  67. // region operator, such as log message spew
  68. //
  69. // VeryLow - Extreme levels ob abuse of this function can cause
  70. // impaired functioning of the region, or very gullible
  71. // users can be tricked into experiencing harmless effects
  72. //
  73. // Low - Intentional abuse can cause crashes or malfunction
  74. // under certain circumstances, which can easily be rectified,
  75. // or certain users can be tricked into certain situations
  76. // in an avoidable manner.
  77. //
  78. // Moderate - Intentional abuse can cause denial of service and crashes
  79. // with potential of data or state loss, or trusting users
  80. // can be tricked into embarrassing or uncomfortable
  81. // situationsa.
  82. //
  83. // High - Casual abuse can cause impaired functionality or temporary
  84. // denial of service conditions. Intentional abuse can easily
  85. // cause crashes with potential data loss, or can be used to
  86. // trick experienced and cautious users into unwanted situations,
  87. // or changes global data permanently and without undo ability
  88. // Malicious scripting can allow theft of content
  89. //
  90. // VeryHigh - Even normal use may, depending on the number of instances,
  91. // or frequency of use, result in severe service impairment
  92. // or crash with loss of data, or can be used to cause
  93. // unwanted or harmful effects on users without giving the
  94. // user a means to avoid it.
  95. //
  96. // Severe - Even casual use is a danger to region stability, or function
  97. // allows console or OS command execution, or function allows
  98. // taking money without consent, or allows deletion or
  99. // modification of user data, or allows the compromise of
  100. // sensitive data by design.
  101. [Serializable]
  102. public class OSSL_Api : MarshalByRefObject, IOSSL_Api, IScriptApi
  103. {
  104. internal IScriptEngine m_ScriptEngine;
  105. internal ILSL_Api m_LSL_Api = null; // get a reference to the LSL API so we can call methods housed there
  106. internal SceneObjectPart m_host;
  107. internal uint m_localID;
  108. internal UUID m_itemID;
  109. internal bool m_OSFunctionsEnabled = false;
  110. internal ThreatLevel m_MaxThreatLevel = ThreatLevel.VeryLow;
  111. internal float m_ScriptDelayFactor = 1.0f;
  112. internal float m_ScriptDistanceFactor = 1.0f;
  113. internal Dictionary<string, List<UUID> > m_FunctionPerms = new Dictionary<string, List<UUID> >();
  114. public void Initialize(IScriptEngine ScriptEngine, SceneObjectPart host, uint localID, UUID itemID)
  115. {
  116. m_ScriptEngine = ScriptEngine;
  117. m_host = host;
  118. m_localID = localID;
  119. m_itemID = itemID;
  120. if (m_ScriptEngine.Config.GetBoolean("AllowOSFunctions", false))
  121. m_OSFunctionsEnabled = true;
  122. m_ScriptDelayFactor =
  123. m_ScriptEngine.Config.GetFloat("ScriptDelayFactor", 1.0f);
  124. m_ScriptDistanceFactor =
  125. m_ScriptEngine.Config.GetFloat("ScriptDistanceLimitFactor", 1.0f);
  126. string risk = m_ScriptEngine.Config.GetString("OSFunctionThreatLevel", "VeryLow");
  127. switch (risk)
  128. {
  129. case "None":
  130. m_MaxThreatLevel = ThreatLevel.None;
  131. break;
  132. case "VeryLow":
  133. m_MaxThreatLevel = ThreatLevel.VeryLow;
  134. break;
  135. case "Low":
  136. m_MaxThreatLevel = ThreatLevel.Low;
  137. break;
  138. case "Moderate":
  139. m_MaxThreatLevel = ThreatLevel.Moderate;
  140. break;
  141. case "High":
  142. m_MaxThreatLevel = ThreatLevel.High;
  143. break;
  144. case "VeryHigh":
  145. m_MaxThreatLevel = ThreatLevel.VeryHigh;
  146. break;
  147. case "Severe":
  148. m_MaxThreatLevel = ThreatLevel.Severe;
  149. break;
  150. default:
  151. break;
  152. }
  153. }
  154. public override Object InitializeLifetimeService()
  155. {
  156. ILease lease = (ILease)base.InitializeLifetimeService();
  157. if (lease.CurrentState == LeaseState.Initial)
  158. {
  159. lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
  160. // lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
  161. // lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
  162. }
  163. return lease;
  164. }
  165. public Scene World
  166. {
  167. get { return m_ScriptEngine.World; }
  168. }
  169. internal void OSSLError(string msg)
  170. {
  171. throw new Exception("OSSL Runtime Error: " + msg);
  172. }
  173. private void InitLSL()
  174. {
  175. if (m_LSL_Api != null)
  176. return;
  177. m_LSL_Api = (ILSL_Api)m_ScriptEngine.GetApi(m_itemID, "LSL");
  178. }
  179. //
  180. //Dumps an error message on the debug console.
  181. //
  182. internal void OSSLShoutError(string message)
  183. {
  184. if (message.Length > 1023)
  185. message = message.Substring(0, 1023);
  186. World.SimChat(Utils.StringToBytes(message),
  187. ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, true);
  188. IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
  189. wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message);
  190. }
  191. public void CheckThreatLevel(ThreatLevel level, string function)
  192. {
  193. if (!m_OSFunctionsEnabled)
  194. OSSLError(String.Format("{0} permission denied. All OS functions are disabled.", function)); // throws
  195. if (!m_FunctionPerms.ContainsKey(function))
  196. {
  197. string perm = m_ScriptEngine.Config.GetString("Allow_" + function, "");
  198. if (perm == "")
  199. {
  200. m_FunctionPerms[function] = null; // a null value is default
  201. }
  202. else
  203. {
  204. bool allowed;
  205. if (bool.TryParse(perm, out allowed))
  206. {
  207. // Boolean given
  208. if (allowed)
  209. {
  210. m_FunctionPerms[function] = new List<UUID>();
  211. m_FunctionPerms[function].Add(UUID.Zero);
  212. }
  213. else
  214. m_FunctionPerms[function] = new List<UUID>(); // Empty list = none
  215. }
  216. else
  217. {
  218. m_FunctionPerms[function] = new List<UUID>();
  219. string[] ids = perm.Split(new char[] {','});
  220. foreach (string id in ids)
  221. {
  222. string current = id.Trim();
  223. UUID uuid;
  224. if (UUID.TryParse(current, out uuid))
  225. {
  226. if (uuid != UUID.Zero)
  227. m_FunctionPerms[function].Add(uuid);
  228. }
  229. }
  230. }
  231. }
  232. }
  233. // If the list is null, then the value was true / undefined
  234. // Threat level governs permissions in this case
  235. //
  236. // If the list is non-null, then it is a list of UUIDs allowed
  237. // to use that particular function. False causes an empty
  238. // list and therefore means "no one"
  239. //
  240. // To allow use by anyone, the list contains UUID.Zero
  241. //
  242. if (m_FunctionPerms[function] == null) // No list = true
  243. {
  244. if (level > m_MaxThreatLevel)
  245. OSSLError(
  246. String.Format(
  247. "{0} permission denied. Allowed threat level is {1} but function threat level is {2}.",
  248. function, m_MaxThreatLevel, level));
  249. }
  250. else
  251. {
  252. if (!m_FunctionPerms[function].Contains(UUID.Zero))
  253. {
  254. if (!m_FunctionPerms[function].Contains(m_host.OwnerID))
  255. OSSLError(
  256. String.Format("{0} permission denied. Prim owner is not in the list of users allowed to execute this function.",
  257. function));
  258. }
  259. }
  260. }
  261. protected void ScriptSleep(int delay)
  262. {
  263. delay = (int)((float)delay * m_ScriptDelayFactor);
  264. if (delay == 0)
  265. return;
  266. System.Threading.Thread.Sleep(delay);
  267. }
  268. //
  269. // OpenSim functions
  270. //
  271. public LSL_Integer osTerrainSetHeight(int x, int y, double val)
  272. {
  273. CheckThreatLevel(ThreatLevel.High, "osTerrainSetHeight");
  274. m_host.AddScriptLPS(1);
  275. if (x > ((int)Constants.RegionSize - 1) || x < 0 || y > ((int)Constants.RegionSize - 1) || y < 0)
  276. OSSLError("osTerrainSetHeight: Coordinate out of bounds");
  277. if (World.Permissions.CanTerraformLand(m_host.OwnerID, new Vector3(x, y, 0)))
  278. {
  279. World.Heightmap[x, y] = val;
  280. return 1;
  281. }
  282. else
  283. {
  284. return 0;
  285. }
  286. }
  287. public LSL_Float osTerrainGetHeight(int x, int y)
  288. {
  289. CheckThreatLevel(ThreatLevel.None, "osTerrainGetHeight");
  290. m_host.AddScriptLPS(1);
  291. if (x > ((int)Constants.RegionSize - 1) || x < 0 || y > ((int)Constants.RegionSize - 1) || y < 0)
  292. OSSLError("osTerrainGetHeight: Coordinate out of bounds");
  293. return World.Heightmap[x, y];
  294. }
  295. public void osTerrainFlush()
  296. {
  297. CheckThreatLevel(ThreatLevel.VeryLow, "osTerrainFlush");
  298. ITerrainModule terrainModule = World.RequestModuleInterface<ITerrainModule>();
  299. if (terrainModule != null) terrainModule.TaintTerrain();
  300. }
  301. public int osRegionRestart(double seconds)
  302. {
  303. // This is High here because region restart is not reliable
  304. // it may result in the region staying down or becoming
  305. // unstable. This should be changed to Low or VeryLow once
  306. // The underlying functionality is fixed, since the security
  307. // as such is sound
  308. //
  309. CheckThreatLevel(ThreatLevel.High, "osRegionRestart");
  310. m_host.AddScriptLPS(1);
  311. if (World.Permissions.CanIssueEstateCommand(m_host.OwnerID, false))
  312. {
  313. World.Restart((float)seconds);
  314. return 1;
  315. }
  316. else
  317. {
  318. return 0;
  319. }
  320. }
  321. public void osRegionNotice(string msg)
  322. {
  323. // This implementation provides absolutely no security
  324. // It's high griefing potential makes this classification
  325. // necessary
  326. //
  327. CheckThreatLevel(ThreatLevel.VeryHigh, "osRegionNotice");
  328. m_host.AddScriptLPS(1);
  329. IDialogModule dm = World.RequestModuleInterface<IDialogModule>();
  330. if (dm != null)
  331. dm.SendGeneralAlert(msg);
  332. }
  333. public void osSetRot(UUID target, Quaternion rotation)
  334. {
  335. // This function has no security. It can be used to destroy
  336. // arbitrary builds the user would normally have no rights to
  337. //
  338. CheckThreatLevel(ThreatLevel.VeryHigh, "osSetRot");
  339. m_host.AddScriptLPS(1);
  340. if (World.Entities.ContainsKey(target))
  341. {
  342. World.Entities[target].Rotation = rotation;
  343. }
  344. else
  345. {
  346. OSSLError("osSetRot: Invalid target");
  347. }
  348. }
  349. public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams,
  350. int timer)
  351. {
  352. // This may be upgraded depending on the griefing or DOS
  353. // potential, or guarded with a delay
  354. //
  355. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureURL");
  356. m_host.AddScriptLPS(1);
  357. if (dynamicID == String.Empty)
  358. {
  359. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  360. UUID createdTexture =
  361. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  362. extraParams, timer);
  363. return createdTexture.ToString();
  364. }
  365. else
  366. {
  367. //TODO update existing dynamic textures
  368. }
  369. return UUID.Zero.ToString();
  370. }
  371. public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
  372. int timer, int alpha)
  373. {
  374. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureURLBlend");
  375. m_host.AddScriptLPS(1);
  376. if (dynamicID == String.Empty)
  377. {
  378. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  379. UUID createdTexture =
  380. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  381. extraParams, timer, true, (byte) alpha);
  382. return createdTexture.ToString();
  383. }
  384. else
  385. {
  386. //TODO update existing dynamic textures
  387. }
  388. return UUID.Zero.ToString();
  389. }
  390. public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
  391. bool blend, int disp, int timer, int alpha, int face)
  392. {
  393. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureURLBlendFace");
  394. m_host.AddScriptLPS(1);
  395. if (dynamicID == String.Empty)
  396. {
  397. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  398. UUID createdTexture =
  399. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  400. extraParams, timer, blend, disp, (byte) alpha, face);
  401. return createdTexture.ToString();
  402. }
  403. else
  404. {
  405. //TODO update existing dynamic textures
  406. }
  407. return UUID.Zero.ToString();
  408. }
  409. public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams,
  410. int timer)
  411. {
  412. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureData");
  413. m_host.AddScriptLPS(1);
  414. if (dynamicID == String.Empty)
  415. {
  416. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  417. if (textureManager != null)
  418. {
  419. if (extraParams == String.Empty)
  420. {
  421. extraParams = "256";
  422. }
  423. UUID createdTexture =
  424. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  425. extraParams, timer);
  426. return createdTexture.ToString();
  427. }
  428. }
  429. else
  430. {
  431. //TODO update existing dynamic textures
  432. }
  433. return UUID.Zero.ToString();
  434. }
  435. public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
  436. int timer, int alpha)
  437. {
  438. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureDataBlend");
  439. m_host.AddScriptLPS(1);
  440. if (dynamicID == String.Empty)
  441. {
  442. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  443. if (textureManager != null)
  444. {
  445. if (extraParams == String.Empty)
  446. {
  447. extraParams = "256";
  448. }
  449. UUID createdTexture =
  450. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  451. extraParams, timer, true, (byte) alpha);
  452. return createdTexture.ToString();
  453. }
  454. }
  455. else
  456. {
  457. //TODO update existing dynamic textures
  458. }
  459. return UUID.Zero.ToString();
  460. }
  461. public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
  462. bool blend, int disp, int timer, int alpha, int face)
  463. {
  464. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureDataBlendFace");
  465. m_host.AddScriptLPS(1);
  466. if (dynamicID == String.Empty)
  467. {
  468. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  469. if (textureManager != null)
  470. {
  471. if (extraParams == String.Empty)
  472. {
  473. extraParams = "256";
  474. }
  475. UUID createdTexture =
  476. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  477. extraParams, timer, blend, disp, (byte) alpha, face);
  478. return createdTexture.ToString();
  479. }
  480. }
  481. else
  482. {
  483. //TODO update existing dynamic textures
  484. }
  485. return UUID.Zero.ToString();
  486. }
  487. public bool osConsoleCommand(string command)
  488. {
  489. CheckThreatLevel(ThreatLevel.Severe, "osConsoleCommand");
  490. m_host.AddScriptLPS(1);
  491. if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID))
  492. {
  493. MainConsole.Instance.RunCommand(command);
  494. return true;
  495. }
  496. return false;
  497. }
  498. public void osSetPrimFloatOnWater(int floatYN)
  499. {
  500. CheckThreatLevel(ThreatLevel.VeryLow, "osSetPrimFloatOnWater");
  501. m_host.AddScriptLPS(1);
  502. if (m_host.ParentGroup != null)
  503. {
  504. if (m_host.ParentGroup.RootPart != null)
  505. {
  506. m_host.ParentGroup.RootPart.SetFloatOnWater(floatYN);
  507. }
  508. }
  509. }
  510. // Teleport functions
  511. public void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  512. {
  513. // High because there is no security check. High griefer potential
  514. //
  515. CheckThreatLevel(ThreatLevel.High, "osTeleportAgent");
  516. m_host.AddScriptLPS(1);
  517. UUID agentId = new UUID();
  518. if (UUID.TryParse(agent, out agentId))
  519. {
  520. ScenePresence presence = World.GetScenePresence(agentId);
  521. if (presence != null)
  522. {
  523. // agent must be over owners land to avoid abuse
  524. if (m_host.OwnerID
  525. == World.LandChannel.GetLandObject(
  526. presence.AbsolutePosition.X, presence.AbsolutePosition.Y).landData.OwnerID)
  527. {
  528. // Check for hostname , attempt to make a hglink
  529. // and convert the regionName to the target region
  530. if (regionName.Contains(".") && regionName.Contains(":"))
  531. {
  532. // Try to link the region
  533. RegionInfo regInfo = HGHyperlink.TryLinkRegion(World,
  534. presence.ControllingClient,
  535. regionName);
  536. // Get the region name
  537. if (regInfo != null)
  538. {
  539. regionName = regInfo.RegionName;
  540. }
  541. else
  542. {
  543. // Might need to ping the client here in case of failure??
  544. }
  545. }
  546. presence.ControllingClient.SendTeleportLocationStart();
  547. World.RequestTeleportLocation(presence.ControllingClient, regionName,
  548. new Vector3((float)position.x, (float)position.y, (float)position.z),
  549. new Vector3((float)lookat.x, (float)lookat.y, (float)lookat.z), (uint)TPFlags.ViaLocation);
  550. ScriptSleep(5000);
  551. }
  552. }
  553. }
  554. }
  555. // Teleport functions
  556. public void osTeleportAgent(string agent, uint regionX, uint regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  557. {
  558. // High because there is no security check. High griefer potential
  559. //
  560. CheckThreatLevel(ThreatLevel.High, "osTeleportAgent");
  561. ulong regionHandle = Util.UIntsToLong((regionX * (uint)Constants.RegionSize), (regionY * (uint)Constants.RegionSize));
  562. m_host.AddScriptLPS(1);
  563. UUID agentId = new UUID();
  564. if (UUID.TryParse(agent, out agentId))
  565. {
  566. ScenePresence presence = World.GetScenePresence(agentId);
  567. if (presence != null)
  568. {
  569. // agent must be over owners land to avoid abuse
  570. if (m_host.OwnerID
  571. == World.LandChannel.GetLandObject(
  572. presence.AbsolutePosition.X, presence.AbsolutePosition.Y).landData.OwnerID)
  573. {
  574. presence.ControllingClient.SendTeleportLocationStart();
  575. World.RequestTeleportLocation(presence.ControllingClient, regionHandle,
  576. new Vector3((float)position.x, (float)position.y, (float)position.z),
  577. new Vector3((float)lookat.x, (float)lookat.y, (float)lookat.z), (uint)TPFlags.ViaLocation);
  578. ScriptSleep(5000);
  579. }
  580. }
  581. }
  582. }
  583. public void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  584. {
  585. osTeleportAgent(agent, World.RegionInfo.RegionName, position, lookat);
  586. }
  587. // Functions that get information from the agent itself.
  588. //
  589. // osGetAgentIP - this is used to determine the IP address of
  590. //the client. This is needed to help configure other in world
  591. //resources based on the IP address of the clients connected.
  592. //I think High is a good risk level for this, as it is an
  593. //information leak.
  594. public string osGetAgentIP(string agent)
  595. {
  596. CheckThreatLevel(ThreatLevel.High, "osGetAgentIP");
  597. UUID avatarID = (UUID)agent;
  598. m_host.AddScriptLPS(1);
  599. if (World.Entities.ContainsKey((UUID)agent) && World.Entities[avatarID] is ScenePresence)
  600. {
  601. ScenePresence target = (ScenePresence)World.Entities[avatarID];
  602. EndPoint ep = target.ControllingClient.GetClientEP();
  603. if (ep is IPEndPoint)
  604. {
  605. IPEndPoint ip = (IPEndPoint)ep;
  606. return ip.Address.ToString();
  607. }
  608. }
  609. // fall through case, just return nothing
  610. return "";
  611. }
  612. // Get a list of all the avatars/agents in the region
  613. public LSL_List osGetAgents()
  614. {
  615. // threat level is None as we could get this information with an
  616. // in-world script as well, just not as efficient
  617. CheckThreatLevel(ThreatLevel.None, "osGetAgents");
  618. LSL_List result = new LSL_List();
  619. foreach (ScenePresence avatar in World.GetAvatars())
  620. {
  621. result.Add(avatar.Name);
  622. }
  623. return result;
  624. }
  625. // Adam's super super custom animation functions
  626. public void osAvatarPlayAnimation(string avatar, string animation)
  627. {
  628. CheckThreatLevel(ThreatLevel.VeryHigh, "osAvatarPlayAnimation");
  629. UUID avatarID = (UUID)avatar;
  630. m_host.AddScriptLPS(1);
  631. if (World.Entities.ContainsKey((UUID)avatar) && World.Entities[avatarID] is ScenePresence)
  632. {
  633. ScenePresence target = (ScenePresence)World.Entities[avatarID];
  634. if (target != null)
  635. {
  636. UUID animID=UUID.Zero;
  637. lock (m_host.TaskInventory)
  638. {
  639. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  640. {
  641. if (inv.Value.Name == animation)
  642. {
  643. if (inv.Value.Type == (int)AssetType.Animation)
  644. animID = inv.Value.AssetID;
  645. continue;
  646. }
  647. }
  648. }
  649. if (animID == UUID.Zero)
  650. target.AddAnimation(animation, m_host.UUID);
  651. else
  652. target.AddAnimation(animID, m_host.UUID);
  653. }
  654. }
  655. }
  656. public void osAvatarStopAnimation(string avatar, string animation)
  657. {
  658. CheckThreatLevel(ThreatLevel.VeryHigh, "osAvatarStopAnimation");
  659. UUID avatarID = (UUID)avatar;
  660. m_host.AddScriptLPS(1);
  661. if (World.Entities.ContainsKey(avatarID) && World.Entities[avatarID] is ScenePresence)
  662. {
  663. ScenePresence target = (ScenePresence)World.Entities[avatarID];
  664. if (target != null)
  665. {
  666. UUID animID=UUID.Zero;
  667. lock (m_host.TaskInventory)
  668. {
  669. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  670. {
  671. if (inv.Value.Name == animation)
  672. {
  673. if (inv.Value.Type == (int)AssetType.Animation)
  674. animID = inv.Value.AssetID;
  675. continue;
  676. }
  677. }
  678. }
  679. if (animID == UUID.Zero)
  680. target.RemoveAnimation(animation);
  681. else
  682. target.RemoveAnimation(animID);
  683. }
  684. }
  685. }
  686. //Texture draw functions
  687. public string osMovePen(string drawList, int x, int y)
  688. {
  689. CheckThreatLevel(ThreatLevel.None, "osMovePen");
  690. m_host.AddScriptLPS(1);
  691. drawList += "MoveTo " + x + "," + y + ";";
  692. return drawList;
  693. }
  694. public string osDrawLine(string drawList, int startX, int startY, int endX, int endY)
  695. {
  696. CheckThreatLevel(ThreatLevel.None, "osDrawLine");
  697. m_host.AddScriptLPS(1);
  698. drawList += "MoveTo "+ startX+","+ startY +"; LineTo "+endX +","+endY +"; ";
  699. return drawList;
  700. }
  701. public string osDrawLine(string drawList, int endX, int endY)
  702. {
  703. CheckThreatLevel(ThreatLevel.None, "osDrawLine");
  704. m_host.AddScriptLPS(1);
  705. drawList += "LineTo " + endX + "," + endY + "; ";
  706. return drawList;
  707. }
  708. public string osDrawText(string drawList, string text)
  709. {
  710. CheckThreatLevel(ThreatLevel.None, "osDrawText");
  711. m_host.AddScriptLPS(1);
  712. drawList += "Text " + text + "; ";
  713. return drawList;
  714. }
  715. public string osDrawEllipse(string drawList, int width, int height)
  716. {
  717. CheckThreatLevel(ThreatLevel.None, "osDrawEllipse");
  718. m_host.AddScriptLPS(1);
  719. drawList += "Ellipse " + width + "," + height + "; ";
  720. return drawList;
  721. }
  722. public string osDrawRectangle(string drawList, int width, int height)
  723. {
  724. CheckThreatLevel(ThreatLevel.None, "osDrawRectangle");
  725. m_host.AddScriptLPS(1);
  726. drawList += "Rectangle " + width + "," + height + "; ";
  727. return drawList;
  728. }
  729. public string osDrawFilledRectangle(string drawList, int width, int height)
  730. {
  731. CheckThreatLevel(ThreatLevel.None, "osDrawFilledRectangle");
  732. m_host.AddScriptLPS(1);
  733. drawList += "FillRectangle " + width + "," + height + "; ";
  734. return drawList;
  735. }
  736. public string osSetFontSize(string drawList, int fontSize)
  737. {
  738. CheckThreatLevel(ThreatLevel.None, "osSetFontSize");
  739. m_host.AddScriptLPS(1);
  740. drawList += "FontSize "+ fontSize +"; ";
  741. return drawList;
  742. }
  743. public string osSetPenSize(string drawList, int penSize)
  744. {
  745. CheckThreatLevel(ThreatLevel.None, "osSetPenSize");
  746. m_host.AddScriptLPS(1);
  747. drawList += "PenSize " + penSize + "; ";
  748. return drawList;
  749. }
  750. public string osSetPenColour(string drawList, string colour)
  751. {
  752. CheckThreatLevel(ThreatLevel.None, "osSetPenColour");
  753. m_host.AddScriptLPS(1);
  754. drawList += "PenColour " + colour + "; ";
  755. return drawList;
  756. }
  757. public string osDrawImage(string drawList, int width, int height, string imageUrl)
  758. {
  759. CheckThreatLevel(ThreatLevel.None, "osDrawImage");
  760. m_host.AddScriptLPS(1);
  761. drawList +="Image " +width + "," + height+ ","+ imageUrl +"; " ;
  762. return drawList;
  763. }
  764. public LSL_Vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize)
  765. {
  766. CheckThreatLevel(ThreatLevel.VeryLow, "osGetDrawStringSize");
  767. m_host.AddScriptLPS(1);
  768. LSL_Vector vec = new LSL_Vector(0,0,0);
  769. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  770. if (textureManager != null)
  771. {
  772. double xSize, ySize;
  773. textureManager.GetDrawStringSize(contentType, text, fontName, fontSize,
  774. out xSize, out ySize);
  775. vec.x = xSize;
  776. vec.y = ySize;
  777. }
  778. return vec;
  779. }
  780. public void osSetStateEvents(int events)
  781. {
  782. // This function is a hack. There is no reason for it's existence
  783. // anymore, since state events now work properly.
  784. // It was probably added as a crutch or debugging aid, and
  785. // should be removed
  786. //
  787. CheckThreatLevel(ThreatLevel.High, "osSetStateEvents");
  788. m_host.SetScriptEvents(m_itemID, events);
  789. }
  790. public void osSetRegionWaterHeight(double height)
  791. {
  792. CheckThreatLevel(ThreatLevel.High, "osSetRegionWaterHeight");
  793. m_host.AddScriptLPS(1);
  794. //Check to make sure that the script's owner is the estate manager/master
  795. //World.Permissions.GenericEstatePermission(
  796. if (World.Permissions.IsGod(m_host.OwnerID))
  797. {
  798. World.EventManager.TriggerRequestChangeWaterHeight((float)height);
  799. }
  800. }
  801. /// <summary>
  802. /// Changes the Region Sun Settings, then Triggers a Sun Update
  803. /// </summary>
  804. /// <param name="useEstateSun">True to use Estate Sun instead of Region Sun</param>
  805. /// <param name="sunFixed">True to keep the sun stationary</param>
  806. /// <param name="sunHour">The "Sun Hour" that is desired, 0...24, with 0 just after SunRise</param>
  807. public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour)
  808. {
  809. CheckThreatLevel(ThreatLevel.Nuisance, "osSetRegionSunSettings");
  810. m_host.AddScriptLPS(1);
  811. //Check to make sure that the script's owner is the estate manager/master
  812. //World.Permissions.GenericEstatePermission(
  813. if (World.Permissions.IsGod(m_host.OwnerID))
  814. {
  815. while (sunHour > 24.0)
  816. sunHour -= 24.0;
  817. while (sunHour < 0)
  818. sunHour += 24.0;
  819. World.RegionInfo.RegionSettings.UseEstateSun = useEstateSun;
  820. World.RegionInfo.RegionSettings.SunPosition = sunHour + 6; // LL Region Sun Hour is 6 to 30
  821. World.RegionInfo.RegionSettings.FixedSun = sunFixed;
  822. World.RegionInfo.RegionSettings.Save();
  823. World.EventManager.TriggerEstateToolsSunUpdate(World.RegionInfo.RegionHandle, sunFixed, useEstateSun, (float)sunHour);
  824. }
  825. }
  826. /// <summary>
  827. /// Changes the Estate Sun Settings, then Triggers a Sun Update
  828. /// </summary>
  829. /// <param name="sunFixed">True to keep the sun stationary, false to use global time</param>
  830. /// <param name="sunHour">The "Sun Hour" that is desired, 0...24, with 0 just after SunRise</param>
  831. public void osSetEstateSunSettings(bool sunFixed, double sunHour)
  832. {
  833. CheckThreatLevel(ThreatLevel.Nuisance, "osSetEstateSunSettings");
  834. m_host.AddScriptLPS(1);
  835. //Check to make sure that the script's owner is the estate manager/master
  836. //World.Permissions.GenericEstatePermission(
  837. if (World.Permissions.IsGod(m_host.OwnerID))
  838. {
  839. while (sunHour > 24.0)
  840. sunHour -= 24.0;
  841. while (sunHour < 0)
  842. sunHour += 24.0;
  843. World.RegionInfo.EstateSettings.UseGlobalTime = !sunFixed;
  844. World.RegionInfo.EstateSettings.SunPosition = sunHour;
  845. World.RegionInfo.EstateSettings.FixedSun = sunFixed;
  846. World.RegionInfo.EstateSettings.Save();
  847. World.EventManager.TriggerEstateToolsSunUpdate(World.RegionInfo.RegionHandle, sunFixed, World.RegionInfo.RegionSettings.UseEstateSun, (float)sunHour);
  848. }
  849. }
  850. /// <summary>
  851. /// Return the current Sun Hour 0...24, with 0 being roughly sun-rise
  852. /// </summary>
  853. /// <returns></returns>
  854. public double osGetCurrentSunHour()
  855. {
  856. CheckThreatLevel(ThreatLevel.None, "osGetCurrentSunHour");
  857. m_host.AddScriptLPS(1);
  858. // Must adjust for the fact that Region Sun Settings are still LL offset
  859. double sunHour = World.RegionInfo.RegionSettings.SunPosition - 6;
  860. // See if the sun module has registered itself, if so it's authoritative
  861. ISunModule module = World.RequestModuleInterface<ISunModule>();
  862. if (module != null)
  863. {
  864. sunHour = module.GetCurrentSunHour();
  865. }
  866. return sunHour;
  867. }
  868. public double osSunGetParam(string param)
  869. {
  870. CheckThreatLevel(ThreatLevel.None, "osSunGetParam");
  871. m_host.AddScriptLPS(1);
  872. double value = 0.0;
  873. ISunModule module = World.RequestModuleInterface<ISunModule>();
  874. if (module != null)
  875. {
  876. value = module.GetSunParameter(param);
  877. }
  878. return value;
  879. }
  880. public void osSunSetParam(string param, double value)
  881. {
  882. CheckThreatLevel(ThreatLevel.None, "osSunSetParam");
  883. m_host.AddScriptLPS(1);
  884. ISunModule module = World.RequestModuleInterface<ISunModule>();
  885. if (module != null)
  886. {
  887. module.SetSunParameter(param, value);
  888. }
  889. }
  890. public string osWindActiveModelPluginName()
  891. {
  892. CheckThreatLevel(ThreatLevel.None, "osWindActiveModelPluginName");
  893. m_host.AddScriptLPS(1);
  894. IWindModule module = World.RequestModuleInterface<IWindModule>();
  895. if (module != null)
  896. {
  897. return module.WindActiveModelPluginName;
  898. }
  899. return String.Empty;
  900. }
  901. public void osWindParamSet(string plugin, string param, float value)
  902. {
  903. CheckThreatLevel(ThreatLevel.VeryLow, "osWindParamSet");
  904. m_host.AddScriptLPS(1);
  905. IWindModule module = World.RequestModuleInterface<IWindModule>();
  906. if (module != null)
  907. {
  908. try
  909. {
  910. module.WindParamSet(plugin, param, value);
  911. }
  912. catch (Exception) { }
  913. }
  914. }
  915. public float osWindParamGet(string plugin, string param)
  916. {
  917. CheckThreatLevel(ThreatLevel.VeryLow, "osWindParamGet");
  918. m_host.AddScriptLPS(1);
  919. IWindModule module = World.RequestModuleInterface<IWindModule>();
  920. if (module != null)
  921. {
  922. return module.WindParamGet(plugin, param);
  923. }
  924. return 0.0f;
  925. }
  926. public double osList2Double(LSL_Types.list src, int index)
  927. {
  928. // There is really no double type in OSSL. C# and other
  929. // have one, but the current implementation of LSL_Types.list
  930. // is not allowed to contain any.
  931. // This really should be removed.
  932. //
  933. CheckThreatLevel(ThreatLevel.None, "osList2Double");
  934. m_host.AddScriptLPS(1);
  935. if (index < 0)
  936. {
  937. index = src.Length + index;
  938. }
  939. if (index >= src.Length)
  940. {
  941. return 0.0;
  942. }
  943. return Convert.ToDouble(src.Data[index]);
  944. }
  945. public void osSetParcelMediaURL(string url)
  946. {
  947. // What actually is the difference to the LL function?
  948. //
  949. CheckThreatLevel(ThreatLevel.VeryLow, "osSetParcelMediaURL");
  950. m_host.AddScriptLPS(1);
  951. ILandObject land
  952. = World.LandChannel.GetLandObject(m_host.AbsolutePosition.X, m_host.AbsolutePosition.Y);
  953. if (land.landData.OwnerID != m_host.ObjectOwner)
  954. return;
  955. land.SetMediaUrl(url);
  956. }
  957. public string osGetScriptEngineName()
  958. {
  959. // This gets a "high" because knowing the engine may be used
  960. // to exploit engine-specific bugs or induce usage patterns
  961. // that trigger engine-specific failures.
  962. // Besides, public grid users aren't supposed to know.
  963. //
  964. CheckThreatLevel(ThreatLevel.High, "osGetScriptEngineName");
  965. m_host.AddScriptLPS(1);
  966. int scriptEngineNameIndex = 0;
  967. if (!String.IsNullOrEmpty(m_ScriptEngine.ScriptEngineName))
  968. {
  969. // parse off the "ScriptEngine."
  970. scriptEngineNameIndex = m_ScriptEngine.ScriptEngineName.IndexOf(".", scriptEngineNameIndex);
  971. scriptEngineNameIndex++; // get past delimiter
  972. int scriptEngineNameLength = m_ScriptEngine.ScriptEngineName.Length - scriptEngineNameIndex;
  973. // create char array then a string that is only the script engine name
  974. Char[] scriptEngineNameCharArray = m_ScriptEngine.ScriptEngineName.ToCharArray(scriptEngineNameIndex, scriptEngineNameLength);
  975. String scriptEngineName = new String(scriptEngineNameCharArray);
  976. return scriptEngineName;
  977. }
  978. else
  979. {
  980. return String.Empty;
  981. }
  982. }
  983. public string osGetSimulatorVersion()
  984. {
  985. // High because it can be used to target attacks to known weaknesses
  986. // This would allow a new class of griefer scripts that don't even
  987. // require their user to know what they are doing (see script
  988. // kiddie)
  989. //
  990. CheckThreatLevel(ThreatLevel.High,"osGetSimulatorVersion");
  991. m_host.AddScriptLPS(1);
  992. return m_ScriptEngine.World.GetSimulatorVersion();
  993. }
  994. public Hashtable osParseJSON(string JSON)
  995. {
  996. CheckThreatLevel(ThreatLevel.None, "osParseJSON");
  997. m_host.AddScriptLPS(1);
  998. // see http://www.json.org/ for more details on JSON
  999. string currentKey = null;
  1000. Stack objectStack = new Stack(); // objects in JSON can be nested so we need to keep a track of this
  1001. Hashtable jsondata = new Hashtable(); // the hashtable to be returned
  1002. int i = 0;
  1003. try
  1004. {
  1005. // iterate through the serialised stream of tokens and store at the right depth in the hashtable
  1006. // the top level hashtable may contain more nested hashtables within it each containing an objects representation
  1007. for (i = 0; i < JSON.Length; i++)
  1008. {
  1009. // m_log.Debug(""+JSON[i]);
  1010. switch (JSON[i])
  1011. {
  1012. case '{':
  1013. // create hashtable and add it to the stack or array if we are populating one, we can have a lot of nested objects in JSON
  1014. Hashtable currentObject = new Hashtable();
  1015. if (objectStack.Count == 0) // the stack should only be empty for the first outer object
  1016. {
  1017. objectStack.Push(jsondata);
  1018. }
  1019. else if (objectStack.Peek().ToString() == "System.Collections.ArrayList")
  1020. {
  1021. // add it to the parent array
  1022. ((ArrayList)objectStack.Peek()).Add(currentObject);
  1023. objectStack.Push(currentObject);
  1024. }
  1025. else
  1026. {
  1027. // add it to the parent hashtable
  1028. ((Hashtable)objectStack.Peek()).Add(currentKey,currentObject);
  1029. objectStack.Push(currentObject);
  1030. }
  1031. // clear the key
  1032. currentKey = null;
  1033. break;
  1034. case '}':
  1035. // pop the hashtable off the stack
  1036. objectStack.Pop();
  1037. break;
  1038. case '"':// string boundary
  1039. string tokenValue = "";
  1040. i++; // move to next char
  1041. // just loop through until the next quote mark storing the string, ignore quotes with pre-ceding \
  1042. while (JSON[i] != '"')
  1043. {
  1044. tokenValue += JSON[i];
  1045. // handle escaped double quotes \"
  1046. if (JSON[i] == '\\' && JSON[i+1] == '"')
  1047. {
  1048. tokenValue += JSON[i+1];
  1049. i++;
  1050. }
  1051. i++;
  1052. }
  1053. // ok we've got a string, if we've got an array on the top of the stack then we store it
  1054. if (objectStack.Peek().ToString() == "System.Collections.ArrayList")
  1055. {
  1056. ((ArrayList)objectStack.Peek()).Add(tokenValue);
  1057. }
  1058. else if (currentKey == null) // no key stored and its not an array this must be a key so store it
  1059. {
  1060. currentKey = tokenValue;
  1061. }
  1062. else
  1063. {
  1064. // we have a key so lets store this value
  1065. ((Hashtable)objectStack.Peek()).Add(currentKey,tokenValue);
  1066. // now lets clear the key, we're done with it and moving on
  1067. currentKey = null;
  1068. }
  1069. break;
  1070. case ':':// key : value separator
  1071. // just ignore
  1072. break;
  1073. case ' ':// spaces
  1074. // just ignore
  1075. break;
  1076. case '[': // array start
  1077. ArrayList currentArray = new ArrayList();
  1078. if (objectStack.Peek().ToString() == "System.Collections.ArrayList")
  1079. {
  1080. ((ArrayList)objectStack.Peek()).Add(currentArray);
  1081. }
  1082. else
  1083. {
  1084. ((Hashtable)objectStack.Peek()).Add(currentKey,currentArray);
  1085. // clear the key
  1086. currentKey = null;
  1087. }
  1088. objectStack.Push(currentArray);
  1089. break;
  1090. case ',':// seperator
  1091. // just ignore
  1092. break;
  1093. case ']'://Array end
  1094. // pop the array off the stack
  1095. objectStack.Pop();
  1096. break;
  1097. case 't': // we've found a character start not in quotes, it must be a boolean true
  1098. if (objectStack.Peek().ToString() == "System.Collections.ArrayList")
  1099. {
  1100. ((ArrayList)objectStack.Peek()).Add(true);
  1101. }
  1102. else
  1103. {
  1104. ((Hashtable)objectStack.Peek()).Add(currentKey,true);
  1105. currentKey = null;
  1106. }
  1107. //advance the counter to the letter 'e'
  1108. i = i + 3;
  1109. break;
  1110. case 'f': // we've found a character start not in quotes, it must be a boolean false
  1111. if (objectStack.Peek().ToString() == "System.Collections.ArrayList")
  1112. {
  1113. ((ArrayList)objectStack.Peek()).Add(false);
  1114. }
  1115. else
  1116. {
  1117. ((Hashtable)objectStack.Peek()).Add(currentKey,false);
  1118. currentKey = null;
  1119. }
  1120. //advance the counter to the letter 'e'
  1121. i = i + 4;
  1122. break;
  1123. case '\n':// carriage return
  1124. // just ignore
  1125. break;
  1126. case '\r':// carriage return
  1127. // just ignore
  1128. break;
  1129. default:
  1130. // ok here we're catching all numeric types int,double,long we might want to spit these up mr accurately
  1131. // but for now we'll just do them as strings
  1132. string numberValue = "";
  1133. // just loop through until the next known marker quote mark storing the string
  1134. while (JSON[i] != '"' && JSON[i] != ',' && JSON[i] != ']' && JSON[i] != '}' && JSON[i] != ' ')
  1135. {
  1136. numberValue += "" + JSON[i++];
  1137. }
  1138. i--; // we want to process this caracter that marked the end of this string in the main loop
  1139. // ok we've got a string, if we've got an array on the top of the stack then we store it
  1140. if (objectStack.Peek().ToString() == "System.Collections.ArrayList")
  1141. {
  1142. ((ArrayList)objectStack.Peek()).Add(numberValue);
  1143. }
  1144. else
  1145. {
  1146. // we have a key so lets store this value
  1147. ((Hashtable)objectStack.Peek()).Add(currentKey,numberValue);
  1148. // now lets clear the key, we're done with it and moving on
  1149. currentKey = null;
  1150. }
  1151. break;
  1152. }
  1153. }
  1154. }
  1155. catch(Exception)
  1156. {
  1157. OSSLError("osParseJSON: The JSON string is not valid " + JSON) ;
  1158. }
  1159. return jsondata;
  1160. }
  1161. // send a message to to object identified by the given UUID, a script in the object must implement the dataserver function
  1162. // the dataserver function is passed the ID of the calling function and a string message
  1163. public void osMessageObject(LSL_Key objectUUID, string message)
  1164. {
  1165. CheckThreatLevel(ThreatLevel.Low, "osMessageObject");
  1166. m_host.AddScriptLPS(1);
  1167. object[] resobj = new object[] { new LSL_Types.LSLString(m_host.UUID.ToString()), new LSL_Types.LSLString(message) };
  1168. SceneObjectPart sceneOP = World.GetSceneObjectPart(new UUID(objectUUID));
  1169. m_ScriptEngine.PostObjectEvent(
  1170. sceneOP.LocalId, new EventParams(
  1171. "dataserver", resobj, new DetectParams[0]));
  1172. }
  1173. // This needs ThreatLevel high. It is an excellent griefer tool,
  1174. // In a loop, it can cause asset bloat and DOS levels of asset
  1175. // writes.
  1176. //
  1177. public void osMakeNotecard(string notecardName, LSL_Types.list contents)
  1178. {
  1179. CheckThreatLevel(ThreatLevel.High, "osMakeNotecard");
  1180. m_host.AddScriptLPS(1);
  1181. // Create new asset
  1182. AssetBase asset = new AssetBase();
  1183. asset.Name = notecardName;
  1184. asset.Description = "Script Generated Notecard";
  1185. asset.Type = 7;
  1186. asset.FullID = UUID.Random();
  1187. string notecardData = "";
  1188. for (int i = 0; i < contents.Length; i++) {
  1189. notecardData += contents.GetLSLStringItem(i) + "\n";
  1190. }
  1191. int textLength = notecardData.Length;
  1192. notecardData = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length "
  1193. + textLength.ToString() + "\n" + notecardData + "}\n";
  1194. asset.Data = Encoding.ASCII.GetBytes(notecardData);
  1195. World.AssetService.Store(asset);
  1196. // Create Task Entry
  1197. TaskInventoryItem taskItem=new TaskInventoryItem();
  1198. taskItem.ResetIDs(m_host.UUID);
  1199. taskItem.ParentID = m_host.UUID;
  1200. taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch();
  1201. taskItem.Name = asset.Name;
  1202. taskItem.Description = asset.Description;
  1203. taskItem.Type = (int)AssetType.Notecard;
  1204. taskItem.InvType = (int)InventoryType.Notecard;
  1205. taskItem.OwnerID = m_host.OwnerID;
  1206. taskItem.CreatorID = m_host.OwnerID;
  1207. taskItem.BasePermissions = (uint)PermissionMask.All;
  1208. taskItem.CurrentPermissions = (uint)PermissionMask.All;
  1209. taskItem.EveryonePermissions = 0;
  1210. taskItem.NextPermissions = (uint)PermissionMask.All;
  1211. taskItem.GroupID = m_host.GroupID;
  1212. taskItem.GroupPermissions = 0;
  1213. taskItem.Flags = 0;
  1214. taskItem.PermsGranter = UUID.Zero;
  1215. taskItem.PermsMask = 0;
  1216. taskItem.AssetID = asset.FullID;
  1217. m_host.Inventory.AddInventoryItem(taskItem, false);
  1218. }
  1219. /*Instead of using the LSL Dataserver event to pull notecard data,
  1220. this will simply read the requested line and return its data as a string.
  1221. Warning - due to the synchronous method this function uses to fetch assets, its use
  1222. may be dangerous and unreliable while running in grid mode.
  1223. */
  1224. public string osGetNotecardLine(string name, int line)
  1225. {
  1226. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNotecardLine");
  1227. m_host.AddScriptLPS(1);
  1228. UUID assetID = UUID.Zero;
  1229. if (!UUID.TryParse(name, out assetID))
  1230. {
  1231. foreach (TaskInventoryItem item in m_host.TaskInventory.Values)
  1232. {
  1233. if (item.Type == 7 && item.Name == name)
  1234. {
  1235. assetID = item.AssetID;
  1236. }
  1237. }
  1238. }
  1239. if (assetID == UUID.Zero)
  1240. {
  1241. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1242. return "ERROR!";
  1243. }
  1244. if (!NotecardCache.IsCached(assetID))
  1245. {
  1246. AssetBase a = World.AssetService.Get(assetID.ToString());
  1247. if (a != null)
  1248. {
  1249. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1250. string data = enc.GetString(a.Data);
  1251. NotecardCache.Cache(assetID, data);
  1252. }
  1253. else
  1254. {
  1255. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1256. return "ERROR!";
  1257. }
  1258. };
  1259. return NotecardCache.GetLine(assetID, line, 255);
  1260. }
  1261. /*Instead of using the LSL Dataserver event to pull notecard data line by line,
  1262. this will simply read the entire notecard and return its data as a string.
  1263. Warning - due to the synchronous method this function uses to fetch assets, its use
  1264. may be dangerous and unreliable while running in grid mode.
  1265. */
  1266. public string osGetNotecard(string name)
  1267. {
  1268. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNotecard");
  1269. m_host.AddScriptLPS(1);
  1270. UUID assetID = UUID.Zero;
  1271. string NotecardData = "";
  1272. if (!UUID.TryParse(name, out assetID))
  1273. {
  1274. foreach (TaskInventoryItem item in m_host.TaskInventory.Values)
  1275. {
  1276. if (item.Type == 7 && item.Name == name)
  1277. {
  1278. assetID = item.AssetID;
  1279. }
  1280. }
  1281. }
  1282. if (assetID == UUID.Zero)
  1283. {
  1284. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1285. return "ERROR!";
  1286. }
  1287. if (!NotecardCache.IsCached(assetID))
  1288. {
  1289. AssetBase a = World.AssetService.Get(assetID.ToString());
  1290. if (a != null)
  1291. {
  1292. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1293. string data = enc.GetString(a.Data);
  1294. NotecardCache.Cache(assetID, data);
  1295. }
  1296. else
  1297. {
  1298. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1299. return "ERROR!";
  1300. }
  1301. };
  1302. for (int count = 0; count < NotecardCache.GetLines(assetID); count++)
  1303. {
  1304. NotecardData += NotecardCache.GetLine(assetID, count, 255) + "\n";
  1305. }
  1306. return NotecardData;
  1307. }
  1308. /*Instead of using the LSL Dataserver event to pull notecard data,
  1309. this will simply read the number of note card lines and return this data as an integer.
  1310. Warning - due to the synchronous method this function uses to fetch assets, its use
  1311. may be dangerous and unreliable while running in grid mode.
  1312. */
  1313. public int osGetNumberOfNotecardLines(string name)
  1314. {
  1315. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNumberOfNotecardLines");
  1316. m_host.AddScriptLPS(1);
  1317. UUID assetID = UUID.Zero;
  1318. if (!UUID.TryParse(name, out assetID))
  1319. {
  1320. foreach (TaskInventoryItem item in m_host.TaskInventory.Values)
  1321. {
  1322. if (item.Type == 7 && item.Name == name)
  1323. {
  1324. assetID = item.AssetID;
  1325. }
  1326. }
  1327. }
  1328. if (assetID == UUID.Zero)
  1329. {
  1330. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1331. return -1;
  1332. }
  1333. if (!NotecardCache.IsCached(assetID))
  1334. {
  1335. AssetBase a = World.AssetService.Get(assetID.ToString());
  1336. if (a != null)
  1337. {
  1338. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1339. string data = enc.GetString(a.Data);
  1340. NotecardCache.Cache(assetID, data);
  1341. }
  1342. else
  1343. {
  1344. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1345. return -1;
  1346. }
  1347. };
  1348. return NotecardCache.GetLines(assetID);
  1349. }
  1350. public string osAvatarName2Key(string firstname, string lastname)
  1351. {
  1352. CheckThreatLevel(ThreatLevel.Low, "osAvatarName2Key");
  1353. CachedUserInfo userInfo = World.CommsManager.UserProfileCacheService.GetUserDetails(firstname, lastname);
  1354. if (null == userInfo)
  1355. {
  1356. return UUID.Zero.ToString();
  1357. }
  1358. else
  1359. {
  1360. return userInfo.UserProfile.ID.ToString();
  1361. }
  1362. }
  1363. public string osKey2Name(string id)
  1364. {
  1365. CheckThreatLevel(ThreatLevel.Low, "osKey2Name");
  1366. UUID key = new UUID();
  1367. if (UUID.TryParse(id, out key))
  1368. {
  1369. CachedUserInfo userInfo = World.CommsManager.UserProfileCacheService.GetUserDetails(key);
  1370. if (null == userInfo)
  1371. {
  1372. return "";
  1373. }
  1374. else
  1375. {
  1376. return userInfo.UserProfile.Name;
  1377. }
  1378. }
  1379. else
  1380. {
  1381. return "";
  1382. }
  1383. }
  1384. /// Threat level is Moderate because intentional abuse, for instance
  1385. /// scripts that are written to be malicious only on one grid,
  1386. /// for instance in a HG scenario, are a distinct possibility.
  1387. ///
  1388. /// Use value from the config file and return it.
  1389. ///
  1390. public string osGetGridNick()
  1391. {
  1392. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridNick");
  1393. m_host.AddScriptLPS(1);
  1394. string nick = "hippogrid";
  1395. IConfigSource config = new IniConfigSource(Application.iniFilePath);
  1396. if (config.Configs["GridInfo"] != null)
  1397. nick = config.Configs["GridInfo"].GetString("gridnick", nick);
  1398. return nick;
  1399. }
  1400. public string osGetGridName()
  1401. {
  1402. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridName");
  1403. m_host.AddScriptLPS(1);
  1404. string name = "the lost continent of hippo";
  1405. IConfigSource config = new IniConfigSource(Application.iniFilePath);
  1406. if (config.Configs["GridInfo"] != null)
  1407. name = config.Configs["GridInfo"].GetString("gridname", name);
  1408. return name;
  1409. }
  1410. public string osGetGridLoginURI()
  1411. {
  1412. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridLoginURI");
  1413. m_host.AddScriptLPS(1);
  1414. string loginURI = "http://127.0.0.1:9000/";
  1415. IConfigSource config = new IniConfigSource(Application.iniFilePath);
  1416. if (config.Configs["GridInfo"] != null)
  1417. loginURI = config.Configs["GridInfo"].GetString("login", loginURI);
  1418. return loginURI;
  1419. }
  1420. public LSL_String osFormatString(string str, LSL_List strings)
  1421. {
  1422. CheckThreatLevel(ThreatLevel.Low, "osFormatString");
  1423. m_host.AddScriptLPS(1);
  1424. return String.Format(str, strings.Data);
  1425. }
  1426. public LSL_List osMatchString(string src, string pattern, int start)
  1427. {
  1428. CheckThreatLevel(ThreatLevel.High, "osMatchString");
  1429. m_host.AddScriptLPS(1);
  1430. LSL_List result = new LSL_List();
  1431. // Normalize indices (if negative).
  1432. // After normlaization they may still be
  1433. // negative, but that is now relative to
  1434. // the start, rather than the end, of the
  1435. // sequence.
  1436. if (start < 0)
  1437. {
  1438. start = src.Length + start;
  1439. }
  1440. if (start < 0 || start >= src.Length)
  1441. {
  1442. return result; // empty list
  1443. }
  1444. // Find matches beginning at start position
  1445. Regex matcher = new Regex(pattern);
  1446. Match match = matcher.Match(src, start);
  1447. if (match.Success)
  1448. {
  1449. foreach (System.Text.RegularExpressions.Group g in match.Groups)
  1450. {
  1451. if (g.Success)
  1452. {
  1453. result.Add(g.Value);
  1454. result.Add(g.Index);
  1455. }
  1456. }
  1457. }
  1458. return result;
  1459. }
  1460. public string osLoadedCreationDate()
  1461. {
  1462. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationDate");
  1463. m_host.AddScriptLPS(1);
  1464. return World.RegionInfo.RegionSettings.LoadedCreationDate;
  1465. }
  1466. public string osLoadedCreationTime()
  1467. {
  1468. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationTime");
  1469. m_host.AddScriptLPS(1);
  1470. return World.RegionInfo.RegionSettings.LoadedCreationTime;
  1471. }
  1472. public string osLoadedCreationID()
  1473. {
  1474. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationID");
  1475. m_host.AddScriptLPS(1);
  1476. return World.RegionInfo.RegionSettings.LoadedCreationID;
  1477. }
  1478. // Threat level is 'Low' because certain users could possibly be tricked into
  1479. // dropping an unverified script into one of their own objects, which could
  1480. // then gather the physical construction details of the object and transmit it
  1481. // to an unscrupulous third party, thus permitting unauthorized duplication of
  1482. // the object's form.
  1483. //
  1484. public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules)
  1485. {
  1486. CheckThreatLevel(ThreatLevel.High, "osGetLinkPrimitiveParams");
  1487. m_host.AddScriptLPS(1);
  1488. InitLSL();
  1489. LSL_List retVal = new LSL_List();
  1490. List<SceneObjectPart> parts = ((LSL_Api)m_LSL_Api).GetLinkParts(linknumber);
  1491. foreach (SceneObjectPart part in parts)
  1492. {
  1493. retVal += ((LSL_Api)m_LSL_Api).GetLinkPrimitiveParams(part, rules);
  1494. }
  1495. return retVal;
  1496. }
  1497. }
  1498. }