OSSL_Api.cs 146 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012
  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.IO;
  31. using System.Reflection;
  32. using System.Runtime.Remoting.Lifetime;
  33. using System.Text;
  34. using System.Net;
  35. using System.Threading;
  36. using System.Xml;
  37. using log4net;
  38. using OpenMetaverse;
  39. using OpenMetaverse.StructuredData;
  40. using Nini.Config;
  41. using OpenSim;
  42. using OpenSim.Framework;
  43. using OpenSim.Framework.Console;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. using OpenSim.Region.ScriptEngine.Shared;
  47. using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
  48. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  49. using OpenSim.Region.ScriptEngine.Interfaces;
  50. using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
  51. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  52. using OpenSim.Services.Interfaces;
  53. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  54. using System.Text.RegularExpressions;
  55. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  56. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  57. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  58. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  59. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  60. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  61. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  62. using PermissionMask = OpenSim.Framework.PermissionMask;
  63. using OpenSim.Services.Connectors.Hypergrid;
  64. namespace OpenSim.Region.ScriptEngine.Shared.Api
  65. {
  66. //////////////////////////////////////////////////////////////
  67. //
  68. // Level description
  69. //
  70. // None - Function is no threat at all. It doesn't constitute
  71. // an threat to either users or the system and has no
  72. // known side effects
  73. //
  74. // Nuisance - Abuse of this command can cause a nuisance to the
  75. // region operator, such as log message spew
  76. //
  77. // VeryLow - Extreme levels ob abuse of this function can cause
  78. // impaired functioning of the region, or very gullible
  79. // users can be tricked into experiencing harmless effects
  80. //
  81. // Low - Intentional abuse can cause crashes or malfunction
  82. // under certain circumstances, which can easily be rectified,
  83. // or certain users can be tricked into certain situations
  84. // in an avoidable manner.
  85. //
  86. // Moderate - Intentional abuse can cause denial of service and crashes
  87. // with potential of data or state loss, or trusting users
  88. // can be tricked into embarrassing or uncomfortable
  89. // situationsa.
  90. //
  91. // High - Casual abuse can cause impaired functionality or temporary
  92. // denial of service conditions. Intentional abuse can easily
  93. // cause crashes with potential data loss, or can be used to
  94. // trick experienced and cautious users into unwanted situations,
  95. // or changes global data permanently and without undo ability
  96. // Malicious scripting can allow theft of content
  97. //
  98. // VeryHigh - Even normal use may, depending on the number of instances,
  99. // or frequency of use, result in severe service impairment
  100. // or crash with loss of data, or can be used to cause
  101. // unwanted or harmful effects on users without giving the
  102. // user a means to avoid it.
  103. //
  104. // Severe - Even casual use is a danger to region stability, or function
  105. // allows console or OS command execution, or function allows
  106. // taking money without consent, or allows deletion or
  107. // modification of user data, or allows the compromise of
  108. // sensitive data by design.
  109. class FunctionPerms
  110. {
  111. public List<UUID> AllowedCreators;
  112. public List<UUID> AllowedOwners;
  113. public List<string> AllowedOwnerClasses;
  114. public FunctionPerms()
  115. {
  116. AllowedCreators = new List<UUID>();
  117. AllowedOwners = new List<UUID>();
  118. AllowedOwnerClasses = new List<string>();
  119. }
  120. }
  121. [Serializable]
  122. public class OSSL_Api : MarshalByRefObject, IOSSL_Api, IScriptApi
  123. {
  124. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  125. public const string GridInfoServiceConfigSectionName = "GridInfoService";
  126. internal IScriptEngine m_ScriptEngine;
  127. internal ILSL_Api m_LSL_Api = null; // get a reference to the LSL API so we can call methods housed there
  128. internal SceneObjectPart m_host;
  129. internal TaskInventoryItem m_item;
  130. internal bool m_OSFunctionsEnabled = false;
  131. internal ThreatLevel m_MaxThreatLevel = ThreatLevel.VeryLow;
  132. internal float m_ScriptDelayFactor = 1.0f;
  133. internal float m_ScriptDistanceFactor = 1.0f;
  134. internal Dictionary<string, FunctionPerms > m_FunctionPerms = new Dictionary<string, FunctionPerms >();
  135. protected IUrlModule m_UrlModule = null;
  136. public void Initialize(
  137. IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item)
  138. {
  139. m_ScriptEngine = scriptEngine;
  140. m_host = host;
  141. m_item = item;
  142. m_UrlModule = m_ScriptEngine.World.RequestModuleInterface<IUrlModule>();
  143. if (m_ScriptEngine.Config.GetBoolean("AllowOSFunctions", false))
  144. {
  145. m_OSFunctionsEnabled = true;
  146. // m_log.Warn("[OSSL] OSSL FUNCTIONS ENABLED");
  147. }
  148. m_ScriptDelayFactor =
  149. m_ScriptEngine.Config.GetFloat("ScriptDelayFactor", 1.0f);
  150. m_ScriptDistanceFactor =
  151. m_ScriptEngine.Config.GetFloat("ScriptDistanceLimitFactor", 1.0f);
  152. string risk = m_ScriptEngine.Config.GetString("OSFunctionThreatLevel", "VeryLow");
  153. switch (risk)
  154. {
  155. case "NoAccess":
  156. m_MaxThreatLevel = ThreatLevel.NoAccess;
  157. break;
  158. case "None":
  159. m_MaxThreatLevel = ThreatLevel.None;
  160. break;
  161. case "VeryLow":
  162. m_MaxThreatLevel = ThreatLevel.VeryLow;
  163. break;
  164. case "Low":
  165. m_MaxThreatLevel = ThreatLevel.Low;
  166. break;
  167. case "Moderate":
  168. m_MaxThreatLevel = ThreatLevel.Moderate;
  169. break;
  170. case "High":
  171. m_MaxThreatLevel = ThreatLevel.High;
  172. break;
  173. case "VeryHigh":
  174. m_MaxThreatLevel = ThreatLevel.VeryHigh;
  175. break;
  176. case "Severe":
  177. m_MaxThreatLevel = ThreatLevel.Severe;
  178. break;
  179. default:
  180. break;
  181. }
  182. }
  183. public override Object InitializeLifetimeService()
  184. {
  185. ILease lease = (ILease)base.InitializeLifetimeService();
  186. if (lease.CurrentState == LeaseState.Initial)
  187. {
  188. lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
  189. // lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
  190. // lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
  191. }
  192. return lease;
  193. }
  194. public Scene World
  195. {
  196. get { return m_ScriptEngine.World; }
  197. }
  198. internal void OSSLError(string msg)
  199. {
  200. throw new ScriptException("OSSL Runtime Error: " + msg);
  201. }
  202. /// <summary>
  203. /// Initialize the LSL interface.
  204. /// </summary>
  205. /// <remarks>
  206. /// FIXME: This is an abomination. We should be able to set this up earlier but currently we have no
  207. /// guarantee the interface is present on Initialize(). There needs to be another post initialize call from
  208. /// ScriptInstance.
  209. /// </remarks>
  210. private void InitLSL()
  211. {
  212. if (m_LSL_Api != null)
  213. return;
  214. m_LSL_Api = (ILSL_Api)m_ScriptEngine.GetApi(m_item.ItemID, "LSL");
  215. }
  216. //
  217. //Dumps an error message on the debug console.
  218. //
  219. internal void OSSLShoutError(string message)
  220. {
  221. if (message.Length > 1023)
  222. message = message.Substring(0, 1023);
  223. World.SimChat(Utils.StringToBytes(message),
  224. ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, true);
  225. IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
  226. wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message);
  227. }
  228. // Returns of the function is allowed. Throws a script exception if not allowed.
  229. public void CheckThreatLevel(ThreatLevel level, string function)
  230. {
  231. if (!m_OSFunctionsEnabled)
  232. OSSLError(String.Format("{0} permission denied. All OS functions are disabled.", function)); // throws
  233. string reasonWhyNot = CheckThreatLevelTest(level, function);
  234. if (!String.IsNullOrEmpty(reasonWhyNot))
  235. {
  236. OSSLError(reasonWhyNot);
  237. }
  238. }
  239. // Check to see if function is allowed. Returns an empty string if function permitted
  240. // or a string explaining why this function can't be used.
  241. private string CheckThreatLevelTest(ThreatLevel level, string function)
  242. {
  243. if (!m_FunctionPerms.ContainsKey(function))
  244. {
  245. FunctionPerms perms = new FunctionPerms();
  246. m_FunctionPerms[function] = perms;
  247. string ownerPerm = m_ScriptEngine.Config.GetString("Allow_" + function, "");
  248. string creatorPerm = m_ScriptEngine.Config.GetString("Creators_" + function, "");
  249. if (ownerPerm == "" && creatorPerm == "")
  250. {
  251. // Default behavior
  252. perms.AllowedOwners = null;
  253. perms.AllowedCreators = null;
  254. perms.AllowedOwnerClasses = null;
  255. }
  256. else
  257. {
  258. bool allowed;
  259. if (bool.TryParse(ownerPerm, out allowed))
  260. {
  261. // Boolean given
  262. if (allowed)
  263. {
  264. // Allow globally
  265. perms.AllowedOwners.Add(UUID.Zero);
  266. }
  267. }
  268. else
  269. {
  270. string[] ids = ownerPerm.Split(new char[] {','});
  271. foreach (string id in ids)
  272. {
  273. string current = id.Trim();
  274. if (current.ToUpper() == "PARCEL_GROUP_MEMBER" || current.ToUpper() == "PARCEL_OWNER" || current.ToUpper() == "ESTATE_MANAGER" || current.ToUpper() == "ESTATE_OWNER")
  275. {
  276. if (!perms.AllowedOwnerClasses.Contains(current))
  277. perms.AllowedOwnerClasses.Add(current.ToUpper());
  278. }
  279. else
  280. {
  281. UUID uuid;
  282. if (UUID.TryParse(current, out uuid))
  283. {
  284. if (uuid != UUID.Zero)
  285. perms.AllowedOwners.Add(uuid);
  286. }
  287. }
  288. }
  289. ids = creatorPerm.Split(new char[] {','});
  290. foreach (string id in ids)
  291. {
  292. string current = id.Trim();
  293. UUID uuid;
  294. if (UUID.TryParse(current, out uuid))
  295. {
  296. if (uuid != UUID.Zero)
  297. perms.AllowedCreators.Add(uuid);
  298. }
  299. }
  300. }
  301. }
  302. }
  303. // If the list is null, then the value was true / undefined
  304. // Threat level governs permissions in this case
  305. //
  306. // If the list is non-null, then it is a list of UUIDs allowed
  307. // to use that particular function. False causes an empty
  308. // list and therefore means "no one"
  309. //
  310. // To allow use by anyone, the list contains UUID.Zero
  311. //
  312. if (m_FunctionPerms[function].AllowedOwners == null)
  313. {
  314. // Allow / disallow by threat level
  315. if (level > m_MaxThreatLevel)
  316. return
  317. String.Format(
  318. "{0} permission denied. Allowed threat level is {1} but function threat level is {2}.",
  319. function, m_MaxThreatLevel, level);
  320. }
  321. else
  322. {
  323. if (!m_FunctionPerms[function].AllowedOwners.Contains(UUID.Zero))
  324. {
  325. // Not anyone. Do detailed checks
  326. if (m_FunctionPerms[function].AllowedOwners.Contains(m_host.OwnerID))
  327. {
  328. // prim owner is in the list of allowed owners
  329. return String.Empty;
  330. }
  331. UUID ownerID = m_item.OwnerID;
  332. //OSSL only may be used if object is in the same group as the parcel
  333. if (m_FunctionPerms[function].AllowedOwnerClasses.Contains("PARCEL_GROUP_MEMBER"))
  334. {
  335. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  336. if (land.LandData.GroupID == m_item.GroupID && land.LandData.GroupID != UUID.Zero)
  337. {
  338. return String.Empty;
  339. }
  340. }
  341. //Only Parcelowners may use the function
  342. if (m_FunctionPerms[function].AllowedOwnerClasses.Contains("PARCEL_OWNER"))
  343. {
  344. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  345. if (land.LandData.OwnerID == ownerID)
  346. {
  347. return String.Empty;
  348. }
  349. }
  350. //Only Estate Managers may use the function
  351. if (m_FunctionPerms[function].AllowedOwnerClasses.Contains("ESTATE_MANAGER"))
  352. {
  353. //Only Estate Managers may use the function
  354. if (World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(ownerID) && World.RegionInfo.EstateSettings.EstateOwner != ownerID)
  355. {
  356. return String.Empty;
  357. }
  358. }
  359. //Only regionowners may use the function
  360. if (m_FunctionPerms[function].AllowedOwnerClasses.Contains("ESTATE_OWNER"))
  361. {
  362. if (World.RegionInfo.EstateSettings.EstateOwner == ownerID)
  363. {
  364. return String.Empty;
  365. }
  366. }
  367. if (!m_FunctionPerms[function].AllowedCreators.Contains(m_item.CreatorID))
  368. return(
  369. String.Format("{0} permission denied. Script creator is not in the list of users allowed to execute this function and prim owner also has no permission.",
  370. function));
  371. if (m_item.CreatorID != ownerID)
  372. {
  373. if ((m_item.CurrentPermissions & (uint)PermissionMask.Modify) != 0)
  374. return String.Format("{0} permission denied. Script permissions error.", function);
  375. }
  376. }
  377. }
  378. return String.Empty;
  379. }
  380. internal void OSSLDeprecated(string function, string replacement)
  381. {
  382. OSSLShoutError(string.Format("Use of function {0} is deprecated. Use {1} instead.", function, replacement));
  383. }
  384. protected void ScriptSleep(int delay)
  385. {
  386. delay = (int)((float)delay * m_ScriptDelayFactor);
  387. if (delay == 0)
  388. return;
  389. System.Threading.Thread.Sleep(delay);
  390. }
  391. public LSL_Integer osSetTerrainHeight(int x, int y, double val)
  392. {
  393. CheckThreatLevel(ThreatLevel.High, "osSetTerrainHeight");
  394. return SetTerrainHeight(x, y, val);
  395. }
  396. public LSL_Integer osTerrainSetHeight(int x, int y, double val)
  397. {
  398. CheckThreatLevel(ThreatLevel.High, "osTerrainSetHeight");
  399. OSSLDeprecated("osTerrainSetHeight", "osSetTerrainHeight");
  400. return SetTerrainHeight(x, y, val);
  401. }
  402. private LSL_Integer SetTerrainHeight(int x, int y, double val)
  403. {
  404. m_host.AddScriptLPS(1);
  405. if (x > (World.RegionInfo.RegionSizeX - 1) || x < 0 || y > (World.RegionInfo.RegionSizeY - 1) || y < 0)
  406. OSSLError("osSetTerrainHeight: Coordinate out of bounds");
  407. if (World.Permissions.CanTerraformLand(m_host.OwnerID, new Vector3(x, y, 0)))
  408. {
  409. World.Heightmap[x, y] = val;
  410. return 1;
  411. }
  412. else
  413. {
  414. return 0;
  415. }
  416. }
  417. public LSL_Float osGetTerrainHeight(int x, int y)
  418. {
  419. CheckThreatLevel(ThreatLevel.None, "osGetTerrainHeight");
  420. return GetTerrainHeight(x, y);
  421. }
  422. public LSL_Float osTerrainGetHeight(int x, int y)
  423. {
  424. CheckThreatLevel(ThreatLevel.None, "osTerrainGetHeight");
  425. OSSLDeprecated("osTerrainGetHeight", "osGetTerrainHeight");
  426. return GetTerrainHeight(x, y);
  427. }
  428. private LSL_Float GetTerrainHeight(int x, int y)
  429. {
  430. m_host.AddScriptLPS(1);
  431. if (x > (World.RegionInfo.RegionSizeX - 1) || x < 0 || y > (World.RegionInfo.RegionSizeY - 1) || y < 0)
  432. OSSLError("osGetTerrainHeight: Coordinate out of bounds");
  433. return World.Heightmap[x, y];
  434. }
  435. public void osTerrainFlush()
  436. {
  437. CheckThreatLevel(ThreatLevel.VeryLow, "osTerrainFlush");
  438. m_host.AddScriptLPS(1);
  439. ITerrainModule terrainModule = World.RequestModuleInterface<ITerrainModule>();
  440. if (terrainModule != null) terrainModule.TaintTerrain();
  441. }
  442. public int osRegionRestart(double seconds)
  443. {
  444. // This is High here because region restart is not reliable
  445. // it may result in the region staying down or becoming
  446. // unstable. This should be changed to Low or VeryLow once
  447. // The underlying functionality is fixed, since the security
  448. // as such is sound
  449. //
  450. CheckThreatLevel(ThreatLevel.High, "osRegionRestart");
  451. IRestartModule restartModule = World.RequestModuleInterface<IRestartModule>();
  452. m_host.AddScriptLPS(1);
  453. if (World.Permissions.CanIssueEstateCommand(m_host.OwnerID, false) && (restartModule != null))
  454. {
  455. if (seconds < 15)
  456. {
  457. restartModule.AbortRestart("Restart aborted");
  458. return 1;
  459. }
  460. List<int> times = new List<int>();
  461. while (seconds > 0)
  462. {
  463. times.Add((int)seconds);
  464. if (seconds > 300)
  465. seconds -= 120;
  466. else if (seconds > 30)
  467. seconds -= 30;
  468. else
  469. seconds -= 15;
  470. }
  471. restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), true);
  472. return 1;
  473. }
  474. else
  475. {
  476. return 0;
  477. }
  478. }
  479. public void osRegionNotice(string msg)
  480. {
  481. // This implementation provides absolutely no security
  482. // It's high griefing potential makes this classification
  483. // necessary
  484. //
  485. CheckThreatLevel(ThreatLevel.VeryHigh, "osRegionNotice");
  486. m_host.AddScriptLPS(1);
  487. IDialogModule dm = World.RequestModuleInterface<IDialogModule>();
  488. if (dm != null)
  489. dm.SendGeneralAlert(msg);
  490. }
  491. public void osSetRot(UUID target, Quaternion rotation)
  492. {
  493. // This function has no security. It can be used to destroy
  494. // arbitrary builds the user would normally have no rights to
  495. //
  496. CheckThreatLevel(ThreatLevel.VeryHigh, "osSetRot");
  497. m_host.AddScriptLPS(1);
  498. if (World.Entities.ContainsKey(target))
  499. {
  500. EntityBase entity;
  501. if (World.Entities.TryGetValue(target, out entity))
  502. {
  503. if (entity is SceneObjectGroup)
  504. ((SceneObjectGroup)entity).UpdateGroupRotationR(rotation);
  505. else if (entity is ScenePresence)
  506. ((ScenePresence)entity).Rotation = rotation;
  507. }
  508. }
  509. else
  510. {
  511. OSSLError("osSetRot: Invalid target");
  512. }
  513. }
  514. public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams,
  515. int timer)
  516. {
  517. // This may be upgraded depending on the griefing or DOS
  518. // potential, or guarded with a delay
  519. //
  520. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureURL");
  521. m_host.AddScriptLPS(1);
  522. if (dynamicID == String.Empty)
  523. {
  524. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  525. UUID createdTexture =
  526. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  527. extraParams, timer);
  528. return createdTexture.ToString();
  529. }
  530. else
  531. {
  532. //TODO update existing dynamic textures
  533. }
  534. return UUID.Zero.ToString();
  535. }
  536. public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
  537. int timer, int alpha)
  538. {
  539. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureURLBlend");
  540. m_host.AddScriptLPS(1);
  541. if (dynamicID == String.Empty)
  542. {
  543. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  544. UUID createdTexture =
  545. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  546. extraParams, timer, true, (byte) alpha);
  547. return createdTexture.ToString();
  548. }
  549. else
  550. {
  551. //TODO update existing dynamic textures
  552. }
  553. return UUID.Zero.ToString();
  554. }
  555. public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
  556. bool blend, int disp, int timer, int alpha, int face)
  557. {
  558. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureURLBlendFace");
  559. m_host.AddScriptLPS(1);
  560. if (dynamicID == String.Empty)
  561. {
  562. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  563. UUID createdTexture =
  564. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  565. extraParams, timer, blend, disp, (byte) alpha, face);
  566. return createdTexture.ToString();
  567. }
  568. else
  569. {
  570. //TODO update existing dynamic textures
  571. }
  572. return UUID.Zero.ToString();
  573. }
  574. public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams,
  575. int timer)
  576. {
  577. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureData");
  578. m_host.AddScriptLPS(1);
  579. if (dynamicID == String.Empty)
  580. {
  581. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  582. if (textureManager != null)
  583. {
  584. if (extraParams == String.Empty)
  585. {
  586. extraParams = "256";
  587. }
  588. UUID createdTexture =
  589. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  590. extraParams, timer);
  591. return createdTexture.ToString();
  592. }
  593. }
  594. else
  595. {
  596. //TODO update existing dynamic textures
  597. }
  598. return UUID.Zero.ToString();
  599. }
  600. public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
  601. int timer, int alpha)
  602. {
  603. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureDataBlend");
  604. m_host.AddScriptLPS(1);
  605. if (dynamicID == String.Empty)
  606. {
  607. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  608. if (textureManager != null)
  609. {
  610. if (extraParams == String.Empty)
  611. {
  612. extraParams = "256";
  613. }
  614. UUID createdTexture =
  615. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  616. extraParams, timer, true, (byte) alpha);
  617. return createdTexture.ToString();
  618. }
  619. }
  620. else
  621. {
  622. //TODO update existing dynamic textures
  623. }
  624. return UUID.Zero.ToString();
  625. }
  626. public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
  627. bool blend, int disp, int timer, int alpha, int face)
  628. {
  629. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureDataBlendFace");
  630. m_host.AddScriptLPS(1);
  631. if (dynamicID == String.Empty)
  632. {
  633. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  634. if (textureManager != null)
  635. {
  636. if (extraParams == String.Empty)
  637. {
  638. extraParams = "256";
  639. }
  640. UUID createdTexture =
  641. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  642. extraParams, timer, blend, disp, (byte) alpha, face);
  643. return createdTexture.ToString();
  644. }
  645. }
  646. else
  647. {
  648. //TODO update existing dynamic textures
  649. }
  650. return UUID.Zero.ToString();
  651. }
  652. public bool osConsoleCommand(string command)
  653. {
  654. CheckThreatLevel(ThreatLevel.Severe, "osConsoleCommand");
  655. m_host.AddScriptLPS(1);
  656. // For safety, we add another permission check here, and don't rely only on the standard OSSL permissions
  657. if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID))
  658. {
  659. MainConsole.Instance.RunCommand(command);
  660. return true;
  661. }
  662. return false;
  663. }
  664. public void osSetPrimFloatOnWater(int floatYN)
  665. {
  666. CheckThreatLevel(ThreatLevel.VeryLow, "osSetPrimFloatOnWater");
  667. m_host.AddScriptLPS(1);
  668. m_host.ParentGroup.RootPart.SetFloatOnWater(floatYN);
  669. }
  670. // Teleport functions
  671. public void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  672. {
  673. // High because there is no security check. High griefer potential
  674. //
  675. CheckThreatLevel(ThreatLevel.Severe, "osTeleportAgent");
  676. TeleportAgent(agent, regionName, position, lookat, false);
  677. }
  678. private void TeleportAgent(string agent, string regionName,
  679. LSL_Types.Vector3 position, LSL_Types.Vector3 lookat, bool relaxRestrictions)
  680. {
  681. m_host.AddScriptLPS(1);
  682. UUID agentId = new UUID();
  683. if (UUID.TryParse(agent, out agentId))
  684. {
  685. ScenePresence presence = World.GetScenePresence(agentId);
  686. if (presence != null)
  687. {
  688. // For osTeleportAgent, agent must be over owners land to avoid abuse
  689. // For osTeleportOwner, this restriction isn't necessary
  690. // commented out because its redundant and uneeded please remove eventually.
  691. // if (relaxRestrictions ||
  692. // m_host.OwnerID
  693. // == World.LandChannel.GetLandObject(
  694. // presence.AbsolutePosition.X, presence.AbsolutePosition.Y).LandData.OwnerID)
  695. // {
  696. // We will launch the teleport on a new thread so that when the script threads are terminated
  697. // before teleport in ScriptInstance.GetXMLState(), we don't end up aborting the one doing the teleporting.
  698. Util.FireAndForget(
  699. o => World.RequestTeleportLocation(
  700. presence.ControllingClient, regionName, position,
  701. lookat, (uint)TPFlags.ViaLocation),
  702. null, "OSSL_Api.TeleportAgentByRegionCoords");
  703. ScriptSleep(5000);
  704. // }
  705. }
  706. }
  707. }
  708. public void osTeleportAgent(string agent, int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  709. {
  710. // High because there is no security check. High griefer potential
  711. //
  712. CheckThreatLevel(ThreatLevel.Severe, "osTeleportAgent");
  713. TeleportAgent(agent, regionX, regionY, position, lookat, false);
  714. }
  715. private void TeleportAgent(string agent, int regionX, int regionY,
  716. LSL_Types.Vector3 position, LSL_Types.Vector3 lookat, bool relaxRestrictions)
  717. {
  718. // ulong regionHandle = Util.UIntsToLong(((uint)regionX * (uint)Constants.RegionSize), ((uint)regionY * (uint)Constants.RegionSize));
  719. ulong regionHandle = Util.RegionLocToHandle((uint)regionX, (uint)regionY);
  720. m_host.AddScriptLPS(1);
  721. UUID agentId = new UUID();
  722. if (UUID.TryParse(agent, out agentId))
  723. {
  724. ScenePresence presence = World.GetScenePresence(agentId);
  725. if (presence != null)
  726. {
  727. // For osTeleportAgent, agent must be over owners land to avoid abuse
  728. // For osTeleportOwner, this restriction isn't necessary
  729. // commented out because its redundant and uneeded please remove eventually.
  730. // if (relaxRestrictions ||
  731. // m_host.OwnerID
  732. // == World.LandChannel.GetLandObject(
  733. // presence.AbsolutePosition.X, presence.AbsolutePosition.Y).LandData.OwnerID)
  734. // {
  735. // We will launch the teleport on a new thread so that when the script threads are terminated
  736. // before teleport in ScriptInstance.GetXMLState(), we don't end up aborting the one doing the teleporting.
  737. Util.FireAndForget(
  738. o => World.RequestTeleportLocation(
  739. presence.ControllingClient, regionHandle,
  740. position, lookat, (uint)TPFlags.ViaLocation),
  741. null, "OSSL_Api.TeleportAgentByRegionName");
  742. ScriptSleep(5000);
  743. // }
  744. }
  745. }
  746. }
  747. public void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  748. {
  749. osTeleportAgent(agent, World.RegionInfo.RegionName, position, lookat);
  750. }
  751. public void osTeleportOwner(string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  752. {
  753. // Threat level None because this is what can already be done with the World Map in the viewer
  754. CheckThreatLevel(ThreatLevel.None, "osTeleportOwner");
  755. TeleportAgent(m_host.OwnerID.ToString(), regionName, position, lookat, true);
  756. }
  757. public void osTeleportOwner(LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  758. {
  759. osTeleportOwner(World.RegionInfo.RegionName, position, lookat);
  760. }
  761. public void osTeleportOwner(int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  762. {
  763. CheckThreatLevel(ThreatLevel.None, "osTeleportOwner");
  764. TeleportAgent(m_host.OwnerID.ToString(), regionX, regionY, position, lookat, true);
  765. }
  766. ///<summary>
  767. /// Allows a script IN the target prim to force an avatar to sit on it using normal methods
  768. /// as if called by the client.
  769. /// Silent fail if agent (or target if overloaded) not found.
  770. /// Does work if passed key (or keys if overloaded).
  771. /// </summary>
  772. /// <param name="avatar"></param>
  773. public void osForceOtherSit(string avatar)
  774. {
  775. CheckThreatLevel(ThreatLevel.VeryHigh, "osForceOtherSit");
  776. m_host.AddScriptLPS(1);
  777. ForceSit(avatar, m_host.UUID);
  778. }
  779. /// <summary>
  780. /// Overload method of osForceOtherSit(string avatar) to allow a script NOT in the target prim to force
  781. /// an avatar to sit on the target prim using normal methods as if called by the client.
  782. /// </summary>
  783. /// <param name="avatar"></param>
  784. /// <param name="target"></param>
  785. public void osForceOtherSit(string avatar, string target)
  786. {
  787. CheckThreatLevel(ThreatLevel.VeryHigh, "osForceOtherSit");
  788. m_host.AddScriptLPS(1);
  789. UUID targetID = new UUID(target);
  790. ForceSit(avatar, targetID);
  791. }
  792. public void ForceSit(string avatar, UUID targetID)
  793. {
  794. UUID agentID;
  795. if (!UUID.TryParse(avatar, out agentID))
  796. return;
  797. ScenePresence presence = World.GetScenePresence(agentID);
  798. SceneObjectPart part = World.GetSceneObjectPart(targetID);
  799. if (presence != null &&
  800. part != null &&
  801. part.SitTargetAvatar == UUID.Zero)
  802. presence.HandleAgentRequestSit(presence.ControllingClient,
  803. agentID,
  804. targetID,
  805. part.SitTargetPosition);
  806. }
  807. // Functions that get information from the agent itself.
  808. //
  809. // osGetAgentIP - this is used to determine the IP address of
  810. //the client. This is needed to help configure other in world
  811. //resources based on the IP address of the clients connected.
  812. //I think High is a good risk level for this, as it is an
  813. //information leak.
  814. public string osGetAgentIP(string agent)
  815. {
  816. CheckThreatLevel(ThreatLevel.High, "osGetAgentIP");
  817. UUID avatarID = (UUID)agent;
  818. m_host.AddScriptLPS(1);
  819. if (World.Entities.ContainsKey((UUID)agent) && World.Entities[avatarID] is ScenePresence)
  820. {
  821. ScenePresence target = (ScenePresence)World.Entities[avatarID];
  822. return target.ControllingClient.RemoteEndPoint.Address.ToString();
  823. }
  824. // fall through case, just return nothing
  825. return "";
  826. }
  827. // Get a list of all the avatars/agents in the region
  828. public LSL_List osGetAgents()
  829. {
  830. // threat level is None as we could get this information with an
  831. // in-world script as well, just not as efficient
  832. CheckThreatLevel(ThreatLevel.None, "osGetAgents");
  833. m_host.AddScriptLPS(1);
  834. LSL_List result = new LSL_List();
  835. World.ForEachRootScenePresence(delegate(ScenePresence sp)
  836. {
  837. result.Add(new LSL_String(sp.Name));
  838. });
  839. return result;
  840. }
  841. // Adam's super super custom animation functions
  842. public void osAvatarPlayAnimation(string avatar, string animation)
  843. {
  844. CheckThreatLevel(ThreatLevel.VeryHigh, "osAvatarPlayAnimation");
  845. AvatarPlayAnimation(avatar, animation);
  846. }
  847. private void AvatarPlayAnimation(string avatar, string animation)
  848. {
  849. UUID avatarID = (UUID)avatar;
  850. m_host.AddScriptLPS(1);
  851. if (World.Entities.ContainsKey((UUID)avatar) && World.Entities[avatarID] is ScenePresence)
  852. {
  853. ScenePresence target = (ScenePresence)World.Entities[avatarID];
  854. if (target != null)
  855. {
  856. UUID animID=UUID.Zero;
  857. lock (m_host.TaskInventory)
  858. {
  859. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  860. {
  861. if (inv.Value.Name == animation)
  862. {
  863. if (inv.Value.Type == (int)AssetType.Animation)
  864. animID = inv.Value.AssetID;
  865. continue;
  866. }
  867. }
  868. }
  869. if (animID == UUID.Zero)
  870. target.Animator.AddAnimation(animation, m_host.UUID);
  871. else
  872. target.Animator.AddAnimation(animID, m_host.UUID);
  873. }
  874. }
  875. }
  876. public void osAvatarStopAnimation(string avatar, string animation)
  877. {
  878. CheckThreatLevel(ThreatLevel.VeryHigh, "osAvatarStopAnimation");
  879. AvatarStopAnimation(avatar, animation);
  880. }
  881. private void AvatarStopAnimation(string avatar, string animation)
  882. {
  883. UUID avatarID = (UUID)avatar;
  884. m_host.AddScriptLPS(1);
  885. // FIXME: What we really want to do here is factor out the similar code in llStopAnimation() to a common
  886. // method (though see that doesn't do the is animation check, which is probably a bug) and have both
  887. // these functions call that common code. However, this does mean navigating the brain-dead requirement
  888. // of calling InitLSL()
  889. if (World.Entities.ContainsKey(avatarID) && World.Entities[avatarID] is ScenePresence)
  890. {
  891. ScenePresence target = (ScenePresence)World.Entities[avatarID];
  892. if (target != null)
  893. {
  894. UUID animID;
  895. if (!UUID.TryParse(animation, out animID))
  896. {
  897. TaskInventoryItem item = m_host.Inventory.GetInventoryItem(animation);
  898. if (item != null && item.Type == (int)AssetType.Animation)
  899. animID = item.AssetID;
  900. else
  901. animID = UUID.Zero;
  902. }
  903. if (animID == UUID.Zero)
  904. target.Animator.RemoveAnimation(animation);
  905. else
  906. target.Animator.RemoveAnimation(animID, true);
  907. }
  908. }
  909. }
  910. //Texture draw functions
  911. public string osMovePen(string drawList, int x, int y)
  912. {
  913. CheckThreatLevel(ThreatLevel.None, "osMovePen");
  914. m_host.AddScriptLPS(1);
  915. drawList += "MoveTo " + x + "," + y + ";";
  916. return drawList;
  917. }
  918. public string osDrawLine(string drawList, int startX, int startY, int endX, int endY)
  919. {
  920. CheckThreatLevel(ThreatLevel.None, "osDrawLine");
  921. m_host.AddScriptLPS(1);
  922. drawList += "MoveTo "+ startX+","+ startY +"; LineTo "+endX +","+endY +"; ";
  923. return drawList;
  924. }
  925. public string osDrawLine(string drawList, int endX, int endY)
  926. {
  927. CheckThreatLevel(ThreatLevel.None, "osDrawLine");
  928. m_host.AddScriptLPS(1);
  929. drawList += "LineTo " + endX + "," + endY + "; ";
  930. return drawList;
  931. }
  932. public string osDrawText(string drawList, string text)
  933. {
  934. CheckThreatLevel(ThreatLevel.None, "osDrawText");
  935. m_host.AddScriptLPS(1);
  936. drawList += "Text " + text + "; ";
  937. return drawList;
  938. }
  939. public string osDrawEllipse(string drawList, int width, int height)
  940. {
  941. CheckThreatLevel(ThreatLevel.None, "osDrawEllipse");
  942. m_host.AddScriptLPS(1);
  943. drawList += "Ellipse " + width + "," + height + "; ";
  944. return drawList;
  945. }
  946. public string osDrawRectangle(string drawList, int width, int height)
  947. {
  948. CheckThreatLevel(ThreatLevel.None, "osDrawRectangle");
  949. m_host.AddScriptLPS(1);
  950. drawList += "Rectangle " + width + "," + height + "; ";
  951. return drawList;
  952. }
  953. public string osDrawFilledRectangle(string drawList, int width, int height)
  954. {
  955. CheckThreatLevel(ThreatLevel.None, "osDrawFilledRectangle");
  956. m_host.AddScriptLPS(1);
  957. drawList += "FillRectangle " + width + "," + height + "; ";
  958. return drawList;
  959. }
  960. public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y)
  961. {
  962. CheckThreatLevel(ThreatLevel.None, "osDrawFilledPolygon");
  963. m_host.AddScriptLPS(1);
  964. if (x.Length != y.Length || x.Length < 3)
  965. {
  966. return "";
  967. }
  968. drawList += "FillPolygon " + x.GetLSLStringItem(0) + "," + y.GetLSLStringItem(0);
  969. for (int i = 1; i < x.Length; i++)
  970. {
  971. drawList += "," + x.GetLSLStringItem(i) + "," + y.GetLSLStringItem(i);
  972. }
  973. drawList += "; ";
  974. return drawList;
  975. }
  976. public string osDrawPolygon(string drawList, LSL_List x, LSL_List y)
  977. {
  978. CheckThreatLevel(ThreatLevel.None, "osDrawPolygon");
  979. m_host.AddScriptLPS(1);
  980. if (x.Length != y.Length || x.Length < 3)
  981. {
  982. return "";
  983. }
  984. drawList += "Polygon " + x.GetLSLStringItem(0) + "," + y.GetLSLStringItem(0);
  985. for (int i = 1; i < x.Length; i++)
  986. {
  987. drawList += "," + x.GetLSLStringItem(i) + "," + y.GetLSLStringItem(i);
  988. }
  989. drawList += "; ";
  990. return drawList;
  991. }
  992. public string osSetFontSize(string drawList, int fontSize)
  993. {
  994. CheckThreatLevel(ThreatLevel.None, "osSetFontSize");
  995. m_host.AddScriptLPS(1);
  996. drawList += "FontSize "+ fontSize +"; ";
  997. return drawList;
  998. }
  999. public string osSetFontName(string drawList, string fontName)
  1000. {
  1001. CheckThreatLevel(ThreatLevel.None, "osSetFontName");
  1002. m_host.AddScriptLPS(1);
  1003. drawList += "FontName "+ fontName +"; ";
  1004. return drawList;
  1005. }
  1006. public string osSetPenSize(string drawList, int penSize)
  1007. {
  1008. CheckThreatLevel(ThreatLevel.None, "osSetPenSize");
  1009. m_host.AddScriptLPS(1);
  1010. drawList += "PenSize " + penSize + "; ";
  1011. return drawList;
  1012. }
  1013. public string osSetPenColor(string drawList, string color)
  1014. {
  1015. CheckThreatLevel(ThreatLevel.None, "osSetPenColor");
  1016. m_host.AddScriptLPS(1);
  1017. drawList += "PenColor " + color + "; ";
  1018. return drawList;
  1019. }
  1020. // Deprecated
  1021. public string osSetPenColour(string drawList, string colour)
  1022. {
  1023. CheckThreatLevel(ThreatLevel.None, "osSetPenColour");
  1024. OSSLDeprecated("osSetPenColour", "osSetPenColor");
  1025. m_host.AddScriptLPS(1);
  1026. drawList += "PenColour " + colour + "; ";
  1027. return drawList;
  1028. }
  1029. public string osSetPenCap(string drawList, string direction, string type)
  1030. {
  1031. CheckThreatLevel(ThreatLevel.None, "osSetPenCap");
  1032. m_host.AddScriptLPS(1);
  1033. drawList += "PenCap " + direction + "," + type + "; ";
  1034. return drawList;
  1035. }
  1036. public string osDrawImage(string drawList, int width, int height, string imageUrl)
  1037. {
  1038. CheckThreatLevel(ThreatLevel.None, "osDrawImage");
  1039. m_host.AddScriptLPS(1);
  1040. drawList +="Image " +width + "," + height+ ","+ imageUrl +"; " ;
  1041. return drawList;
  1042. }
  1043. public LSL_Vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize)
  1044. {
  1045. CheckThreatLevel(ThreatLevel.VeryLow, "osGetDrawStringSize");
  1046. m_host.AddScriptLPS(1);
  1047. LSL_Vector vec = new LSL_Vector(0,0,0);
  1048. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  1049. if (textureManager != null)
  1050. {
  1051. double xSize, ySize;
  1052. textureManager.GetDrawStringSize(contentType, text, fontName, fontSize,
  1053. out xSize, out ySize);
  1054. vec.x = xSize;
  1055. vec.y = ySize;
  1056. }
  1057. return vec;
  1058. }
  1059. public void osSetStateEvents(int events)
  1060. {
  1061. // This function is a hack. There is no reason for it's existence
  1062. // anymore, since state events now work properly.
  1063. // It was probably added as a crutch or debugging aid, and
  1064. // should be removed
  1065. //
  1066. CheckThreatLevel(ThreatLevel.High, "osSetStateEvents");
  1067. m_host.AddScriptLPS(1);
  1068. m_host.SetScriptEvents(m_item.ItemID, events);
  1069. }
  1070. public void osSetRegionWaterHeight(double height)
  1071. {
  1072. CheckThreatLevel(ThreatLevel.High, "osSetRegionWaterHeight");
  1073. m_host.AddScriptLPS(1);
  1074. World.EventManager.TriggerRequestChangeWaterHeight((float)height);
  1075. }
  1076. /// <summary>
  1077. /// Changes the Region Sun Settings, then Triggers a Sun Update
  1078. /// </summary>
  1079. /// <param name="useEstateSun">True to use Estate Sun instead of Region Sun</param>
  1080. /// <param name="sunFixed">True to keep the sun stationary</param>
  1081. /// <param name="sunHour">The "Sun Hour" that is desired, 0...24, with 0 just after SunRise</param>
  1082. public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour)
  1083. {
  1084. CheckThreatLevel(ThreatLevel.High, "osSetRegionSunSettings");
  1085. m_host.AddScriptLPS(1);
  1086. while (sunHour > 24.0)
  1087. sunHour -= 24.0;
  1088. while (sunHour < 0)
  1089. sunHour += 24.0;
  1090. World.RegionInfo.RegionSettings.UseEstateSun = useEstateSun;
  1091. World.RegionInfo.RegionSettings.SunPosition = sunHour + 6; // LL Region Sun Hour is 6 to 30
  1092. World.RegionInfo.RegionSettings.FixedSun = sunFixed;
  1093. World.RegionInfo.RegionSettings.Save();
  1094. World.EventManager.TriggerEstateToolsSunUpdate(World.RegionInfo.RegionHandle);
  1095. }
  1096. /// <summary>
  1097. /// Changes the Estate Sun Settings, then Triggers a Sun Update
  1098. /// </summary>
  1099. /// <param name="sunFixed">True to keep the sun stationary, false to use global time</param>
  1100. /// <param name="sunHour">The "Sun Hour" that is desired, 0...24, with 0 just after SunRise</param>
  1101. public void osSetEstateSunSettings(bool sunFixed, double sunHour)
  1102. {
  1103. CheckThreatLevel(ThreatLevel.High, "osSetEstateSunSettings");
  1104. m_host.AddScriptLPS(1);
  1105. while (sunHour > 24.0)
  1106. sunHour -= 24.0;
  1107. while (sunHour < 0)
  1108. sunHour += 24.0;
  1109. World.RegionInfo.EstateSettings.UseGlobalTime = !sunFixed;
  1110. World.RegionInfo.EstateSettings.SunPosition = sunHour;
  1111. World.RegionInfo.EstateSettings.FixedSun = sunFixed;
  1112. World.EstateDataService.StoreEstateSettings(World.RegionInfo.EstateSettings);
  1113. World.EventManager.TriggerEstateToolsSunUpdate(World.RegionInfo.RegionHandle);
  1114. }
  1115. /// <summary>
  1116. /// Return the current Sun Hour 0...24, with 0 being roughly sun-rise
  1117. /// </summary>
  1118. /// <returns></returns>
  1119. public double osGetCurrentSunHour()
  1120. {
  1121. CheckThreatLevel(ThreatLevel.None, "osGetCurrentSunHour");
  1122. m_host.AddScriptLPS(1);
  1123. // Must adjust for the fact that Region Sun Settings are still LL offset
  1124. double sunHour = World.RegionInfo.RegionSettings.SunPosition - 6;
  1125. // See if the sun module has registered itself, if so it's authoritative
  1126. ISunModule module = World.RequestModuleInterface<ISunModule>();
  1127. if (module != null)
  1128. {
  1129. sunHour = module.GetCurrentSunHour();
  1130. }
  1131. return sunHour;
  1132. }
  1133. public double osSunGetParam(string param)
  1134. {
  1135. CheckThreatLevel(ThreatLevel.None, "osSunGetParam");
  1136. OSSLDeprecated("osSunGetParam", "osGetSunParam");
  1137. return GetSunParam(param);
  1138. }
  1139. public double osGetSunParam(string param)
  1140. {
  1141. CheckThreatLevel(ThreatLevel.None, "osGetSunParam");
  1142. return GetSunParam(param);
  1143. }
  1144. private double GetSunParam(string param)
  1145. {
  1146. m_host.AddScriptLPS(1);
  1147. double value = 0.0;
  1148. ISunModule module = World.RequestModuleInterface<ISunModule>();
  1149. if (module != null)
  1150. {
  1151. value = module.GetSunParameter(param);
  1152. }
  1153. return value;
  1154. }
  1155. public void osSunSetParam(string param, double value)
  1156. {
  1157. CheckThreatLevel(ThreatLevel.None, "osSunSetParam");
  1158. OSSLDeprecated("osSunSetParam", "osSetSunParam");
  1159. SetSunParam(param, value);
  1160. }
  1161. public void osSetSunParam(string param, double value)
  1162. {
  1163. CheckThreatLevel(ThreatLevel.None, "osSetSunParam");
  1164. SetSunParam(param, value);
  1165. }
  1166. private void SetSunParam(string param, double value)
  1167. {
  1168. m_host.AddScriptLPS(1);
  1169. ISunModule module = World.RequestModuleInterface<ISunModule>();
  1170. if (module != null)
  1171. {
  1172. module.SetSunParameter(param, value);
  1173. }
  1174. }
  1175. public string osWindActiveModelPluginName()
  1176. {
  1177. CheckThreatLevel(ThreatLevel.None, "osWindActiveModelPluginName");
  1178. m_host.AddScriptLPS(1);
  1179. IWindModule module = World.RequestModuleInterface<IWindModule>();
  1180. if (module != null)
  1181. {
  1182. return module.WindActiveModelPluginName;
  1183. }
  1184. return String.Empty;
  1185. }
  1186. public void osSetWindParam(string plugin, string param, LSL_Float value)
  1187. {
  1188. CheckThreatLevel(ThreatLevel.VeryLow, "osSetWindParam");
  1189. m_host.AddScriptLPS(1);
  1190. IWindModule module = World.RequestModuleInterface<IWindModule>();
  1191. if (module != null)
  1192. {
  1193. try
  1194. {
  1195. module.WindParamSet(plugin, param, (float)value);
  1196. }
  1197. catch (Exception) { }
  1198. }
  1199. }
  1200. public LSL_Float osGetWindParam(string plugin, string param)
  1201. {
  1202. CheckThreatLevel(ThreatLevel.VeryLow, "osGetWindParam");
  1203. m_host.AddScriptLPS(1);
  1204. IWindModule module = World.RequestModuleInterface<IWindModule>();
  1205. if (module != null)
  1206. {
  1207. return module.WindParamGet(plugin, param);
  1208. }
  1209. return 0.0f;
  1210. }
  1211. // Routines for creating and managing parcels programmatically
  1212. public void osParcelJoin(LSL_Vector pos1, LSL_Vector pos2)
  1213. {
  1214. CheckThreatLevel(ThreatLevel.High, "osParcelJoin");
  1215. m_host.AddScriptLPS(1);
  1216. int startx = (int)(pos1.x < pos2.x ? pos1.x : pos2.x);
  1217. int starty = (int)(pos1.y < pos2.y ? pos1.y : pos2.y);
  1218. int endx = (int)(pos1.x > pos2.x ? pos1.x : pos2.x);
  1219. int endy = (int)(pos1.y > pos2.y ? pos1.y : pos2.y);
  1220. World.LandChannel.Join(startx,starty,endx,endy,m_host.OwnerID);
  1221. }
  1222. public void osParcelSubdivide(LSL_Vector pos1, LSL_Vector pos2)
  1223. {
  1224. CheckThreatLevel(ThreatLevel.High, "osParcelSubdivide");
  1225. m_host.AddScriptLPS(1);
  1226. int startx = (int)(pos1.x < pos2.x ? pos1.x : pos2.x);
  1227. int starty = (int)(pos1.y < pos2.y ? pos1.y : pos2.y);
  1228. int endx = (int)(pos1.x > pos2.x ? pos1.x : pos2.x);
  1229. int endy = (int)(pos1.y > pos2.y ? pos1.y : pos2.y);
  1230. World.LandChannel.Subdivide(startx,starty,endx,endy,m_host.OwnerID);
  1231. }
  1232. public void osParcelSetDetails(LSL_Vector pos, LSL_List rules)
  1233. {
  1234. const string functionName = "osParcelSetDetails";
  1235. CheckThreatLevel(ThreatLevel.High, functionName);
  1236. OSSLDeprecated(functionName, "osSetParcelDetails");
  1237. SetParcelDetails(pos, rules, functionName);
  1238. }
  1239. public void osSetParcelDetails(LSL_Vector pos, LSL_List rules)
  1240. {
  1241. const string functionName = "osSetParcelDetails";
  1242. CheckThreatLevel(ThreatLevel.High, functionName);
  1243. SetParcelDetails(pos, rules, functionName);
  1244. }
  1245. private void SetParcelDetails(LSL_Vector pos, LSL_List rules, string functionName)
  1246. {
  1247. m_host.AddScriptLPS(1);
  1248. // Get a reference to the land data and make sure the owner of the script
  1249. // can modify it
  1250. ILandObject startLandObject = World.LandChannel.GetLandObject((int)pos.x, (int)pos.y);
  1251. if (startLandObject == null)
  1252. {
  1253. OSSLShoutError("There is no land at that location");
  1254. return;
  1255. }
  1256. if (!World.Permissions.CanEditParcelProperties(m_host.OwnerID, startLandObject, GroupPowers.LandOptions))
  1257. {
  1258. OSSLShoutError("You do not have permission to modify the parcel");
  1259. return;
  1260. }
  1261. // Create a new land data object we can modify
  1262. LandData newLand = startLandObject.LandData.Copy();
  1263. UUID uuid;
  1264. // Process the rules, not sure what the impact would be of changing owner or group
  1265. for (int idx = 0; idx < rules.Length;)
  1266. {
  1267. int code = rules.GetLSLIntegerItem(idx++);
  1268. string arg = rules.GetLSLStringItem(idx++);
  1269. switch (code)
  1270. {
  1271. case ScriptBaseClass.PARCEL_DETAILS_NAME:
  1272. newLand.Name = arg;
  1273. break;
  1274. case ScriptBaseClass.PARCEL_DETAILS_DESC:
  1275. newLand.Description = arg;
  1276. break;
  1277. case ScriptBaseClass.PARCEL_DETAILS_OWNER:
  1278. CheckThreatLevel(ThreatLevel.VeryHigh, functionName);
  1279. if (UUID.TryParse(arg, out uuid))
  1280. newLand.OwnerID = uuid;
  1281. break;
  1282. case ScriptBaseClass.PARCEL_DETAILS_GROUP:
  1283. CheckThreatLevel(ThreatLevel.VeryHigh, functionName);
  1284. if (UUID.TryParse(arg, out uuid))
  1285. newLand.GroupID = uuid;
  1286. break;
  1287. case ScriptBaseClass.PARCEL_DETAILS_CLAIMDATE:
  1288. CheckThreatLevel(ThreatLevel.VeryHigh, functionName);
  1289. newLand.ClaimDate = Convert.ToInt32(arg);
  1290. if (newLand.ClaimDate == 0)
  1291. newLand.ClaimDate = Util.UnixTimeSinceEpoch();
  1292. break;
  1293. }
  1294. }
  1295. World.LandChannel.UpdateLandObject(newLand.LocalID,newLand);
  1296. }
  1297. public double osList2Double(LSL_Types.list src, int index)
  1298. {
  1299. // There is really no double type in OSSL. C# and other
  1300. // have one, but the current implementation of LSL_Types.list
  1301. // is not allowed to contain any.
  1302. // This really should be removed.
  1303. //
  1304. CheckThreatLevel(ThreatLevel.None, "osList2Double");
  1305. m_host.AddScriptLPS(1);
  1306. if (index < 0)
  1307. {
  1308. index = src.Length + index;
  1309. }
  1310. if (index >= src.Length)
  1311. {
  1312. return 0.0;
  1313. }
  1314. return Convert.ToDouble(src.Data[index]);
  1315. }
  1316. public void osSetParcelMediaURL(string url)
  1317. {
  1318. // What actually is the difference to the LL function?
  1319. //
  1320. CheckThreatLevel(ThreatLevel.VeryLow, "osSetParcelMediaURL");
  1321. m_host.AddScriptLPS(1);
  1322. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  1323. if (land.LandData.OwnerID != m_host.OwnerID)
  1324. return;
  1325. land.SetMediaUrl(url);
  1326. }
  1327. public void osSetParcelSIPAddress(string SIPAddress)
  1328. {
  1329. // What actually is the difference to the LL function?
  1330. //
  1331. CheckThreatLevel(ThreatLevel.VeryLow, "osSetParcelSIPAddress");
  1332. m_host.AddScriptLPS(1);
  1333. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  1334. if (land.LandData.OwnerID != m_host.OwnerID)
  1335. {
  1336. OSSLError("osSetParcelSIPAddress: Sorry, you need to own the land to use this function");
  1337. return;
  1338. }
  1339. // get the voice module
  1340. IVoiceModule voiceModule = World.RequestModuleInterface<IVoiceModule>();
  1341. if (voiceModule != null)
  1342. voiceModule.setLandSIPAddress(SIPAddress,land.LandData.GlobalID);
  1343. else
  1344. OSSLError("osSetParcelSIPAddress: No voice module enabled for this land");
  1345. }
  1346. public string osGetScriptEngineName()
  1347. {
  1348. // This gets a "high" because knowing the engine may be used
  1349. // to exploit engine-specific bugs or induce usage patterns
  1350. // that trigger engine-specific failures.
  1351. // Besides, public grid users aren't supposed to know.
  1352. //
  1353. CheckThreatLevel(ThreatLevel.High, "osGetScriptEngineName");
  1354. m_host.AddScriptLPS(1);
  1355. int scriptEngineNameIndex = 0;
  1356. if (!String.IsNullOrEmpty(m_ScriptEngine.ScriptEngineName))
  1357. {
  1358. // parse off the "ScriptEngine."
  1359. scriptEngineNameIndex = m_ScriptEngine.ScriptEngineName.IndexOf(".", scriptEngineNameIndex);
  1360. scriptEngineNameIndex++; // get past delimiter
  1361. int scriptEngineNameLength = m_ScriptEngine.ScriptEngineName.Length - scriptEngineNameIndex;
  1362. // create char array then a string that is only the script engine name
  1363. Char[] scriptEngineNameCharArray = m_ScriptEngine.ScriptEngineName.ToCharArray(scriptEngineNameIndex, scriptEngineNameLength);
  1364. String scriptEngineName = new String(scriptEngineNameCharArray);
  1365. return scriptEngineName;
  1366. }
  1367. else
  1368. {
  1369. return String.Empty;
  1370. }
  1371. }
  1372. public LSL_Integer osCheckODE()
  1373. {
  1374. m_host.AddScriptLPS(1);
  1375. LSL_Integer ret = 0; // false
  1376. if (m_ScriptEngine.World.PhysicsScene != null)
  1377. {
  1378. string physEngine = m_ScriptEngine.World.PhysicsScene.EngineType;
  1379. if (physEngine == "OpenDynamicsEngine")
  1380. {
  1381. ret = 1; // true
  1382. }
  1383. }
  1384. return ret;
  1385. }
  1386. public string osGetPhysicsEngineType()
  1387. {
  1388. // High because it can be used to target attacks to known weaknesses
  1389. // This would allow a new class of griefer scripts that don't even
  1390. // require their user to know what they are doing (see script
  1391. // kiddie)
  1392. // Because it would be nice if scripts didn't blow up if the information
  1393. // about the physics engine, this function returns an empty string if
  1394. // the user does not have permission to see it. This as opposed to
  1395. // throwing an exception.
  1396. m_host.AddScriptLPS(1);
  1397. string ret = String.Empty;
  1398. if (String.IsNullOrEmpty(CheckThreatLevelTest(ThreatLevel.High, "osGetPhysicsEngineType")))
  1399. {
  1400. if (m_ScriptEngine.World.PhysicsScene != null)
  1401. {
  1402. ret = m_ScriptEngine.World.PhysicsScene.EngineType;
  1403. // An old physics engine might have an uninitialized engine type
  1404. if (ret == null)
  1405. ret = "unknown";
  1406. }
  1407. }
  1408. return ret;
  1409. }
  1410. public string osGetSimulatorVersion()
  1411. {
  1412. // High because it can be used to target attacks to known weaknesses
  1413. // This would allow a new class of griefer scripts that don't even
  1414. // require their user to know what they are doing (see script
  1415. // kiddie)
  1416. //
  1417. CheckThreatLevel(ThreatLevel.High,"osGetSimulatorVersion");
  1418. m_host.AddScriptLPS(1);
  1419. return m_ScriptEngine.World.GetSimulatorVersion();
  1420. }
  1421. private Hashtable osdToHashtable(OSDMap map)
  1422. {
  1423. Hashtable result = new Hashtable();
  1424. foreach (KeyValuePair<string, OSD> item in map) {
  1425. result.Add(item.Key, osdToObject(item.Value));
  1426. }
  1427. return result;
  1428. }
  1429. private ArrayList osdToArray(OSDArray list)
  1430. {
  1431. ArrayList result = new ArrayList();
  1432. foreach ( OSD item in list ) {
  1433. result.Add(osdToObject(item));
  1434. }
  1435. return result;
  1436. }
  1437. private Object osdToObject(OSD decoded)
  1438. {
  1439. if ( decoded is OSDString ) {
  1440. return (string) decoded.AsString();
  1441. } else if ( decoded is OSDInteger ) {
  1442. return (int) decoded.AsInteger();
  1443. } else if ( decoded is OSDReal ) {
  1444. return (float) decoded.AsReal();
  1445. } else if ( decoded is OSDBoolean ) {
  1446. return (bool) decoded.AsBoolean();
  1447. } else if ( decoded is OSDMap ) {
  1448. return osdToHashtable((OSDMap) decoded);
  1449. } else if ( decoded is OSDArray ) {
  1450. return osdToArray((OSDArray) decoded);
  1451. } else {
  1452. return null;
  1453. }
  1454. }
  1455. public Object osParseJSONNew(string JSON)
  1456. {
  1457. CheckThreatLevel(ThreatLevel.None, "osParseJSONNew");
  1458. m_host.AddScriptLPS(1);
  1459. try
  1460. {
  1461. OSD decoded = OSDParser.DeserializeJson(JSON);
  1462. return osdToObject(decoded);
  1463. }
  1464. catch(Exception e)
  1465. {
  1466. OSSLError("osParseJSONNew: Problems decoding JSON string " + JSON + " : " + e.Message) ;
  1467. return null;
  1468. }
  1469. }
  1470. public Hashtable osParseJSON(string JSON)
  1471. {
  1472. CheckThreatLevel(ThreatLevel.None, "osParseJSON");
  1473. m_host.AddScriptLPS(1);
  1474. Object decoded = osParseJSONNew(JSON);
  1475. if ( decoded is Hashtable ) {
  1476. return (Hashtable) decoded;
  1477. } else if ( decoded is ArrayList ) {
  1478. ArrayList decoded_list = (ArrayList) decoded;
  1479. Hashtable fakearray = new Hashtable();
  1480. int i = 0;
  1481. for ( i = 0; i < decoded_list.Count ; i++ ) {
  1482. fakearray.Add(i, decoded_list[i]);
  1483. }
  1484. return fakearray;
  1485. } else {
  1486. OSSLError("osParseJSON: unable to parse JSON string " + JSON);
  1487. return null;
  1488. }
  1489. }
  1490. /// <summary>
  1491. /// Send a message to to object identified by the given UUID
  1492. /// </summary>
  1493. /// <remarks>
  1494. /// A script in the object must implement the dataserver function
  1495. /// the dataserver function is passed the ID of the calling function and a string message
  1496. /// </remarks>
  1497. /// <param name="objectUUID"></param>
  1498. /// <param name="message"></param>
  1499. public void osMessageObject(LSL_Key objectUUID, string message)
  1500. {
  1501. CheckThreatLevel(ThreatLevel.Low, "osMessageObject");
  1502. m_host.AddScriptLPS(1);
  1503. UUID objUUID;
  1504. if (!UUID.TryParse(objectUUID, out objUUID)) // prior to patching, a thrown exception regarding invalid GUID format would be shouted instead.
  1505. {
  1506. OSSLShoutError("osMessageObject() cannot send messages to objects with invalid UUIDs");
  1507. return;
  1508. }
  1509. MessageObject(objUUID, message);
  1510. }
  1511. private void MessageObject(UUID objUUID, string message)
  1512. {
  1513. object[] resobj = new object[] { new LSL_Types.LSLString(m_host.UUID.ToString()), new LSL_Types.LSLString(message) };
  1514. SceneObjectPart sceneOP = World.GetSceneObjectPart(objUUID);
  1515. if (sceneOP == null) // prior to patching, PostObjectEvent() would cause a throw exception to be shouted instead.
  1516. {
  1517. OSSLShoutError("osMessageObject() cannot send message to " + objUUID.ToString() + ", object was not found in scene.");
  1518. return;
  1519. }
  1520. m_ScriptEngine.PostObjectEvent(
  1521. sceneOP.LocalId, new EventParams(
  1522. "dataserver", resobj, new DetectParams[0]));
  1523. }
  1524. /// <summary>
  1525. /// Write a notecard directly to the prim's inventory.
  1526. /// </summary>
  1527. /// <remarks>
  1528. /// This needs ThreatLevel high. It is an excellent griefer tool,
  1529. /// In a loop, it can cause asset bloat and DOS levels of asset
  1530. /// writes.
  1531. /// </remarks>
  1532. /// <param name="notecardName">The name of the notecard to write.</param>
  1533. /// <param name="contents">The contents of the notecard.</param>
  1534. public void osMakeNotecard(string notecardName, LSL_Types.list contents)
  1535. {
  1536. CheckThreatLevel(ThreatLevel.High, "osMakeNotecard");
  1537. m_host.AddScriptLPS(1);
  1538. StringBuilder notecardData = new StringBuilder();
  1539. for (int i = 0; i < contents.Length; i++)
  1540. notecardData.Append((string)(contents.GetLSLStringItem(i) + "\n"));
  1541. SaveNotecard(notecardName, "Script generated notecard", notecardData.ToString(), false);
  1542. }
  1543. /// <summary>
  1544. /// Save a notecard to prim inventory.
  1545. /// </summary>
  1546. /// <param name="name"></param>
  1547. /// <param name="description">Description of notecard</param>
  1548. /// <param name="notecardData"></param>
  1549. /// <param name="forceSameName">
  1550. /// If true, then if an item exists with the same name, it is replaced.
  1551. /// If false, then a new item is created witha slightly different name (e.g. name 1)
  1552. /// </param>
  1553. /// <returns>Prim inventory item created.</returns>
  1554. protected TaskInventoryItem SaveNotecard(string name, string description, string data, bool forceSameName)
  1555. {
  1556. // Create new asset
  1557. AssetBase asset = new AssetBase(UUID.Random(), name, (sbyte)AssetType.Notecard, m_host.OwnerID.ToString());
  1558. asset.Description = description;
  1559. byte[] a;
  1560. byte[] b;
  1561. byte[] c;
  1562. b = Util.UTF8.GetBytes(data);
  1563. a = Util.UTF8.GetBytes(
  1564. "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + b.Length.ToString() + "\n");
  1565. c = Util.UTF8.GetBytes("}");
  1566. byte[] d = new byte[a.Length + b.Length + c.Length];
  1567. Buffer.BlockCopy(a, 0, d, 0, a.Length);
  1568. Buffer.BlockCopy(b, 0, d, a.Length, b.Length);
  1569. Buffer.BlockCopy(c, 0, d, a.Length + b.Length, c.Length);
  1570. asset.Data = d;
  1571. World.AssetService.Store(asset);
  1572. // Create Task Entry
  1573. TaskInventoryItem taskItem = new TaskInventoryItem();
  1574. taskItem.ResetIDs(m_host.UUID);
  1575. taskItem.ParentID = m_host.UUID;
  1576. taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch();
  1577. taskItem.Name = asset.Name;
  1578. taskItem.Description = asset.Description;
  1579. taskItem.Type = (int)AssetType.Notecard;
  1580. taskItem.InvType = (int)InventoryType.Notecard;
  1581. taskItem.OwnerID = m_host.OwnerID;
  1582. taskItem.CreatorID = m_host.OwnerID;
  1583. taskItem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  1584. taskItem.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  1585. taskItem.EveryonePermissions = 0;
  1586. taskItem.NextPermissions = (uint)PermissionMask.All;
  1587. taskItem.GroupID = m_host.GroupID;
  1588. taskItem.GroupPermissions = 0;
  1589. taskItem.Flags = 0;
  1590. taskItem.PermsGranter = UUID.Zero;
  1591. taskItem.PermsMask = 0;
  1592. taskItem.AssetID = asset.FullID;
  1593. if (forceSameName)
  1594. m_host.Inventory.AddInventoryItemExclusive(taskItem, false);
  1595. else
  1596. m_host.Inventory.AddInventoryItem(taskItem, false);
  1597. return taskItem;
  1598. }
  1599. /// <summary>
  1600. /// Load the notecard data found at the given prim inventory item name or asset uuid.
  1601. /// </summary>
  1602. /// <param name="notecardNameOrUuid"></param>
  1603. /// <returns>The text loaded. Null if no notecard was found.</returns>
  1604. protected string LoadNotecard(string notecardNameOrUuid)
  1605. {
  1606. UUID assetID = CacheNotecard(notecardNameOrUuid);
  1607. if (assetID != UUID.Zero)
  1608. {
  1609. StringBuilder notecardData = new StringBuilder();
  1610. for (int count = 0; count < NotecardCache.GetLines(assetID); count++)
  1611. {
  1612. string line = NotecardCache.GetLine(assetID, count) + "\n";
  1613. // m_log.DebugFormat("[OSSL]: From notecard {0} loading line {1}", notecardNameOrUuid, line);
  1614. notecardData.Append(line);
  1615. }
  1616. return notecardData.ToString();
  1617. }
  1618. return null;
  1619. }
  1620. /// <summary>
  1621. /// Cache a notecard's contents.
  1622. /// </summary>
  1623. /// <param name="notecardNameOrUuid"></param>
  1624. /// <returns>
  1625. /// The asset id of the notecard, which is used for retrieving the cached data.
  1626. /// UUID.Zero if no asset could be found.
  1627. /// </returns>
  1628. protected UUID CacheNotecard(string notecardNameOrUuid)
  1629. {
  1630. UUID assetID = UUID.Zero;
  1631. if (!UUID.TryParse(notecardNameOrUuid, out assetID))
  1632. {
  1633. foreach (TaskInventoryItem item in m_host.TaskInventory.Values)
  1634. {
  1635. if (item.Type == 7 && item.Name == notecardNameOrUuid)
  1636. {
  1637. assetID = item.AssetID;
  1638. }
  1639. }
  1640. }
  1641. if (assetID == UUID.Zero)
  1642. return UUID.Zero;
  1643. if (!NotecardCache.IsCached(assetID))
  1644. {
  1645. AssetBase a = World.AssetService.Get(assetID.ToString());
  1646. if (a == null)
  1647. return UUID.Zero;
  1648. NotecardCache.Cache(assetID, a.Data);
  1649. };
  1650. return assetID;
  1651. }
  1652. /// <summary>
  1653. /// Directly get an entire notecard at once.
  1654. /// </summary>
  1655. /// <remarks>
  1656. /// Instead of using the LSL Dataserver event to pull notecard data
  1657. /// this will simply read the entire notecard and return its data as a string.
  1658. ///
  1659. /// Warning - due to the synchronous method this function uses to fetch assets, its use
  1660. /// may be dangerous and unreliable while running in grid mode.
  1661. /// </remarks>
  1662. /// <param name="name">Name of the notecard or its asset id</param>
  1663. /// <param name="line">The line number to read. The first line is line 0</param>
  1664. /// <returns>Notecard line</returns>
  1665. public string osGetNotecardLine(string name, int line)
  1666. {
  1667. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNotecardLine");
  1668. m_host.AddScriptLPS(1);
  1669. UUID assetID = CacheNotecard(name);
  1670. if (assetID == UUID.Zero)
  1671. {
  1672. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1673. return "ERROR!";
  1674. }
  1675. return NotecardCache.GetLine(assetID, line);
  1676. }
  1677. /// <summary>
  1678. /// Get an entire notecard at once.
  1679. /// </summary>
  1680. /// <remarks>
  1681. /// Instead of using the LSL Dataserver event to pull notecard data line by line,
  1682. /// this will simply read the entire notecard and return its data as a string.
  1683. ///
  1684. /// Warning - due to the synchronous method this function uses to fetch assets, its use
  1685. /// may be dangerous and unreliable while running in grid mode.
  1686. /// </remarks>
  1687. /// <param name="name">Name of the notecard or its asset id</param>
  1688. /// <returns>Notecard text</returns>
  1689. public string osGetNotecard(string name)
  1690. {
  1691. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNotecard");
  1692. m_host.AddScriptLPS(1);
  1693. string text = LoadNotecard(name);
  1694. if (text == null)
  1695. {
  1696. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1697. return "ERROR!";
  1698. }
  1699. else
  1700. {
  1701. return text;
  1702. }
  1703. }
  1704. /// <summary>
  1705. /// Get the number of lines in the given notecard.
  1706. /// </summary>
  1707. /// <remarks>
  1708. /// Instead of using the LSL Dataserver event to pull notecard data,
  1709. /// this will simply read the number of note card lines and return this data as an integer.
  1710. ///
  1711. /// Warning - due to the synchronous method this function uses to fetch assets, its use
  1712. /// may be dangerous and unreliable while running in grid mode.
  1713. /// </remarks>
  1714. /// <param name="name">Name of the notecard or its asset id</param>
  1715. /// <returns></returns>
  1716. public int osGetNumberOfNotecardLines(string name)
  1717. {
  1718. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNumberOfNotecardLines");
  1719. m_host.AddScriptLPS(1);
  1720. UUID assetID = CacheNotecard(name);
  1721. if (assetID == UUID.Zero)
  1722. {
  1723. OSSLShoutError("Notecard '" + name + "' could not be found.");
  1724. return -1;
  1725. }
  1726. return NotecardCache.GetLines(assetID);
  1727. }
  1728. public string osAvatarName2Key(string firstname, string lastname)
  1729. {
  1730. CheckThreatLevel(ThreatLevel.Low, "osAvatarName2Key");
  1731. m_host.AddScriptLPS(1);
  1732. IUserManagement userManager = World.RequestModuleInterface<IUserManagement>();
  1733. if (userManager == null)
  1734. {
  1735. OSSLShoutError("osAvatarName2Key: UserManagement module not available");
  1736. return string.Empty;
  1737. }
  1738. // Check if the user is already cached
  1739. UUID userID = userManager.GetUserIdByName(firstname, lastname);
  1740. if (userID != UUID.Zero)
  1741. return userID.ToString();
  1742. // Query for the user
  1743. String realFirstName; String realLastName; String serverURI;
  1744. if (Util.ParseForeignAvatarName(firstname, lastname, out realFirstName, out realLastName, out serverURI))
  1745. {
  1746. try
  1747. {
  1748. UserAgentServiceConnector userConnection = new UserAgentServiceConnector(serverURI, true);
  1749. if (userConnection != null)
  1750. {
  1751. userID = userConnection.GetUUID(realFirstName, realLastName);
  1752. if (userID != UUID.Zero)
  1753. {
  1754. userManager.AddUser(userID, realFirstName, realLastName, serverURI);
  1755. return userID.ToString();
  1756. }
  1757. }
  1758. }
  1759. catch (Exception /*e*/)
  1760. {
  1761. // m_log.Warn("[osAvatarName2Key] UserAgentServiceConnector - Unable to connect to destination grid ", e);
  1762. }
  1763. }
  1764. else
  1765. {
  1766. UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, firstname, lastname);
  1767. if (account != null)
  1768. return account.PrincipalID.ToString();
  1769. }
  1770. return UUID.Zero.ToString();
  1771. }
  1772. public string osKey2Name(string id)
  1773. {
  1774. CheckThreatLevel(ThreatLevel.Low, "osKey2Name");
  1775. m_host.AddScriptLPS(1);
  1776. UUID key = new UUID();
  1777. if (UUID.TryParse(id, out key))
  1778. {
  1779. UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, key);
  1780. if (account != null)
  1781. return account.Name;
  1782. if (m_ScriptEngine.World.GridUserService != null)
  1783. {
  1784. GridUserInfo uInfo = m_ScriptEngine.World.GridUserService.GetGridUserInfo(key.ToString());
  1785. if (uInfo != null)
  1786. {
  1787. UUID userUUID; String gridURL; String firstName; String lastName; String tmp;
  1788. if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out userUUID, out gridURL, out firstName, out lastName, out tmp))
  1789. {
  1790. string grid = new Uri(gridURL).Authority;
  1791. return firstName + "." + lastName + " @" + grid;
  1792. }
  1793. }
  1794. }
  1795. }
  1796. return "";
  1797. }
  1798. private enum InfoType
  1799. {
  1800. Nick,
  1801. Name,
  1802. Login,
  1803. Home,
  1804. Custom
  1805. };
  1806. private string GridUserInfo(InfoType type)
  1807. {
  1808. return GridUserInfo(type, "");
  1809. }
  1810. private string GridUserInfo(InfoType type, string key)
  1811. {
  1812. string retval = String.Empty;
  1813. IConfigSource config = m_ScriptEngine.ConfigSource;
  1814. string url = null;
  1815. IConfig gridInfoConfig = config.Configs["GridInfo"];
  1816. if (gridInfoConfig != null)
  1817. url = gridInfoConfig.GetString("GridInfoURI", String.Empty);
  1818. if (String.IsNullOrEmpty(url))
  1819. return "Configuration Error!";
  1820. string verb ="/json_grid_info";
  1821. OSDMap json = new OSDMap();
  1822. OSDMap info = WebUtil.GetFromService(String.Format("{0}{1}",url,verb), 3000);
  1823. if (info["Success"] != true)
  1824. return "Get GridInfo Failed!";
  1825. json = (OSDMap)OSDParser.DeserializeJson(info["_RawResult"].AsString());
  1826. switch (type)
  1827. {
  1828. case InfoType.Nick:
  1829. retval = json["gridnick"];
  1830. break;
  1831. case InfoType.Name:
  1832. retval = json["gridname"];
  1833. break;
  1834. case InfoType.Login:
  1835. retval = json["login"];
  1836. break;
  1837. case InfoType.Home:
  1838. retval = json["home"];
  1839. break;
  1840. case InfoType.Custom:
  1841. retval = json[key];
  1842. break;
  1843. default:
  1844. retval = "error";
  1845. break;
  1846. }
  1847. return retval;
  1848. }
  1849. /// <summary>
  1850. /// Get the nickname of this grid, as set in the [GridInfo] config section.
  1851. /// </summary>
  1852. /// <remarks>
  1853. /// Threat level is Moderate because intentional abuse, for instance
  1854. /// scripts that are written to be malicious only on one grid,
  1855. /// for instance in a HG scenario, are a distinct possibility.
  1856. /// </remarks>
  1857. /// <returns></returns>
  1858. public string osGetGridNick()
  1859. {
  1860. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridNick");
  1861. m_host.AddScriptLPS(1);
  1862. string nick = String.Empty;
  1863. IConfigSource config = m_ScriptEngine.ConfigSource;
  1864. if (config.Configs[GridInfoServiceConfigSectionName] != null)
  1865. nick = config.Configs[GridInfoServiceConfigSectionName].GetString("gridnick", nick);
  1866. if (String.IsNullOrEmpty(nick))
  1867. nick = GridUserInfo(InfoType.Nick);
  1868. return nick;
  1869. }
  1870. public string osGetGridName()
  1871. {
  1872. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridName");
  1873. m_host.AddScriptLPS(1);
  1874. string name = String.Empty;
  1875. IConfigSource config = m_ScriptEngine.ConfigSource;
  1876. if (config.Configs[GridInfoServiceConfigSectionName] != null)
  1877. name = config.Configs[GridInfoServiceConfigSectionName].GetString("gridname", name);
  1878. if (String.IsNullOrEmpty(name))
  1879. name = GridUserInfo(InfoType.Name);
  1880. return name;
  1881. }
  1882. public string osGetGridLoginURI()
  1883. {
  1884. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridLoginURI");
  1885. m_host.AddScriptLPS(1);
  1886. string loginURI = String.Empty;
  1887. IConfigSource config = m_ScriptEngine.ConfigSource;
  1888. if (config.Configs[GridInfoServiceConfigSectionName] != null)
  1889. loginURI = config.Configs[GridInfoServiceConfigSectionName].GetString("login", loginURI);
  1890. if (String.IsNullOrEmpty(loginURI))
  1891. loginURI = GridUserInfo(InfoType.Login);
  1892. return loginURI;
  1893. }
  1894. public string osGetGridHomeURI()
  1895. {
  1896. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridHomeURI");
  1897. m_host.AddScriptLPS(1);
  1898. IConfigSource config = m_ScriptEngine.ConfigSource;
  1899. string HomeURI = Util.GetConfigVarFromSections<string>(config, "HomeURI",
  1900. new string[] { "Startup", "Hypergrid" }, String.Empty);
  1901. if (!string.IsNullOrEmpty(HomeURI))
  1902. return HomeURI;
  1903. // Legacy. Remove soon!
  1904. if (config.Configs["LoginService"] != null)
  1905. HomeURI = config.Configs["LoginService"].GetString("SRV_HomeURI", HomeURI);
  1906. if (String.IsNullOrEmpty(HomeURI))
  1907. HomeURI = GridUserInfo(InfoType.Home);
  1908. return HomeURI;
  1909. }
  1910. public string osGetGridGatekeeperURI()
  1911. {
  1912. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridGatekeeperURI");
  1913. m_host.AddScriptLPS(1);
  1914. IConfigSource config = m_ScriptEngine.ConfigSource;
  1915. string gatekeeperURI = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
  1916. new string[] { "Startup", "Hypergrid" }, String.Empty);
  1917. if (!string.IsNullOrEmpty(gatekeeperURI))
  1918. return gatekeeperURI;
  1919. // Legacy. Remove soon!
  1920. if (config.Configs["GridService"] != null)
  1921. gatekeeperURI = config.Configs["GridService"].GetString("Gatekeeper", gatekeeperURI);
  1922. return gatekeeperURI;
  1923. }
  1924. public string osGetGridCustom(string key)
  1925. {
  1926. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridCustom");
  1927. m_host.AddScriptLPS(1);
  1928. string retval = String.Empty;
  1929. IConfigSource config = m_ScriptEngine.ConfigSource;
  1930. if (config.Configs[GridInfoServiceConfigSectionName] != null)
  1931. retval = config.Configs[GridInfoServiceConfigSectionName].GetString(key, retval);
  1932. if (String.IsNullOrEmpty(retval))
  1933. retval = GridUserInfo(InfoType.Custom, key);
  1934. return retval;
  1935. }
  1936. public string osGetAvatarHomeURI(string uuid)
  1937. {
  1938. CheckThreatLevel(ThreatLevel.Low, "osGetAvatarHomeURI");
  1939. m_host.AddScriptLPS(1);
  1940. IUserManagement userManager = m_ScriptEngine.World.RequestModuleInterface<IUserManagement>();
  1941. string returnValue = "";
  1942. if (userManager != null)
  1943. {
  1944. returnValue = userManager.GetUserServerURL(new UUID(uuid), "HomeURI");
  1945. }
  1946. if (returnValue == "")
  1947. {
  1948. IConfigSource config = m_ScriptEngine.ConfigSource;
  1949. returnValue = Util.GetConfigVarFromSections<string>(config, "HomeURI",
  1950. new string[] { "Startup", "Hypergrid" }, String.Empty);
  1951. if (!string.IsNullOrEmpty(returnValue))
  1952. return returnValue;
  1953. // Legacy. Remove soon!
  1954. if (config.Configs["LoginService"] != null)
  1955. returnValue = config.Configs["LoginService"].GetString("SRV_HomeURI", returnValue);
  1956. if (String.IsNullOrEmpty(returnValue))
  1957. returnValue = GridUserInfo(InfoType.Home);
  1958. }
  1959. return returnValue;
  1960. }
  1961. public LSL_String osFormatString(string str, LSL_List strings)
  1962. {
  1963. CheckThreatLevel(ThreatLevel.VeryLow, "osFormatString");
  1964. m_host.AddScriptLPS(1);
  1965. return String.Format(str, strings.Data);
  1966. }
  1967. public LSL_List osMatchString(string src, string pattern, int start)
  1968. {
  1969. CheckThreatLevel(ThreatLevel.VeryLow, "osMatchString");
  1970. m_host.AddScriptLPS(1);
  1971. LSL_List result = new LSL_List();
  1972. // Normalize indices (if negative).
  1973. // After normlaization they may still be
  1974. // negative, but that is now relative to
  1975. // the start, rather than the end, of the
  1976. // sequence.
  1977. if (start < 0)
  1978. {
  1979. start = src.Length + start;
  1980. }
  1981. if (start < 0 || start >= src.Length)
  1982. {
  1983. return result; // empty list
  1984. }
  1985. // Find matches beginning at start position
  1986. Regex matcher = new Regex(pattern);
  1987. Match match = matcher.Match(src, start);
  1988. while (match.Success)
  1989. {
  1990. foreach (System.Text.RegularExpressions.Group g in match.Groups)
  1991. {
  1992. if (g.Success)
  1993. {
  1994. result.Add(new LSL_String(g.Value));
  1995. result.Add(new LSL_Integer(g.Index));
  1996. }
  1997. }
  1998. match = match.NextMatch();
  1999. }
  2000. return result;
  2001. }
  2002. public LSL_String osReplaceString(string src, string pattern, string replace, int count, int start)
  2003. {
  2004. CheckThreatLevel(ThreatLevel.VeryLow, "osReplaceString");
  2005. m_host.AddScriptLPS(1);
  2006. // Normalize indices (if negative).
  2007. // After normlaization they may still be
  2008. // negative, but that is now relative to
  2009. // the start, rather than the end, of the
  2010. // sequence.
  2011. if (start < 0)
  2012. {
  2013. start = src.Length + start;
  2014. }
  2015. if (start < 0 || start >= src.Length)
  2016. {
  2017. return src;
  2018. }
  2019. // Find matches beginning at start position
  2020. Regex matcher = new Regex(pattern);
  2021. return matcher.Replace(src,replace,count,start);
  2022. }
  2023. public string osLoadedCreationDate()
  2024. {
  2025. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationDate");
  2026. m_host.AddScriptLPS(1);
  2027. return World.RegionInfo.RegionSettings.LoadedCreationDate;
  2028. }
  2029. public string osLoadedCreationTime()
  2030. {
  2031. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationTime");
  2032. m_host.AddScriptLPS(1);
  2033. return World.RegionInfo.RegionSettings.LoadedCreationTime;
  2034. }
  2035. public string osLoadedCreationID()
  2036. {
  2037. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationID");
  2038. m_host.AddScriptLPS(1);
  2039. return World.RegionInfo.RegionSettings.LoadedCreationID;
  2040. }
  2041. /// <summary>
  2042. /// Get the primitive parameters of a linked prim.
  2043. /// </summary>
  2044. /// <remarks>
  2045. /// Threat level is 'Low' because certain users could possibly be tricked into
  2046. /// dropping an unverified script into one of their own objects, which could
  2047. /// then gather the physical construction details of the object and transmit it
  2048. /// to an unscrupulous third party, thus permitting unauthorized duplication of
  2049. /// the object's form.
  2050. /// </remarks>
  2051. /// <param name="linknumber"></param>
  2052. /// <param name="rules"></param>
  2053. /// <returns></returns>
  2054. public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules)
  2055. {
  2056. CheckThreatLevel(ThreatLevel.High, "osGetLinkPrimitiveParams");
  2057. m_host.AddScriptLPS(1);
  2058. InitLSL();
  2059. // One needs to cast m_LSL_Api because we're using functions not
  2060. // on the ILSL_Api interface.
  2061. LSL_Api LSL_Api = (LSL_Api)m_LSL_Api;
  2062. LSL_List retVal = new LSL_List();
  2063. LSL_List remaining = new LSL_List();
  2064. List<SceneObjectPart> parts = LSL_Api.GetLinkParts(linknumber);
  2065. foreach (SceneObjectPart part in parts)
  2066. {
  2067. remaining = LSL_Api.GetPrimParams(part, rules, ref retVal);
  2068. }
  2069. while (remaining.Length > 2)
  2070. {
  2071. linknumber = remaining.GetLSLIntegerItem(0);
  2072. rules = remaining.GetSublist(1, -1);
  2073. parts = LSL_Api.GetLinkParts(linknumber);
  2074. foreach (SceneObjectPart part in parts)
  2075. remaining = LSL_Api.GetPrimParams(part, rules, ref retVal);
  2076. }
  2077. return retVal;
  2078. }
  2079. public void osForceCreateLink(string target, int parent)
  2080. {
  2081. CheckThreatLevel(ThreatLevel.VeryLow, "osForceCreateLink");
  2082. m_host.AddScriptLPS(1);
  2083. InitLSL();
  2084. ((LSL_Api)m_LSL_Api).CreateLink(target, parent);
  2085. }
  2086. public void osForceBreakLink(int linknum)
  2087. {
  2088. CheckThreatLevel(ThreatLevel.VeryLow, "osForceBreakLink");
  2089. m_host.AddScriptLPS(1);
  2090. InitLSL();
  2091. ((LSL_Api)m_LSL_Api).BreakLink(linknum);
  2092. }
  2093. public void osForceBreakAllLinks()
  2094. {
  2095. CheckThreatLevel(ThreatLevel.VeryLow, "osForceBreakAllLinks");
  2096. m_host.AddScriptLPS(1);
  2097. InitLSL();
  2098. ((LSL_Api)m_LSL_Api).BreakAllLinks();
  2099. }
  2100. public LSL_Integer osIsNpc(LSL_Key npc)
  2101. {
  2102. CheckThreatLevel(ThreatLevel.None, "osIsNpc");
  2103. m_host.AddScriptLPS(1);
  2104. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2105. if (module != null)
  2106. {
  2107. UUID npcId;
  2108. if (UUID.TryParse(npc.m_string, out npcId))
  2109. if (module.IsNPC(npcId, World))
  2110. return ScriptBaseClass.TRUE;
  2111. }
  2112. return ScriptBaseClass.FALSE;
  2113. }
  2114. public LSL_Key osNpcCreate(string firstname, string lastname, LSL_Vector position, string notecard)
  2115. {
  2116. CheckThreatLevel(ThreatLevel.High, "osNpcCreate");
  2117. m_host.AddScriptLPS(1);
  2118. return NpcCreate(firstname, lastname, position, notecard, false, false);
  2119. }
  2120. public LSL_Key osNpcCreate(string firstname, string lastname, LSL_Vector position, string notecard, int options)
  2121. {
  2122. CheckThreatLevel(ThreatLevel.High, "osNpcCreate");
  2123. m_host.AddScriptLPS(1);
  2124. return NpcCreate(
  2125. firstname, lastname, position, notecard,
  2126. (options & ScriptBaseClass.OS_NPC_NOT_OWNED) == 0,
  2127. (options & ScriptBaseClass.OS_NPC_SENSE_AS_AGENT) != 0);
  2128. }
  2129. private LSL_Key NpcCreate(
  2130. string firstname, string lastname, LSL_Vector position, string notecard, bool owned, bool senseAsAgent)
  2131. {
  2132. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2133. if (module != null)
  2134. {
  2135. AvatarAppearance appearance = null;
  2136. UUID id;
  2137. if (UUID.TryParse(notecard, out id))
  2138. {
  2139. ScenePresence clonePresence = World.GetScenePresence(id);
  2140. if (clonePresence != null)
  2141. appearance = clonePresence.Appearance;
  2142. }
  2143. if (appearance == null)
  2144. {
  2145. string appearanceSerialized = LoadNotecard(notecard);
  2146. if (appearanceSerialized != null)
  2147. {
  2148. OSDMap appearanceOsd = (OSDMap)OSDParser.DeserializeLLSDXml(appearanceSerialized);
  2149. appearance = new AvatarAppearance();
  2150. appearance.Unpack(appearanceOsd);
  2151. }
  2152. else
  2153. {
  2154. OSSLError(string.Format("osNpcCreate: Notecard reference '{0}' not found.", notecard));
  2155. }
  2156. }
  2157. UUID ownerID = UUID.Zero;
  2158. if (owned)
  2159. ownerID = m_host.OwnerID;
  2160. UUID x = module.CreateNPC(firstname,
  2161. lastname,
  2162. position,
  2163. ownerID,
  2164. senseAsAgent,
  2165. World,
  2166. appearance);
  2167. return new LSL_Key(x.ToString());
  2168. }
  2169. return new LSL_Key(UUID.Zero.ToString());
  2170. }
  2171. /// <summary>
  2172. /// Save the current appearance of the NPC permanently to the named notecard.
  2173. /// </summary>
  2174. /// <param name="avatar"></param>
  2175. /// <param name="notecard">The name of the notecard to which to save the appearance.</param>
  2176. /// <returns>The asset ID of the notecard saved.</returns>
  2177. public LSL_Key osNpcSaveAppearance(LSL_Key npc, string notecard)
  2178. {
  2179. CheckThreatLevel(ThreatLevel.High, "osNpcSaveAppearance");
  2180. m_host.AddScriptLPS(1);
  2181. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2182. if (npcModule != null)
  2183. {
  2184. UUID npcId;
  2185. if (!UUID.TryParse(npc.m_string, out npcId))
  2186. return new LSL_Key(UUID.Zero.ToString());
  2187. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2188. return new LSL_Key(UUID.Zero.ToString());
  2189. return SaveAppearanceToNotecard(npcId, notecard);
  2190. }
  2191. return new LSL_Key(UUID.Zero.ToString());
  2192. }
  2193. public void osNpcLoadAppearance(LSL_Key npc, string notecard)
  2194. {
  2195. CheckThreatLevel(ThreatLevel.High, "osNpcLoadAppearance");
  2196. m_host.AddScriptLPS(1);
  2197. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2198. if (npcModule != null)
  2199. {
  2200. UUID npcId;
  2201. if (!UUID.TryParse(npc.m_string, out npcId))
  2202. return;
  2203. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2204. return;
  2205. string appearanceSerialized = LoadNotecard(notecard);
  2206. if (appearanceSerialized == null)
  2207. OSSLError(string.Format("osNpcCreate: Notecard reference '{0}' not found.", notecard));
  2208. OSDMap appearanceOsd = (OSDMap)OSDParser.DeserializeLLSDXml(appearanceSerialized);
  2209. // OSD a = OSDParser.DeserializeLLSDXml(appearanceSerialized);
  2210. // Console.WriteLine("appearanceSerialized {0}", appearanceSerialized);
  2211. // Console.WriteLine("a.Type {0}, a.ToString() {1}", a.Type, a);
  2212. AvatarAppearance appearance = new AvatarAppearance();
  2213. appearance.Unpack(appearanceOsd);
  2214. npcModule.SetNPCAppearance(npcId, appearance, m_host.ParentGroup.Scene);
  2215. }
  2216. }
  2217. public LSL_Key osNpcGetOwner(LSL_Key npc)
  2218. {
  2219. CheckThreatLevel(ThreatLevel.None, "osNpcGetOwner");
  2220. m_host.AddScriptLPS(1);
  2221. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2222. if (npcModule != null)
  2223. {
  2224. UUID npcId;
  2225. if (UUID.TryParse(npc.m_string, out npcId))
  2226. {
  2227. UUID owner = npcModule.GetOwner(npcId);
  2228. if (owner != UUID.Zero)
  2229. return new LSL_Key(owner.ToString());
  2230. else
  2231. return npc;
  2232. }
  2233. }
  2234. return new LSL_Key(UUID.Zero.ToString());
  2235. }
  2236. public LSL_Vector osNpcGetPos(LSL_Key npc)
  2237. {
  2238. CheckThreatLevel(ThreatLevel.High, "osNpcGetPos");
  2239. m_host.AddScriptLPS(1);
  2240. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2241. if (npcModule != null)
  2242. {
  2243. UUID npcId;
  2244. if (!UUID.TryParse(npc.m_string, out npcId))
  2245. return new LSL_Vector(0, 0, 0);
  2246. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2247. return new LSL_Vector(0, 0, 0);
  2248. ScenePresence sp = World.GetScenePresence(npcId);
  2249. if (sp != null)
  2250. return new LSL_Vector(sp.AbsolutePosition);
  2251. }
  2252. return Vector3.Zero;
  2253. }
  2254. public void osNpcMoveTo(LSL_Key npc, LSL_Vector pos)
  2255. {
  2256. CheckThreatLevel(ThreatLevel.High, "osNpcMoveTo");
  2257. m_host.AddScriptLPS(1);
  2258. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2259. if (module != null)
  2260. {
  2261. UUID npcId;
  2262. if (!UUID.TryParse(npc.m_string, out npcId))
  2263. return;
  2264. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2265. return;
  2266. module.MoveToTarget(npcId, World, pos, false, true, false);
  2267. }
  2268. }
  2269. public void osNpcMoveToTarget(LSL_Key npc, LSL_Vector target, int options)
  2270. {
  2271. CheckThreatLevel(ThreatLevel.High, "osNpcMoveToTarget");
  2272. m_host.AddScriptLPS(1);
  2273. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2274. if (module != null)
  2275. {
  2276. UUID npcId;
  2277. if (!UUID.TryParse(npc.m_string, out npcId))
  2278. return;
  2279. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2280. return;
  2281. module.MoveToTarget(
  2282. new UUID(npc.m_string),
  2283. World,
  2284. target,
  2285. (options & ScriptBaseClass.OS_NPC_NO_FLY) != 0,
  2286. (options & ScriptBaseClass.OS_NPC_LAND_AT_TARGET) != 0,
  2287. (options & ScriptBaseClass.OS_NPC_RUNNING) != 0);
  2288. }
  2289. }
  2290. public LSL_Rotation osNpcGetRot(LSL_Key npc)
  2291. {
  2292. CheckThreatLevel(ThreatLevel.High, "osNpcGetRot");
  2293. m_host.AddScriptLPS(1);
  2294. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2295. if (npcModule != null)
  2296. {
  2297. UUID npcId;
  2298. if (!UUID.TryParse(npc.m_string, out npcId))
  2299. return new LSL_Rotation(Quaternion.Identity);
  2300. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2301. return new LSL_Rotation(Quaternion.Identity);
  2302. ScenePresence sp = World.GetScenePresence(npcId);
  2303. if (sp != null)
  2304. return new LSL_Rotation(sp.GetWorldRotation());
  2305. }
  2306. return Quaternion.Identity;
  2307. }
  2308. public void osNpcSetRot(LSL_Key npc, LSL_Rotation rotation)
  2309. {
  2310. CheckThreatLevel(ThreatLevel.High, "osNpcSetRot");
  2311. m_host.AddScriptLPS(1);
  2312. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2313. if (npcModule != null)
  2314. {
  2315. UUID npcId;
  2316. if (!UUID.TryParse(npc.m_string, out npcId))
  2317. return;
  2318. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2319. return;
  2320. ScenePresence sp = World.GetScenePresence(npcId);
  2321. if (sp != null)
  2322. sp.Rotation = rotation;
  2323. }
  2324. }
  2325. public void osNpcStopMoveToTarget(LSL_Key npc)
  2326. {
  2327. CheckThreatLevel(ThreatLevel.High, "osNpcStopMoveToTarget");
  2328. m_host.AddScriptLPS(1);
  2329. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2330. if (module != null)
  2331. {
  2332. UUID npcId = new UUID(npc.m_string);
  2333. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2334. return;
  2335. module.StopMoveToTarget(npcId, World);
  2336. }
  2337. }
  2338. public void osNpcSay(LSL_Key npc, string message)
  2339. {
  2340. osNpcSay(npc, 0, message);
  2341. }
  2342. public void osNpcSay(LSL_Key npc, int channel, string message)
  2343. {
  2344. CheckThreatLevel(ThreatLevel.High, "osNpcSay");
  2345. m_host.AddScriptLPS(1);
  2346. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2347. if (module != null)
  2348. {
  2349. UUID npcId = new UUID(npc.m_string);
  2350. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2351. return;
  2352. module.Say(npcId, World, message, channel);
  2353. }
  2354. }
  2355. public void osNpcShout(LSL_Key npc, int channel, string message)
  2356. {
  2357. CheckThreatLevel(ThreatLevel.High, "osNpcShout");
  2358. m_host.AddScriptLPS(1);
  2359. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2360. if (module != null)
  2361. {
  2362. UUID npcId = new UUID(npc.m_string);
  2363. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2364. return;
  2365. module.Shout(npcId, World, message, channel);
  2366. }
  2367. }
  2368. public void osNpcSit(LSL_Key npc, LSL_Key target, int options)
  2369. {
  2370. CheckThreatLevel(ThreatLevel.High, "osNpcSit");
  2371. m_host.AddScriptLPS(1);
  2372. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2373. if (module != null)
  2374. {
  2375. UUID npcId = new UUID(npc.m_string);
  2376. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2377. return;
  2378. module.Sit(npcId, new UUID(target.m_string), World);
  2379. }
  2380. }
  2381. public void osNpcStand(LSL_Key npc)
  2382. {
  2383. CheckThreatLevel(ThreatLevel.High, "osNpcStand");
  2384. m_host.AddScriptLPS(1);
  2385. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2386. if (module != null)
  2387. {
  2388. UUID npcId = new UUID(npc.m_string);
  2389. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2390. return;
  2391. module.Stand(npcId, World);
  2392. }
  2393. }
  2394. public void osNpcRemove(LSL_Key npc)
  2395. {
  2396. CheckThreatLevel(ThreatLevel.High, "osNpcRemove");
  2397. m_host.AddScriptLPS(1);
  2398. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2399. if (module != null)
  2400. {
  2401. UUID npcId = new UUID(npc.m_string);
  2402. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2403. return;
  2404. module.DeleteNPC(npcId, World);
  2405. }
  2406. }
  2407. public void osNpcPlayAnimation(LSL_Key npc, string animation)
  2408. {
  2409. CheckThreatLevel(ThreatLevel.High, "osNpcPlayAnimation");
  2410. m_host.AddScriptLPS(1);
  2411. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2412. if (module != null)
  2413. {
  2414. UUID npcID = new UUID(npc.m_string);
  2415. if (module.CheckPermissions(npcID, m_host.OwnerID))
  2416. AvatarPlayAnimation(npcID.ToString(), animation);
  2417. }
  2418. }
  2419. public void osNpcStopAnimation(LSL_Key npc, string animation)
  2420. {
  2421. CheckThreatLevel(ThreatLevel.High, "osNpcStopAnimation");
  2422. m_host.AddScriptLPS(1);
  2423. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2424. if (module != null)
  2425. {
  2426. UUID npcID = new UUID(npc.m_string);
  2427. if (module.CheckPermissions(npcID, m_host.OwnerID))
  2428. AvatarStopAnimation(npcID.ToString(), animation);
  2429. }
  2430. }
  2431. public void osNpcWhisper(LSL_Key npc, int channel, string message)
  2432. {
  2433. CheckThreatLevel(ThreatLevel.High, "osNpcWhisper");
  2434. m_host.AddScriptLPS(1);
  2435. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2436. if (module != null)
  2437. {
  2438. UUID npcId = new UUID(npc.m_string);
  2439. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2440. return;
  2441. module.Whisper(npcId, World, message, channel);
  2442. }
  2443. }
  2444. public void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num)
  2445. {
  2446. CheckThreatLevel(ThreatLevel.High, "osNpcTouch");
  2447. m_host.AddScriptLPS(1);
  2448. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2449. int linkNum = link_num.value;
  2450. if (module != null || (linkNum < 0 && linkNum != ScriptBaseClass.LINK_THIS))
  2451. {
  2452. UUID npcId;
  2453. if (!UUID.TryParse(npcLSL_Key, out npcId) || !module.CheckPermissions(npcId, m_host.OwnerID))
  2454. return;
  2455. SceneObjectPart part = null;
  2456. UUID objectId;
  2457. if (UUID.TryParse(LSL_String.ToString(object_key), out objectId))
  2458. part = World.GetSceneObjectPart(objectId);
  2459. if (part == null)
  2460. return;
  2461. if (linkNum != ScriptBaseClass.LINK_THIS)
  2462. {
  2463. if (linkNum == 0 || linkNum == ScriptBaseClass.LINK_ROOT)
  2464. { // 0 and 1 are treated as root, find the root if the current part isnt it
  2465. if (!part.IsRoot)
  2466. part = part.ParentGroup.RootPart;
  2467. }
  2468. else
  2469. { // Find the prim with the given link number if not found then fail silently
  2470. part = part.ParentGroup.GetLinkNumPart(linkNum);
  2471. if (part == null)
  2472. return;
  2473. }
  2474. }
  2475. module.Touch(npcId, part.UUID);
  2476. }
  2477. }
  2478. /// <summary>
  2479. /// Save the current appearance of the script owner permanently to the named notecard.
  2480. /// </summary>
  2481. /// <param name="notecard">The name of the notecard to which to save the appearance.</param>
  2482. /// <returns>The asset ID of the notecard saved.</returns>
  2483. public LSL_Key osOwnerSaveAppearance(string notecard)
  2484. {
  2485. CheckThreatLevel(ThreatLevel.High, "osOwnerSaveAppearance");
  2486. m_host.AddScriptLPS(1);
  2487. return SaveAppearanceToNotecard(m_host.OwnerID, notecard);
  2488. }
  2489. public LSL_Key osAgentSaveAppearance(LSL_Key avatarId, string notecard)
  2490. {
  2491. CheckThreatLevel(ThreatLevel.VeryHigh, "osAgentSaveAppearance");
  2492. m_host.AddScriptLPS(1);
  2493. return SaveAppearanceToNotecard(avatarId, notecard);
  2494. }
  2495. protected LSL_Key SaveAppearanceToNotecard(ScenePresence sp, string notecard)
  2496. {
  2497. IAvatarFactoryModule appearanceModule = World.RequestModuleInterface<IAvatarFactoryModule>();
  2498. if (appearanceModule != null)
  2499. {
  2500. appearanceModule.SaveBakedTextures(sp.UUID);
  2501. OSDMap appearancePacked = sp.Appearance.Pack();
  2502. TaskInventoryItem item
  2503. = SaveNotecard(notecard, "Avatar Appearance", Util.GetFormattedXml(appearancePacked as OSD), true);
  2504. return new LSL_Key(item.AssetID.ToString());
  2505. }
  2506. else
  2507. {
  2508. return new LSL_Key(UUID.Zero.ToString());
  2509. }
  2510. }
  2511. protected LSL_Key SaveAppearanceToNotecard(UUID avatarId, string notecard)
  2512. {
  2513. ScenePresence sp = World.GetScenePresence(avatarId);
  2514. if (sp == null || sp.IsChildAgent)
  2515. return new LSL_Key(UUID.Zero.ToString());
  2516. return SaveAppearanceToNotecard(sp, notecard);
  2517. }
  2518. protected LSL_Key SaveAppearanceToNotecard(LSL_Key rawAvatarId, string notecard)
  2519. {
  2520. UUID avatarId;
  2521. if (!UUID.TryParse(rawAvatarId, out avatarId))
  2522. return new LSL_Key(UUID.Zero.ToString());
  2523. return SaveAppearanceToNotecard(avatarId, notecard);
  2524. }
  2525. /// <summary>
  2526. /// Get the gender as specified in avatar appearance for a given avatar key
  2527. /// </summary>
  2528. /// <param name="rawAvatarId"></param>
  2529. /// <returns>"male" or "female" or "unknown"</returns>
  2530. public LSL_String osGetGender(LSL_Key rawAvatarId)
  2531. {
  2532. CheckThreatLevel(ThreatLevel.None, "osGetGender");
  2533. m_host.AddScriptLPS(1);
  2534. UUID avatarId;
  2535. if (!UUID.TryParse(rawAvatarId, out avatarId))
  2536. return new LSL_String("unknown");
  2537. ScenePresence sp = World.GetScenePresence(avatarId);
  2538. if (sp == null || sp.IsChildAgent || sp.Appearance == null || sp.Appearance.VisualParams == null)
  2539. return new LSL_String("unknown");
  2540. // find the index of "shape" parameter "male"
  2541. int vpShapeMaleIndex = 0;
  2542. bool indexFound = false;
  2543. VisualParam param = new VisualParam();
  2544. foreach(var vpEntry in VisualParams.Params)
  2545. {
  2546. param = vpEntry.Value;
  2547. if (param.Name == "male" && param.Wearable == "shape")
  2548. {
  2549. indexFound = true;
  2550. break;
  2551. }
  2552. if (param.Group == 0)
  2553. vpShapeMaleIndex++;
  2554. }
  2555. if (!indexFound)
  2556. return new LSL_String("unknown");
  2557. float vpShapeMale = Utils.ByteToFloat(sp.Appearance.VisualParams[vpShapeMaleIndex], param.MinValue, param.MaxValue);
  2558. bool isMale = vpShapeMale > 0.5f;
  2559. return new LSL_String(isMale ? "male" : "female");
  2560. }
  2561. /// <summary>
  2562. /// Get current region's map texture UUID
  2563. /// </summary>
  2564. /// <returns></returns>
  2565. public LSL_Key osGetMapTexture()
  2566. {
  2567. CheckThreatLevel(ThreatLevel.None, "osGetMapTexture");
  2568. m_host.AddScriptLPS(1);
  2569. return m_ScriptEngine.World.RegionInfo.RegionSettings.TerrainImageID.ToString();
  2570. }
  2571. /// <summary>
  2572. /// Get a region's map texture UUID by region UUID or name.
  2573. /// </summary>
  2574. /// <param name="regionName"></param>
  2575. /// <returns></returns>
  2576. public LSL_Key osGetRegionMapTexture(string regionName)
  2577. {
  2578. CheckThreatLevel(ThreatLevel.High, "osGetRegionMapTexture");
  2579. m_host.AddScriptLPS(1);
  2580. Scene scene = m_ScriptEngine.World;
  2581. UUID key = UUID.Zero;
  2582. GridRegion region;
  2583. //If string is a key, use it. Otherwise, try to locate region by name.
  2584. if (UUID.TryParse(regionName, out key))
  2585. region = scene.GridService.GetRegionByUUID(UUID.Zero, key);
  2586. else
  2587. region = scene.GridService.GetRegionByName(UUID.Zero, regionName);
  2588. // If region was found, return the regions map texture key.
  2589. if (region != null)
  2590. key = region.TerrainImage;
  2591. ScriptSleep(1000);
  2592. return key.ToString();
  2593. }
  2594. /// <summary>
  2595. /// Return information regarding various simulator statistics (sim fps, physics fps, time
  2596. /// dilation, total number of prims, total number of active scripts, script lps, various
  2597. /// timing data, packets in/out, etc. Basically much the information that's shown in the
  2598. /// client's Statistics Bar (Ctrl-Shift-1)
  2599. /// </summary>
  2600. /// <returns>List of floats</returns>
  2601. public LSL_List osGetRegionStats()
  2602. {
  2603. CheckThreatLevel(ThreatLevel.Moderate, "osGetRegionStats");
  2604. m_host.AddScriptLPS(1);
  2605. LSL_List ret = new LSL_List();
  2606. float[] stats = World.StatsReporter.LastReportedSimStats;
  2607. for (int i = 0; i < 21; i++)
  2608. {
  2609. ret.Add(new LSL_Float(stats[i]));
  2610. }
  2611. return ret;
  2612. }
  2613. public LSL_Vector osGetRegionSize()
  2614. {
  2615. CheckThreatLevel(ThreatLevel.None, "osGetRegionSize");
  2616. m_host.AddScriptLPS(1);
  2617. bool isMegaregion;
  2618. IRegionCombinerModule rcMod = World.RequestModuleInterface<IRegionCombinerModule>();
  2619. if (rcMod != null)
  2620. isMegaregion = rcMod.IsRootForMegaregion(World.RegionInfo.RegionID);
  2621. else
  2622. isMegaregion = false;
  2623. if (isMegaregion)
  2624. {
  2625. Vector2 size = rcMod.GetSizeOfMegaregion(World.RegionInfo.RegionID);
  2626. return new LSL_Vector(size.X, size.Y, Constants.RegionHeight);
  2627. }
  2628. else
  2629. {
  2630. Scene scene = m_ScriptEngine.World;
  2631. GridRegion region = scene.GridService.GetRegionByUUID(UUID.Zero, World.RegionInfo.RegionID);
  2632. return new LSL_Vector((float)region.RegionSizeX, (float)region.RegionSizeX, Constants.RegionHeight);
  2633. }
  2634. }
  2635. public int osGetSimulatorMemory()
  2636. {
  2637. CheckThreatLevel(ThreatLevel.Moderate, "osGetSimulatorMemory");
  2638. m_host.AddScriptLPS(1);
  2639. long pws = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
  2640. if (pws > Int32.MaxValue)
  2641. return Int32.MaxValue;
  2642. if (pws < 0)
  2643. return 0;
  2644. return (int)pws;
  2645. }
  2646. public void osSetSpeed(string UUID, LSL_Float SpeedModifier)
  2647. {
  2648. CheckThreatLevel(ThreatLevel.Moderate, "osSetSpeed");
  2649. m_host.AddScriptLPS(1);
  2650. ScenePresence avatar = World.GetScenePresence(new UUID(UUID));
  2651. if (avatar != null)
  2652. avatar.SpeedModifier = (float)SpeedModifier;
  2653. }
  2654. public void osKickAvatar(string FirstName, string SurName, string alert)
  2655. {
  2656. CheckThreatLevel(ThreatLevel.Severe, "osKickAvatar");
  2657. m_host.AddScriptLPS(1);
  2658. World.ForEachRootScenePresence(delegate(ScenePresence sp)
  2659. {
  2660. if (sp.Firstname == FirstName && sp.Lastname == SurName)
  2661. {
  2662. // kick client...
  2663. if (alert != null)
  2664. sp.ControllingClient.Kick(alert);
  2665. // ...and close on our side
  2666. sp.Scene.CloseAgent(sp.UUID, false);
  2667. }
  2668. });
  2669. }
  2670. public LSL_Float osGetHealth(string avatar)
  2671. {
  2672. CheckThreatLevel(ThreatLevel.None, "osGetHealth");
  2673. m_host.AddScriptLPS(1);
  2674. LSL_Float health = new LSL_Float(-1);
  2675. ScenePresence presence = World.GetScenePresence(new UUID(avatar));
  2676. if (presence != null) health = presence.Health;
  2677. return health;
  2678. }
  2679. public void osCauseDamage(string avatar, double damage)
  2680. {
  2681. CheckThreatLevel(ThreatLevel.High, "osCauseDamage");
  2682. m_host.AddScriptLPS(1);
  2683. UUID avatarId = new UUID(avatar);
  2684. Vector3 pos = m_host.GetWorldPosition();
  2685. ScenePresence presence = World.GetScenePresence(avatarId);
  2686. if (presence != null)
  2687. {
  2688. LandData land = World.GetLandData(pos);
  2689. if ((land.Flags & (uint)ParcelFlags.AllowDamage) == (uint)ParcelFlags.AllowDamage)
  2690. {
  2691. float health = presence.Health;
  2692. health -= (float)damage;
  2693. presence.setHealthWithUpdate(health);
  2694. if (health <= 0)
  2695. {
  2696. float healthliveagain = 100;
  2697. presence.ControllingClient.SendAgentAlertMessage("You died!", true);
  2698. presence.setHealthWithUpdate(healthliveagain);
  2699. presence.Scene.TeleportClientHome(presence.UUID, presence.ControllingClient);
  2700. }
  2701. }
  2702. }
  2703. }
  2704. public void osCauseHealing(string avatar, double healing)
  2705. {
  2706. CheckThreatLevel(ThreatLevel.High, "osCauseHealing");
  2707. m_host.AddScriptLPS(1);
  2708. UUID avatarId = new UUID(avatar);
  2709. ScenePresence presence = World.GetScenePresence(avatarId);
  2710. if (presence != null && World.ScriptDanger(m_host.LocalId, m_host.GetWorldPosition()))
  2711. {
  2712. float health = presence.Health;
  2713. health += (float)healing;
  2714. if (health >= 100)
  2715. health = 100;
  2716. presence.setHealthWithUpdate(health);
  2717. }
  2718. }
  2719. public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules)
  2720. {
  2721. CheckThreatLevel(ThreatLevel.High, "osGetPrimitiveParams");
  2722. m_host.AddScriptLPS(1);
  2723. InitLSL();
  2724. return m_LSL_Api.GetPrimitiveParamsEx(prim, rules);
  2725. }
  2726. public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules)
  2727. {
  2728. CheckThreatLevel(ThreatLevel.High, "osSetPrimitiveParams");
  2729. m_host.AddScriptLPS(1);
  2730. InitLSL();
  2731. m_LSL_Api.SetPrimitiveParamsEx(prim, rules, "osSetPrimitiveParams");
  2732. }
  2733. /// <summary>
  2734. /// Set parameters for light projection in host prim
  2735. /// </summary>
  2736. public void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb)
  2737. {
  2738. CheckThreatLevel(ThreatLevel.High, "osSetProjectionParams");
  2739. osSetProjectionParams(UUID.Zero.ToString(), projection, texture, fov, focus, amb);
  2740. }
  2741. /// <summary>
  2742. /// Set parameters for light projection with uuid of target prim
  2743. /// </summary>
  2744. public void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb)
  2745. {
  2746. CheckThreatLevel(ThreatLevel.High, "osSetProjectionParams");
  2747. m_host.AddScriptLPS(1);
  2748. SceneObjectPart obj = null;
  2749. if (prim == UUID.Zero.ToString())
  2750. {
  2751. obj = m_host;
  2752. }
  2753. else
  2754. {
  2755. obj = World.GetSceneObjectPart(new UUID(prim));
  2756. if (obj == null)
  2757. return;
  2758. }
  2759. obj.Shape.ProjectionEntry = projection;
  2760. obj.Shape.ProjectionTextureUUID = new UUID(texture);
  2761. obj.Shape.ProjectionFOV = (float)fov;
  2762. obj.Shape.ProjectionFocus = (float)focus;
  2763. obj.Shape.ProjectionAmbiance = (float)amb;
  2764. obj.ParentGroup.HasGroupChanged = true;
  2765. obj.ScheduleFullUpdate();
  2766. }
  2767. /// <summary>
  2768. /// Like osGetAgents but returns enough info for a radar
  2769. /// </summary>
  2770. /// <returns>Strided list of the UUID, position and name of each avatar in the region</returns>
  2771. public LSL_List osGetAvatarList()
  2772. {
  2773. CheckThreatLevel(ThreatLevel.None, "osGetAvatarList");
  2774. m_host.AddScriptLPS(1);
  2775. LSL_List result = new LSL_List();
  2776. World.ForEachRootScenePresence(delegate (ScenePresence avatar)
  2777. {
  2778. if (avatar != null && avatar.UUID != m_host.OwnerID)
  2779. {
  2780. result.Add(new LSL_String(avatar.UUID.ToString()));
  2781. result.Add(new LSL_Vector(avatar.AbsolutePosition));
  2782. result.Add(new LSL_String(avatar.Name));
  2783. }
  2784. });
  2785. return result;
  2786. }
  2787. /// <summary>
  2788. /// Convert a unix time to a llGetTimestamp() like string
  2789. /// </summary>
  2790. /// <param name="unixTime"></param>
  2791. /// <returns></returns>
  2792. public LSL_String osUnixTimeToTimestamp(long time)
  2793. {
  2794. CheckThreatLevel(ThreatLevel.VeryLow, "osUnixTimeToTimestamp");
  2795. m_host.AddScriptLPS(1);
  2796. long baseTicks = 621355968000000000;
  2797. long tickResolution = 10000000;
  2798. long epochTicks = (time * tickResolution) + baseTicks;
  2799. DateTime date = new DateTime(epochTicks);
  2800. return date.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ");
  2801. }
  2802. /// <summary>
  2803. /// Get the description from an inventory item
  2804. /// </summary>
  2805. /// <param name="inventoryName"></param>
  2806. /// <returns>Item description</returns>
  2807. public LSL_String osGetInventoryDesc(string item)
  2808. {
  2809. m_host.AddScriptLPS(1);
  2810. lock (m_host.TaskInventory)
  2811. {
  2812. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  2813. {
  2814. if (inv.Value.Name == item)
  2815. {
  2816. return inv.Value.Description.ToString();
  2817. }
  2818. }
  2819. }
  2820. return String.Empty;
  2821. }
  2822. /// <summary>
  2823. /// Invite user to the group this object is set to
  2824. /// </summary>
  2825. /// <param name="agentId"></param>
  2826. /// <returns></returns>
  2827. public LSL_Integer osInviteToGroup(LSL_Key agentId)
  2828. {
  2829. CheckThreatLevel(ThreatLevel.VeryLow, "osInviteToGroup");
  2830. m_host.AddScriptLPS(1);
  2831. UUID agent = new UUID(agentId);
  2832. // groups module is required
  2833. IGroupsModule groupsModule = m_ScriptEngine.World.RequestModuleInterface<IGroupsModule>();
  2834. if (groupsModule == null) return ScriptBaseClass.FALSE;
  2835. // object has to be set to a group, but not group owned
  2836. if (m_host.GroupID == UUID.Zero || m_host.GroupID == m_host.OwnerID) return ScriptBaseClass.FALSE;
  2837. // object owner has to be in that group and required permissions
  2838. GroupMembershipData member = groupsModule.GetMembershipData(m_host.GroupID, m_host.OwnerID);
  2839. if (member == null || (member.GroupPowers & (ulong)GroupPowers.Invite) == 0) return ScriptBaseClass.FALSE;
  2840. // check if agent is in that group already
  2841. //member = groupsModule.GetMembershipData(agent, m_host.GroupID, agent);
  2842. //if (member != null) return ScriptBaseClass.FALSE;
  2843. // invited agent has to be present in this scene
  2844. if (World.GetScenePresence(agent) == null) return ScriptBaseClass.FALSE;
  2845. groupsModule.InviteGroup(null, m_host.OwnerID, m_host.GroupID, agent, UUID.Zero);
  2846. return ScriptBaseClass.TRUE;
  2847. }
  2848. /// <summary>
  2849. /// Eject user from the group this object is set to
  2850. /// </summary>
  2851. /// <param name="agentId"></param>
  2852. /// <returns></returns>
  2853. public LSL_Integer osEjectFromGroup(LSL_Key agentId)
  2854. {
  2855. CheckThreatLevel(ThreatLevel.VeryLow, "osEjectFromGroup");
  2856. m_host.AddScriptLPS(1);
  2857. UUID agent = new UUID(agentId);
  2858. // groups module is required
  2859. IGroupsModule groupsModule = m_ScriptEngine.World.RequestModuleInterface<IGroupsModule>();
  2860. if (groupsModule == null) return ScriptBaseClass.FALSE;
  2861. // object has to be set to a group, but not group owned
  2862. if (m_host.GroupID == UUID.Zero || m_host.GroupID == m_host.OwnerID) return ScriptBaseClass.FALSE;
  2863. // object owner has to be in that group and required permissions
  2864. GroupMembershipData member = groupsModule.GetMembershipData(m_host.GroupID, m_host.OwnerID);
  2865. if (member == null || (member.GroupPowers & (ulong)GroupPowers.Eject) == 0) return ScriptBaseClass.FALSE;
  2866. // agent has to be in that group
  2867. //member = groupsModule.GetMembershipData(agent, m_host.GroupID, agent);
  2868. //if (member == null) return ScriptBaseClass.FALSE;
  2869. // ejectee can be offline
  2870. groupsModule.EjectGroupMember(null, m_host.OwnerID, m_host.GroupID, agent);
  2871. return ScriptBaseClass.TRUE;
  2872. }
  2873. /// <summary>
  2874. /// Sets terrain estate texture
  2875. /// </summary>
  2876. /// <param name="level"></param>
  2877. /// <param name="texture"></param>
  2878. /// <returns></returns>
  2879. public void osSetTerrainTexture(int level, LSL_Key texture)
  2880. {
  2881. CheckThreatLevel(ThreatLevel.High, "osSetTerrainTexture");
  2882. m_host.AddScriptLPS(1);
  2883. //Check to make sure that the script's owner is the estate manager/master
  2884. //World.Permissions.GenericEstatePermission(
  2885. if (World.Permissions.IsGod(m_host.OwnerID))
  2886. {
  2887. if (level < 0 || level > 3)
  2888. return;
  2889. UUID textureID = new UUID();
  2890. if (!UUID.TryParse(texture, out textureID))
  2891. return;
  2892. // estate module is required
  2893. IEstateModule estate = World.RequestModuleInterface<IEstateModule>();
  2894. if (estate != null)
  2895. estate.setEstateTerrainBaseTexture(level, textureID);
  2896. }
  2897. }
  2898. /// <summary>
  2899. /// Sets terrain heights of estate
  2900. /// </summary>
  2901. /// <param name="corner"></param>
  2902. /// <param name="low"></param>
  2903. /// <param name="high"></param>
  2904. /// <returns></returns>
  2905. public void osSetTerrainTextureHeight(int corner, double low, double high)
  2906. {
  2907. CheckThreatLevel(ThreatLevel.High, "osSetTerrainTextureHeight");
  2908. m_host.AddScriptLPS(1);
  2909. //Check to make sure that the script's owner is the estate manager/master
  2910. //World.Permissions.GenericEstatePermission(
  2911. if (World.Permissions.IsGod(m_host.OwnerID))
  2912. {
  2913. if (corner < 0 || corner > 3)
  2914. return;
  2915. // estate module is required
  2916. IEstateModule estate = World.RequestModuleInterface<IEstateModule>();
  2917. if (estate != null)
  2918. estate.setEstateTerrainTextureHeights(corner, (float)low, (float)high);
  2919. }
  2920. }
  2921. #region Attachment commands
  2922. public void osForceAttachToAvatar(int attachmentPoint)
  2923. {
  2924. CheckThreatLevel(ThreatLevel.High, "osForceAttachToAvatar");
  2925. m_host.AddScriptLPS(1);
  2926. InitLSL();
  2927. ((LSL_Api)m_LSL_Api).AttachToAvatar(attachmentPoint);
  2928. }
  2929. public void osForceAttachToAvatarFromInventory(string itemName, int attachmentPoint)
  2930. {
  2931. CheckThreatLevel(ThreatLevel.High, "osForceAttachToAvatarFromInventory");
  2932. m_host.AddScriptLPS(1);
  2933. ForceAttachToAvatarFromInventory(m_host.OwnerID, itemName, attachmentPoint);
  2934. }
  2935. public void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint)
  2936. {
  2937. CheckThreatLevel(ThreatLevel.VeryHigh, "osForceAttachToOtherAvatarFromInventory");
  2938. m_host.AddScriptLPS(1);
  2939. UUID avatarId;
  2940. if (!UUID.TryParse(rawAvatarId, out avatarId))
  2941. return;
  2942. ForceAttachToAvatarFromInventory(avatarId, itemName, attachmentPoint);
  2943. }
  2944. public void ForceAttachToAvatarFromInventory(UUID avatarId, string itemName, int attachmentPoint)
  2945. {
  2946. IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
  2947. if (attachmentsModule == null)
  2948. return;
  2949. InitLSL();
  2950. TaskInventoryItem item = m_host.Inventory.GetInventoryItem(itemName);
  2951. if (item == null)
  2952. {
  2953. ((LSL_Api)m_LSL_Api).llSay(0, string.Format("Could not find object '{0}'", itemName));
  2954. throw new Exception(String.Format("The inventory item '{0}' could not be found", itemName));
  2955. }
  2956. if (item.InvType != (int)InventoryType.Object)
  2957. {
  2958. // FIXME: Temporary null check for regression tests since they dont' have the infrastructure to set
  2959. // up the api reference.
  2960. if (m_LSL_Api != null)
  2961. ((LSL_Api)m_LSL_Api).llSay(0, string.Format("Unable to attach, item '{0}' is not an object.", itemName));
  2962. throw new Exception(String.Format("The inventory item '{0}' is not an object", itemName));
  2963. }
  2964. ScenePresence sp = World.GetScenePresence(avatarId);
  2965. if (sp == null)
  2966. return;
  2967. string message;
  2968. InventoryItemBase newItem = World.MoveTaskInventoryItem(sp.UUID, UUID.Zero, m_host, item.ItemID, out message);
  2969. if (newItem == null)
  2970. {
  2971. m_log.ErrorFormat(
  2972. "[OSSL API]: Could not create user inventory item {0} for {1}, attach point {2} in {3}: {4}",
  2973. itemName, m_host.Name, attachmentPoint, World.Name, message);
  2974. ((LSL_Api)m_LSL_Api).llSay(0, message);
  2975. return;
  2976. }
  2977. attachmentsModule.RezSingleAttachmentFromInventory(sp, newItem.ID, (uint)attachmentPoint);
  2978. }
  2979. public void osForceDetachFromAvatar()
  2980. {
  2981. CheckThreatLevel(ThreatLevel.High, "osForceDetachFromAvatar");
  2982. m_host.AddScriptLPS(1);
  2983. InitLSL();
  2984. ((LSL_Api)m_LSL_Api).DetachFromAvatar();
  2985. }
  2986. public LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints)
  2987. {
  2988. CheckThreatLevel(ThreatLevel.Moderate, "osGetNumberOfAttachments");
  2989. m_host.AddScriptLPS(1);
  2990. UUID targetUUID;
  2991. ScenePresence target;
  2992. LSL_List resp = new LSL_List();
  2993. if (attachmentPoints.Length >= 1 && UUID.TryParse(avatar.ToString(), out targetUUID) && World.TryGetScenePresence(targetUUID, out target))
  2994. {
  2995. foreach (object point in attachmentPoints.Data)
  2996. {
  2997. LSL_Integer ipoint = new LSL_Integer(
  2998. (point is LSL_Integer || point is int || point is uint) ?
  2999. (int)point :
  3000. 0
  3001. );
  3002. resp.Add(ipoint);
  3003. if (ipoint == 0)
  3004. {
  3005. // indicates zero attachments
  3006. resp.Add(new LSL_Integer(0));
  3007. }
  3008. else
  3009. {
  3010. // gets the number of attachments on the attachment point
  3011. resp.Add(new LSL_Integer(target.GetAttachments((uint)ipoint).Count));
  3012. }
  3013. }
  3014. }
  3015. return resp;
  3016. }
  3017. public void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int options)
  3018. {
  3019. CheckThreatLevel(ThreatLevel.Moderate, "osMessageAttachments");
  3020. m_host.AddScriptLPS(1);
  3021. UUID targetUUID;
  3022. ScenePresence target;
  3023. if (attachmentPoints.Length >= 1 && UUID.TryParse(avatar.ToString(), out targetUUID) && World.TryGetScenePresence(targetUUID, out target))
  3024. {
  3025. List<int> aps = new List<int>();
  3026. foreach (object point in attachmentPoints.Data)
  3027. {
  3028. int ipoint;
  3029. if (int.TryParse(point.ToString(), out ipoint))
  3030. {
  3031. aps.Add(ipoint);
  3032. }
  3033. }
  3034. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  3035. bool msgAll = aps.Contains(ScriptBaseClass.OS_ATTACH_MSG_ALL);
  3036. bool invertPoints = (options & ScriptBaseClass.OS_ATTACH_MSG_INVERT_POINTS) != 0;
  3037. if (msgAll && invertPoints)
  3038. {
  3039. return;
  3040. }
  3041. else if (msgAll || invertPoints)
  3042. {
  3043. attachments = target.GetAttachments();
  3044. }
  3045. else
  3046. {
  3047. foreach (int point in aps)
  3048. {
  3049. if (point > 0)
  3050. {
  3051. attachments.AddRange(target.GetAttachments((uint)point));
  3052. }
  3053. }
  3054. }
  3055. // if we have no attachments at this point, exit now
  3056. if (attachments.Count == 0)
  3057. {
  3058. return;
  3059. }
  3060. List<SceneObjectGroup> ignoreThese = new List<SceneObjectGroup>();
  3061. if (invertPoints)
  3062. {
  3063. foreach (SceneObjectGroup attachment in attachments)
  3064. {
  3065. if (aps.Contains((int)attachment.AttachmentPoint))
  3066. {
  3067. ignoreThese.Add(attachment);
  3068. }
  3069. }
  3070. }
  3071. foreach (SceneObjectGroup attachment in ignoreThese)
  3072. {
  3073. attachments.Remove(attachment);
  3074. }
  3075. ignoreThese.Clear();
  3076. // if inverting removed all attachments to check, exit now
  3077. if (attachments.Count < 1)
  3078. {
  3079. return;
  3080. }
  3081. if ((options & ScriptBaseClass.OS_ATTACH_MSG_OBJECT_CREATOR) != 0)
  3082. {
  3083. foreach (SceneObjectGroup attachment in attachments)
  3084. {
  3085. if (attachment.RootPart.CreatorID != m_host.CreatorID)
  3086. {
  3087. ignoreThese.Add(attachment);
  3088. }
  3089. }
  3090. foreach (SceneObjectGroup attachment in ignoreThese)
  3091. {
  3092. attachments.Remove(attachment);
  3093. }
  3094. ignoreThese.Clear();
  3095. // if filtering by same object creator removed all
  3096. // attachments to check, exit now
  3097. if (attachments.Count == 0)
  3098. {
  3099. return;
  3100. }
  3101. }
  3102. if ((options & ScriptBaseClass.OS_ATTACH_MSG_SCRIPT_CREATOR) != 0)
  3103. {
  3104. foreach (SceneObjectGroup attachment in attachments)
  3105. {
  3106. if (attachment.RootPart.CreatorID != m_item.CreatorID)
  3107. {
  3108. ignoreThese.Add(attachment);
  3109. }
  3110. }
  3111. foreach (SceneObjectGroup attachment in ignoreThese)
  3112. {
  3113. attachments.Remove(attachment);
  3114. }
  3115. ignoreThese.Clear();
  3116. // if filtering by object creator must match originating
  3117. // script creator removed all attachments to check,
  3118. // exit now
  3119. if (attachments.Count == 0)
  3120. {
  3121. return;
  3122. }
  3123. }
  3124. foreach (SceneObjectGroup attachment in attachments)
  3125. {
  3126. MessageObject(attachment.RootPart.UUID, message);
  3127. }
  3128. }
  3129. }
  3130. #endregion
  3131. /// <summary>
  3132. /// Checks if thing is a UUID.
  3133. /// </summary>
  3134. /// <param name="thing"></param>
  3135. /// <returns>1 if thing is a valid UUID, 0 otherwise</returns>
  3136. public LSL_Integer osIsUUID(string thing)
  3137. {
  3138. CheckThreatLevel(ThreatLevel.None, "osIsUUID");
  3139. m_host.AddScriptLPS(1);
  3140. UUID test;
  3141. return UUID.TryParse(thing, out test) ? 1 : 0;
  3142. }
  3143. /// <summary>
  3144. /// Wraps to Math.Min()
  3145. /// </summary>
  3146. /// <param name="a"></param>
  3147. /// <param name="b"></param>
  3148. /// <returns></returns>
  3149. public LSL_Float osMin(double a, double b)
  3150. {
  3151. CheckThreatLevel(ThreatLevel.None, "osMin");
  3152. m_host.AddScriptLPS(1);
  3153. return Math.Min(a, b);
  3154. }
  3155. /// <summary>
  3156. /// Wraps to Math.max()
  3157. /// </summary>
  3158. /// <param name="a"></param>
  3159. /// <param name="b"></param>
  3160. /// <returns></returns>
  3161. public LSL_Float osMax(double a, double b)
  3162. {
  3163. CheckThreatLevel(ThreatLevel.None, "osMax");
  3164. m_host.AddScriptLPS(1);
  3165. return Math.Max(a, b);
  3166. }
  3167. public LSL_Key osGetRezzingObject()
  3168. {
  3169. CheckThreatLevel(ThreatLevel.None, "osGetRezzingObject");
  3170. m_host.AddScriptLPS(1);
  3171. return new LSL_Key(m_host.ParentGroup.FromPartID.ToString());
  3172. }
  3173. /// <summary>
  3174. /// Sets the response type for an HTTP request/response
  3175. /// </summary>
  3176. /// <returns></returns>
  3177. public void osSetContentType(LSL_Key id, string type)
  3178. {
  3179. CheckThreatLevel(ThreatLevel.High, "osSetContentType");
  3180. if (m_UrlModule != null)
  3181. m_UrlModule.HttpContentType(new UUID(id),type);
  3182. }
  3183. /// Shout an error if the object owner did not grant the script the specified permissions.
  3184. /// </summary>
  3185. /// <param name="perms"></param>
  3186. /// <returns>boolean indicating whether an error was shouted.</returns>
  3187. protected bool ShoutErrorOnLackingOwnerPerms(int perms, string errorPrefix)
  3188. {
  3189. m_host.AddScriptLPS(1);
  3190. bool fail = false;
  3191. if (m_item.PermsGranter != m_host.OwnerID)
  3192. {
  3193. fail = true;
  3194. OSSLShoutError(string.Format("{0}. Permissions not granted to owner.", errorPrefix));
  3195. }
  3196. else if ((m_item.PermsMask & perms) == 0)
  3197. {
  3198. fail = true;
  3199. OSSLShoutError(string.Format("{0}. Permissions not granted.", errorPrefix));
  3200. }
  3201. return fail;
  3202. }
  3203. protected void DropAttachment(bool checkPerms)
  3204. {
  3205. if (checkPerms && ShoutErrorOnLackingOwnerPerms(ScriptBaseClass.PERMISSION_ATTACH, "Cannot drop attachment"))
  3206. {
  3207. return;
  3208. }
  3209. IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
  3210. ScenePresence sp = attachmentsModule == null ? null : m_host.ParentGroup.Scene.GetScenePresence(m_host.ParentGroup.OwnerID);
  3211. if (attachmentsModule != null && sp != null)
  3212. {
  3213. attachmentsModule.DetachSingleAttachmentToGround(sp, m_host.ParentGroup.LocalId);
  3214. }
  3215. }
  3216. protected void DropAttachmentAt(bool checkPerms, LSL_Vector pos, LSL_Rotation rot)
  3217. {
  3218. if (checkPerms && ShoutErrorOnLackingOwnerPerms(ScriptBaseClass.PERMISSION_ATTACH, "Cannot drop attachment"))
  3219. {
  3220. return;
  3221. }
  3222. IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
  3223. ScenePresence sp = attachmentsModule == null ? null : m_host.ParentGroup.Scene.GetScenePresence(m_host.ParentGroup.OwnerID);
  3224. if (attachmentsModule != null && sp != null)
  3225. {
  3226. attachmentsModule.DetachSingleAttachmentToGround(sp, m_host.ParentGroup.LocalId, pos, rot);
  3227. }
  3228. }
  3229. public void osDropAttachment()
  3230. {
  3231. CheckThreatLevel(ThreatLevel.Moderate, "osDropAttachment");
  3232. m_host.AddScriptLPS(1);
  3233. DropAttachment(true);
  3234. }
  3235. public void osForceDropAttachment()
  3236. {
  3237. CheckThreatLevel(ThreatLevel.High, "osForceDropAttachment");
  3238. m_host.AddScriptLPS(1);
  3239. DropAttachment(false);
  3240. }
  3241. public void osDropAttachmentAt(LSL_Vector pos, LSL_Rotation rot)
  3242. {
  3243. CheckThreatLevel(ThreatLevel.Moderate, "osDropAttachmentAt");
  3244. m_host.AddScriptLPS(1);
  3245. DropAttachmentAt(true, pos, rot);
  3246. }
  3247. public void osForceDropAttachmentAt(LSL_Vector pos, LSL_Rotation rot)
  3248. {
  3249. CheckThreatLevel(ThreatLevel.High, "osForceDropAttachmentAt");
  3250. m_host.AddScriptLPS(1);
  3251. DropAttachmentAt(false, pos, rot);
  3252. }
  3253. public LSL_Integer osListenRegex(int channelID, string name, string ID, string msg, int regexBitfield)
  3254. {
  3255. CheckThreatLevel(ThreatLevel.Low, "osListenRegex");
  3256. m_host.AddScriptLPS(1);
  3257. UUID keyID;
  3258. UUID.TryParse(ID, out keyID);
  3259. // if we want the name to be used as a regular expression, ensure it is valid first.
  3260. if ((regexBitfield & ScriptBaseClass.OS_LISTEN_REGEX_NAME) == ScriptBaseClass.OS_LISTEN_REGEX_NAME)
  3261. {
  3262. try
  3263. {
  3264. Regex.IsMatch("", name);
  3265. }
  3266. catch (Exception)
  3267. {
  3268. OSSLShoutError("Name regex is invalid.");
  3269. return -1;
  3270. }
  3271. }
  3272. // if we want the msg to be used as a regular expression, ensure it is valid first.
  3273. if ((regexBitfield & ScriptBaseClass.OS_LISTEN_REGEX_MESSAGE) == ScriptBaseClass.OS_LISTEN_REGEX_MESSAGE)
  3274. {
  3275. try
  3276. {
  3277. Regex.IsMatch("", msg);
  3278. }
  3279. catch (Exception)
  3280. {
  3281. OSSLShoutError("Message regex is invalid.");
  3282. return -1;
  3283. }
  3284. }
  3285. IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
  3286. return (wComm == null) ? -1 : wComm.Listen(
  3287. m_host.LocalId,
  3288. m_item.ItemID,
  3289. m_host.UUID,
  3290. channelID,
  3291. name,
  3292. keyID,
  3293. msg,
  3294. regexBitfield
  3295. );
  3296. }
  3297. public LSL_Integer osRegexIsMatch(string input, string pattern)
  3298. {
  3299. CheckThreatLevel(ThreatLevel.Low, "osRegexIsMatch");
  3300. m_host.AddScriptLPS(1);
  3301. try
  3302. {
  3303. return Regex.IsMatch(input, pattern) ? 1 : 0;
  3304. }
  3305. catch (Exception)
  3306. {
  3307. OSSLShoutError("Possible invalid regular expression detected.");
  3308. return 0;
  3309. }
  3310. }
  3311. }
  3312. }