BunchOfCaps.cs 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716
  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.Timers;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Collections.Specialized;
  32. using System.IO;
  33. using System.Net;
  34. using System.Threading;
  35. using System.Reflection;
  36. using System.Security.Cryptography;
  37. using System.Text;
  38. using System.Web;
  39. using OpenMetaverse;
  40. using OpenMetaverse.StructuredData;
  41. using Nini.Config;
  42. using log4net;
  43. using OpenSim.Framework;
  44. using OpenSim.Framework.Capabilities;
  45. using OpenSim.Region.Framework;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.Framework.Scenes;
  48. using OpenSim.Region.Framework.Scenes.Serialization;
  49. using OpenSim.Framework.Servers;
  50. using OpenSim.Framework.Servers.HttpServer;
  51. using OpenSim.Services.Interfaces;
  52. using Caps = OpenSim.Framework.Capabilities.Caps;
  53. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  54. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  55. using PermissionMask = OpenSim.Framework.PermissionMask;
  56. using Timer = System.Threading.Timer;
  57. namespace OpenSim.Region.ClientStack.Linden
  58. {
  59. public delegate void UpLoadedAsset(
  60. string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
  61. byte[] data, string inventoryType, string assetType,
  62. int cost, UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
  63. bool IsAtestUpload, ref string error, ref int nextOwnerMask, ref int groupMask, ref int everyoneMask, int[] meshesSides);
  64. public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
  65. public delegate void NewInventoryItem(UUID userID, InventoryItemBase item, uint cost);
  66. public delegate void NewAsset(AssetBase asset);
  67. public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
  68. bool isScriptRunning, byte[] data);
  69. /// <summary>
  70. /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
  71. /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
  72. /// to just pass the whole Scene into CAPS.
  73. /// </summary>
  74. public delegate IClientAPI GetClientDelegate(UUID agentID);
  75. public partial class BunchOfCaps
  76. {
  77. private static readonly ILog m_log =
  78. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  79. private Scene m_Scene;
  80. private UUID m_AgentID;
  81. private UUID m_scopeID;
  82. private Caps m_HostCapsObj;
  83. private ModelCost m_ModelCost;
  84. // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
  85. // These are callbacks which will be setup by the scene so that we can update scene data when we
  86. // receive capability calls
  87. public NewInventoryItem AddNewInventoryItem = null;
  88. public NewAsset AddNewAsset = null;
  89. public ItemUpdatedCallback ItemUpdatedCall = null;
  90. public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
  91. public GetClientDelegate GetClient = null;
  92. private bool m_persistBakedTextures = false;
  93. private IAssetService m_assetService;
  94. private bool m_dumpAssetsToFile = false;
  95. private string m_regionName;
  96. private int m_levelUpload = 0;
  97. private bool m_enableFreeTestUpload = false; // allows "TEST-" prefix hack
  98. private bool m_ForceFreeTestUpload = false; // forces all uploads to be test
  99. private bool m_enableModelUploadTextureToInventory = true; // place uploaded textures also in inventory
  100. // may not be visible till relog
  101. private bool m_RestrictFreeTestUploadPerms = false; // reduces also the permitions. Needs a creator defined!!
  102. private UUID m_testAssetsCreatorID = UUID.Zero;
  103. private float m_PrimScaleMin = 0.001f;
  104. private bool m_AllowCapHomeLocation = true;
  105. private bool m_AllowCapGroupMemberData = true;
  106. private bool m_AllowCapLandResources = true;
  107. private bool m_AllowCapAttachmentResources = true;
  108. private IUserManagement m_UserManager;
  109. private IUserAccountService m_userAccountService;
  110. private IMoneyModule m_moneyModule;
  111. private enum FileAgentInventoryState : int
  112. {
  113. idle = 0,
  114. processRequest = 1,
  115. waitUpload = 2,
  116. processUpload = 3
  117. }
  118. private FileAgentInventoryState m_FileAgentInventoryState = FileAgentInventoryState.idle;
  119. public BunchOfCaps(Scene scene, UUID agentID, Caps caps)
  120. {
  121. m_Scene = scene;
  122. m_AgentID = agentID;
  123. m_HostCapsObj = caps;
  124. // create a model upload cost provider
  125. m_ModelCost = new ModelCost(scene);
  126. m_PrimScaleMin = m_ModelCost.PrimScaleMin;
  127. IConfigSource config = m_Scene.Config;
  128. if (config != null)
  129. {
  130. IConfig sconfig = config.Configs["Startup"];
  131. if (sconfig != null)
  132. {
  133. m_levelUpload = sconfig.GetInt("LevelUpload", 0);
  134. }
  135. if (m_levelUpload == 0)
  136. {
  137. IConfig pconfig = config.Configs["Permissions"];
  138. if (pconfig != null)
  139. {
  140. m_levelUpload = pconfig.GetInt("LevelUpload", 0);
  141. }
  142. }
  143. IConfig appearanceConfig = config.Configs["Appearance"];
  144. if (appearanceConfig != null)
  145. {
  146. m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
  147. }
  148. // economy for model upload
  149. IConfig EconomyConfig = config.Configs["Economy"];
  150. if (EconomyConfig != null)
  151. {
  152. m_ModelCost.Econfig(EconomyConfig);
  153. m_enableModelUploadTextureToInventory = EconomyConfig.GetBoolean("MeshModelAllowTextureToInventory", m_enableModelUploadTextureToInventory);
  154. m_RestrictFreeTestUploadPerms = EconomyConfig.GetBoolean("m_RestrictFreeTestUploadPerms", m_RestrictFreeTestUploadPerms);
  155. m_enableFreeTestUpload = EconomyConfig.GetBoolean("AllowFreeTestUpload", m_enableFreeTestUpload);
  156. m_ForceFreeTestUpload = EconomyConfig.GetBoolean("ForceFreeTestUpload", m_ForceFreeTestUpload);
  157. string testcreator = EconomyConfig.GetString("TestAssetsCreatorID", "");
  158. if (!string.IsNullOrEmpty(testcreator))
  159. {
  160. if (UUID.TryParse(testcreator, out UUID id))
  161. m_testAssetsCreatorID = id;
  162. }
  163. }
  164. IConfig CapsConfig = config.Configs["ClientStack.LindenCaps"];
  165. if (CapsConfig != null)
  166. {
  167. string homeLocationUrl = CapsConfig.GetString("Cap_HomeLocation", "localhost");
  168. if(homeLocationUrl.Length == 0)
  169. m_AllowCapHomeLocation = false;
  170. string GroupMemberDataUrl = CapsConfig.GetString("Cap_GroupMemberData", "localhost");
  171. if(GroupMemberDataUrl.Length == 0)
  172. m_AllowCapGroupMemberData = false;
  173. string LandResourcesUrl = CapsConfig.GetString("Cap_LandResources", "localhost");
  174. if (LandResourcesUrl.Length == 0)
  175. m_AllowCapLandResources = false;
  176. string AttachmentResourcesUrl = CapsConfig.GetString("Cap_AttachmentResources", "localhost");
  177. if (AttachmentResourcesUrl.Length == 0)
  178. m_AllowCapAttachmentResources = false;
  179. }
  180. }
  181. m_assetService = m_Scene.AssetService;
  182. m_regionName = m_Scene.RegionInfo.RegionName;
  183. m_UserManager = m_Scene.RequestModuleInterface<IUserManagement>();
  184. m_userAccountService = m_Scene.RequestModuleInterface<IUserAccountService>();
  185. m_moneyModule = m_Scene.RequestModuleInterface<IMoneyModule>();
  186. if (m_UserManager == null)
  187. m_log.Error("[CAPS]: GetDisplayNames disabled because user management component not found");
  188. UserAccount account = m_userAccountService.GetUserAccount(m_Scene.RegionInfo.ScopeID, m_AgentID);
  189. if (account == null) // Hypergrid?
  190. m_scopeID = m_Scene.RegionInfo.ScopeID;
  191. else
  192. m_scopeID = account.ScopeID;
  193. AddNewInventoryItem = m_Scene.AddUploadedInventoryItem;
  194. ItemUpdatedCall = m_Scene.CapsUpdateItemAsset;
  195. TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset;
  196. GetClient = m_Scene.SceneGraph.GetControllingClient;
  197. RegisterHandlers();
  198. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  199. }
  200. public string GetNewCapPath()
  201. {
  202. return "/" + UUID.Random();
  203. }
  204. /// <summary>
  205. /// Register a bunch of CAPS http service handlers
  206. /// </summary>
  207. public void RegisterHandlers()
  208. {
  209. // this path is also defined elsewhere so keeping it
  210. string seedcapsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath + "0000";
  211. m_HostCapsObj.RegisterSimpleHandler("SEED", new SimpleStreamHandler(seedcapsBase, SeedCapRequest));
  212. // m_log.DebugFormat(
  213. // "[CAPS]: Registered seed capability {0} for {1}", seedcapsBase, m_HostCapsObj.AgentID);
  214. RegisterRegionServiceHandlers();
  215. RegisterInventoryServiceHandlers();
  216. RegisterOtherHandlers();
  217. }
  218. public void RegisterRegionServiceHandlers()
  219. {
  220. try
  221. {
  222. m_HostCapsObj.RegisterSimpleHandler("GetObjectPhysicsData",
  223. new SimpleOSDMapHandler("POST", GetNewCapPath(), GetObjectPhysicsData));
  224. m_HostCapsObj.RegisterSimpleHandler("GetObjectCost",
  225. new SimpleOSDMapHandler("POST", GetNewCapPath(), GetObjectCost));
  226. m_HostCapsObj.RegisterSimpleHandler("ResourceCostSelected",
  227. new SimpleOSDMapHandler("POST", GetNewCapPath(), ResourceCostSelected));
  228. if(m_AllowCapHomeLocation)
  229. {
  230. m_HostCapsObj.RegisterSimpleHandler("HomeLocation",
  231. new SimpleStreamHandler(GetNewCapPath(), HomeLocation));
  232. }
  233. if (m_AllowCapGroupMemberData)
  234. {
  235. m_HostCapsObj.RegisterSimpleHandler("GroupMemberData",
  236. new SimpleStreamHandler(GetNewCapPath(), GroupMemberData));
  237. }
  238. if (m_AllowCapLandResources)
  239. {
  240. m_HostCapsObj.RegisterSimpleHandler("LandResources",
  241. new SimpleOSDMapHandler("POST", GetNewCapPath(), LandResources));
  242. }
  243. if (m_AllowCapAttachmentResources)
  244. {
  245. m_HostCapsObj.RegisterSimpleHandler("AttachmentResources",
  246. new SimpleStreamHandler(GetNewCapPath(), AttachmentResources));
  247. }
  248. }
  249. catch (Exception e)
  250. {
  251. m_log.Error("[CAPS]: " + e.ToString());
  252. }
  253. }
  254. public void RegisterInventoryServiceHandlers()
  255. {
  256. try
  257. {
  258. m_HostCapsObj.RegisterHandler("NewFileAgentInventory",
  259. new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>(
  260. "POST", GetNewCapPath(), NewAgentInventoryRequest, "NewFileAgentInventory", null));
  261. SimpleOSDMapHandler oreq;
  262. if (ItemUpdatedCall != null)
  263. {
  264. // first sets the http handler, others only register the cap, using it
  265. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateNotecardItemAsset);
  266. m_HostCapsObj.RegisterSimpleHandler("UpdateNotecardAgentInventory", oreq, true);
  267. m_HostCapsObj.RegisterSimpleHandler("UpdateNotecardTaskInventory", oreq, false); // a object inv
  268. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateAnimSetItemAsset);
  269. m_HostCapsObj.RegisterSimpleHandler("UpdateAnimSetAgentInventory", oreq, true);
  270. //m_HostCapsObj.RegisterSimpleHandler("UpdateAnimSetTaskInventory", oreq, false);
  271. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateScriptItemAsset);
  272. m_HostCapsObj.RegisterSimpleHandler("UpdateScriptAgent", oreq, true);
  273. m_HostCapsObj.RegisterSimpleHandler("UpdateScriptAgentInventory", oreq, false); //legacy
  274. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateSettingsItemAsset);
  275. m_HostCapsObj.RegisterSimpleHandler("UpdateSettingsAgentInventory", oreq, true);
  276. m_HostCapsObj.RegisterSimpleHandler("UpdateSettingsTaskInventory", oreq, false); // a object inv
  277. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateMaterialItemAsset);
  278. m_HostCapsObj.RegisterSimpleHandler("UpdateMaterialAgentInventory", oreq, true);
  279. m_HostCapsObj.RegisterSimpleHandler("UpdateMaterialTaskInventory", oreq, false); // a object inv
  280. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateGestureItemAsset);
  281. m_HostCapsObj.RegisterSimpleHandler("UpdateGestureAgentInventory", oreq, true);
  282. m_HostCapsObj.RegisterSimpleHandler("UpdateGestureTaskInventory", oreq, false);
  283. }
  284. if (TaskScriptUpdatedCall != null)
  285. {
  286. oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateScriptTaskInventory);
  287. m_HostCapsObj.RegisterSimpleHandler("UpdateScriptTask", oreq, true);
  288. m_HostCapsObj.RegisterSimpleHandler("UpdateScriptTaskInventory", oreq, true); //legacy
  289. }
  290. m_HostCapsObj.RegisterSimpleHandler("UpdateAgentInformation",
  291. new SimpleStreamHandler(GetNewCapPath(), UpdateAgentInformation));
  292. m_HostCapsObj.RegisterSimpleHandler("CopyInventoryFromNotecard",
  293. new SimpleOSDMapHandler("POST", GetNewCapPath(), CopyInventoryFromNotecard));
  294. m_HostCapsObj.RegisterSimpleHandler("CreateInventoryCategory",
  295. new SimpleStreamHandler(GetNewCapPath(), CreateInventoryCategory));
  296. }
  297. catch (Exception e)
  298. {
  299. m_log.Error("[CAPS]: " + e.ToString());
  300. }
  301. }
  302. public void RegisterOtherHandlers()
  303. {
  304. try
  305. {
  306. if (m_UserManager != null)
  307. {
  308. m_HostCapsObj.RegisterSimpleHandler("GetDisplayNames",
  309. new SimpleStreamHandler(GetNewCapPath(), GetDisplayNames));
  310. }
  311. }
  312. catch (Exception e)
  313. {
  314. m_log.Error("[CAPS]: " + e.ToString());
  315. }
  316. }
  317. /// <summary>
  318. /// Construct a client response detailing all the capabilities this server can provide.
  319. /// </summary>
  320. /// <param name="request"></param>
  321. /// <param name="path"></param>
  322. /// <param name="param"></param>
  323. /// <param name="httpRequest">HTTP request header object</param>
  324. /// <param name="httpResponse">HTTP response header object</param>
  325. /// <returns></returns>
  326. public void SeedCapRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  327. {
  328. UUID agentID = m_HostCapsObj.AgentID;
  329. m_log.DebugFormat(
  330. "[CAPS]: Received SEED caps request in {0} for agent {1}", m_regionName, agentID);
  331. if(httpRequest.HttpMethod != "POST" || httpRequest.ContentType != "application/llsd+xml")
  332. {
  333. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  334. return;
  335. }
  336. if (!m_HostCapsObj.WaitForActivation())
  337. {
  338. httpResponse.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  339. httpResponse.AddHeader("Retry-After", "30");
  340. return;
  341. }
  342. if (!m_Scene.CheckClient(agentID, httpRequest.RemoteIPEndPoint))
  343. {
  344. m_log.WarnFormat(
  345. "[CAPS]: Unauthorized CAPS client {0} from {1}",
  346. agentID, httpRequest.RemoteIPEndPoint);
  347. httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
  348. return;
  349. }
  350. OSDArray capsRequested;
  351. try
  352. {
  353. capsRequested = (OSDArray)OSDParser.DeserializeLLSDXml(httpRequest.InputStream);
  354. }
  355. catch
  356. {
  357. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  358. return;
  359. }
  360. List<string> validCaps = new List<string>();
  361. foreach (OSD c in capsRequested)
  362. {
  363. string cstr = c.AsString();
  364. if (cstr.Equals("ObjectAnimation"))
  365. m_HostCapsObj.Flags |= Caps.CapsFlags.ObjectAnim;
  366. else if (cstr.Equals("EnvironmentSettings"))
  367. m_HostCapsObj.Flags |= Caps.CapsFlags.WLEnv;
  368. else if (cstr.Equals("ExtEnvironment"))
  369. m_HostCapsObj.Flags |= Caps.CapsFlags.AdvEnv;
  370. validCaps.Add(cstr);
  371. }
  372. string result = LLSDHelpers.SerialiseLLSDReply(m_HostCapsObj.GetCapsDetails(true, validCaps));
  373. httpResponse.RawBuffer = Util.UTF8NBGetbytes(result);
  374. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  375. //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
  376. m_HostCapsObj.Flags |= Caps.CapsFlags.SentSeeds;
  377. }
  378. /// <summary>
  379. ///
  380. /// </summary>
  381. /// <param name="llsdRequest"></param>
  382. /// <returns></returns>
  383. public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
  384. {
  385. //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
  386. //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
  387. // start by getting the client
  388. IClientAPI client = null;
  389. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  390. // check current state so we only have one service at a time
  391. lock (m_ModelCost)
  392. {
  393. switch (m_FileAgentInventoryState)
  394. {
  395. case FileAgentInventoryState.processRequest:
  396. case FileAgentInventoryState.processUpload:
  397. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  398. resperror.message = "Uploader busy processing previous request";
  399. resperror.identifier = UUID.Zero;
  400. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  401. errorResponse.uploader = "";
  402. errorResponse.state = "error";
  403. errorResponse.error = resperror;
  404. return errorResponse;
  405. case FileAgentInventoryState.waitUpload:
  406. // todo stop current uploader server
  407. break;
  408. case FileAgentInventoryState.idle:
  409. default:
  410. break;
  411. }
  412. m_FileAgentInventoryState = FileAgentInventoryState.processRequest;
  413. }
  414. int cost = 0;
  415. int nreqtextures = 0;
  416. int nreqmeshs= 0;
  417. int nreqinstances = 0;
  418. bool IsAtestUpload = false;
  419. int[] meshesSides = null;
  420. string assetName = llsdRequest.name;
  421. LLSDAssetUploadResponseData meshcostdata = new LLSDAssetUploadResponseData();
  422. if (llsdRequest.asset_type == "texture" ||
  423. llsdRequest.asset_type == "animation" ||
  424. llsdRequest.asset_type == "animatn" || // this is the asset name actually used by viewers
  425. llsdRequest.asset_type == "mesh" ||
  426. llsdRequest.asset_type == "sound")
  427. {
  428. ScenePresence avatar = null;
  429. m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
  430. // check user level
  431. if (avatar != null)
  432. {
  433. if (avatar.GodController.UserLevel < m_levelUpload)
  434. {
  435. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  436. resperror.message = "Insufficient permissions to upload";
  437. resperror.identifier = UUID.Zero;
  438. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  439. errorResponse.uploader = "";
  440. errorResponse.state = "error";
  441. errorResponse.error = resperror;
  442. lock (m_ModelCost)
  443. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  444. return errorResponse;
  445. }
  446. }
  447. // check test upload and funds
  448. if (client != null)
  449. {
  450. IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
  451. int baseCost = 0;
  452. if (mm != null)
  453. baseCost = mm.UploadCharge;
  454. string warning = String.Empty;
  455. if (llsdRequest.asset_type == "mesh")
  456. {
  457. string error;
  458. int modelcost;
  459. if (!m_ModelCost.MeshModelCost(llsdRequest.asset_resources, baseCost, out modelcost,
  460. meshcostdata, out error, ref warning, out meshesSides))
  461. {
  462. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  463. resperror.message = error;
  464. resperror.identifier = UUID.Zero;
  465. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  466. errorResponse.uploader = "";
  467. errorResponse.state = "error";
  468. errorResponse.error = resperror;
  469. lock (m_ModelCost)
  470. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  471. return errorResponse;
  472. }
  473. cost = modelcost;
  474. }
  475. else
  476. {
  477. cost = baseCost;
  478. }
  479. if (cost > 0 && mm != null)
  480. {
  481. // check for test upload
  482. if (m_ForceFreeTestUpload) // all are test
  483. {
  484. if (!(assetName.Length > 5 && assetName.StartsWith("TEST-"))) // has normal name lets change it
  485. assetName = "TEST-" + assetName;
  486. IsAtestUpload = true;
  487. }
  488. else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
  489. {
  490. IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
  491. }
  492. if(IsAtestUpload) // let user know, still showing cost estimation
  493. warning += "Upload will have no cost, for testing purposes only. Other uses are prohibited. Items will be local to region only, Inventory entry will be lost on logout";
  494. // check funds
  495. else
  496. {
  497. if (!mm.UploadCovered(client.AgentId, (int)cost))
  498. {
  499. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  500. resperror.message = "Insuficient funds";
  501. resperror.identifier = UUID.Zero;
  502. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  503. errorResponse.uploader = "";
  504. errorResponse.state = "error";
  505. errorResponse.error = resperror;
  506. lock (m_ModelCost)
  507. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  508. return errorResponse;
  509. }
  510. }
  511. }
  512. else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
  513. {
  514. IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
  515. if(IsAtestUpload)
  516. warning += "Upload for testing purposes only. Items will be local to region only, Inventory entry will be lost on logout";
  517. }
  518. if (client != null && warning != String.Empty)
  519. client.SendAgentAlertMessage(warning, true);
  520. }
  521. }
  522. string assetDes = llsdRequest.description;
  523. UUID newAsset = UUID.Random();
  524. UUID newInvItem = UUID.Random();
  525. UUID parentFolder = llsdRequest.folder_id;
  526. string uploaderPath = GetNewCapPath();
  527. UUID texturesFolder = UUID.Zero;
  528. if(!IsAtestUpload && m_enableModelUploadTextureToInventory)
  529. texturesFolder = llsdRequest.texture_folder_id;
  530. AssetUploader uploader =
  531. new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
  532. llsdRequest.asset_type, uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile, cost,
  533. texturesFolder, nreqtextures, nreqmeshs, nreqinstances, IsAtestUpload,
  534. llsdRequest.next_owner_mask, llsdRequest.group_mask, llsdRequest.everyone_mask, meshesSides);
  535. m_HostCapsObj.HttpListener.AddStreamHandler(
  536. new BinaryStreamHandler(
  537. "POST",
  538. uploaderPath,
  539. uploader.uploaderCaps,
  540. "NewAgentInventoryRequest",
  541. m_HostCapsObj.AgentID.ToString()));
  542. string protocol = "http://";
  543. if (m_HostCapsObj.SSLCaps)
  544. protocol = "https://";
  545. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + uploaderPath;
  546. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  547. uploadResponse.uploader = uploaderURL;
  548. uploadResponse.state = "upload";
  549. uploadResponse.upload_price = (int)cost;
  550. if (llsdRequest.asset_type == "mesh")
  551. {
  552. uploadResponse.data = meshcostdata;
  553. }
  554. uploader.OnUpLoad += UploadCompleteHandler;
  555. lock (m_ModelCost)
  556. m_FileAgentInventoryState = FileAgentInventoryState.waitUpload;
  557. return uploadResponse;
  558. }
  559. /// <summary>
  560. /// Convert raw uploaded data into the appropriate asset and item.
  561. /// </summary>
  562. /// <param name="assetID"></param>
  563. /// <param name="inventoryItem"></param>
  564. /// <param name="data"></param>
  565. public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
  566. UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
  567. string assetType, int cost,
  568. UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
  569. bool IsAtestUpload, ref string error,
  570. ref int nextOwnerMask, ref int groupMask, ref int everyoneMask, int[] meshesSides)
  571. {
  572. lock (m_ModelCost)
  573. m_FileAgentInventoryState = FileAgentInventoryState.processUpload;
  574. m_log.DebugFormat(
  575. "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
  576. assetID, inventoryItem, inventoryType, assetType);
  577. sbyte assType = 0;
  578. sbyte inType = 0;
  579. IClientAPI client = null;
  580. UUID owner_id = m_HostCapsObj.AgentID;
  581. UUID creatorID;
  582. bool istest = IsAtestUpload && m_enableFreeTestUpload;
  583. bool restrictPerms = m_RestrictFreeTestUploadPerms && istest;
  584. if (istest && m_testAssetsCreatorID != UUID.Zero)
  585. creatorID = m_testAssetsCreatorID;
  586. else
  587. creatorID = owner_id;
  588. string creatorIDstr = creatorID.ToString();
  589. IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
  590. if (mm != null)
  591. {
  592. // make sure client still has enougth credit
  593. if (!mm.UploadCovered(m_HostCapsObj.AgentID, (int)cost))
  594. {
  595. error = "Insufficient funds.";
  596. return;
  597. }
  598. }
  599. // strings to types
  600. if (inventoryType == "sound")
  601. {
  602. inType = (sbyte)InventoryType.Sound;
  603. assType = (sbyte)AssetType.Sound;
  604. }
  605. else if (inventoryType == "snapshot")
  606. {
  607. inType = (sbyte)InventoryType.Snapshot;
  608. }
  609. else if (inventoryType == "animation")
  610. {
  611. inType = (sbyte)InventoryType.Animation;
  612. assType = (sbyte)AssetType.Animation;
  613. }
  614. else if (inventoryType == "animset")
  615. {
  616. inType = (sbyte)CustomInventoryType.AnimationSet;
  617. assType = (sbyte)CustomAssetType.AnimationSet;
  618. m_log.Debug("got animset upload request");
  619. }
  620. else if (inventoryType == "wearable")
  621. {
  622. inType = (sbyte)InventoryType.Wearable;
  623. switch (assetType)
  624. {
  625. case "bodypart":
  626. assType = (sbyte)AssetType.Bodypart;
  627. break;
  628. case "clothing":
  629. assType = (sbyte)AssetType.Clothing;
  630. break;
  631. }
  632. }
  633. else if (inventoryType == "object")
  634. {
  635. if (assetType == "mesh") // this code for now is for mesh models uploads only
  636. {
  637. inType = (sbyte)InventoryType.Object;
  638. assType = (sbyte)AssetType.Object;
  639. List<Vector3> positions = new List<Vector3>();
  640. List<Quaternion> rotations = new List<Quaternion>();
  641. OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  642. // compare and get updated information
  643. /* does nothing still we do need something to avoid special viewer to upload something diferent from the cost estimation
  644. bool mismatchError = true;
  645. while (mismatchError)
  646. {
  647. mismatchError = false;
  648. }
  649. if (mismatchError)
  650. {
  651. error = "Upload and fee estimation information don't match";
  652. lock (m_ModelCost)
  653. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  654. return;
  655. }
  656. */
  657. OSDArray instance_list = (OSDArray)request["instance_list"];
  658. OSDArray mesh_list = (OSDArray)request["mesh_list"];
  659. OSDArray texture_list = (OSDArray)request["texture_list"];
  660. SceneObjectGroup grp = null;
  661. // create and store texture assets
  662. bool doTextInv = (!istest && m_enableModelUploadTextureToInventory &&
  663. texturesFolder != UUID.Zero);
  664. List<UUID> textures = new List<UUID>();
  665. // if (doTextInv)
  666. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  667. if(client == null) // don't put textures in inventory if there is no client
  668. doTextInv = false;
  669. for (int i = 0; i < texture_list.Count; i++)
  670. {
  671. AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, creatorIDstr);
  672. textureAsset.Data = texture_list[i].AsBinary();
  673. if (istest)
  674. textureAsset.Local = true;
  675. m_assetService.Store(textureAsset);
  676. textures.Add(textureAsset.FullID);
  677. if (doTextInv)
  678. {
  679. string name = assetName;
  680. if (name.Length > 25)
  681. name = name.Substring(0, 24);
  682. name += "_Texture#" + i.ToString();
  683. InventoryItemBase texitem = new InventoryItemBase();
  684. texitem.Owner = m_HostCapsObj.AgentID;
  685. texitem.CreatorId = creatorIDstr;
  686. texitem.CreatorData = String.Empty;
  687. texitem.ID = UUID.Random();
  688. texitem.AssetID = textureAsset.FullID;
  689. texitem.Description = "mesh model texture";
  690. texitem.Name = name;
  691. texitem.AssetType = (int)AssetType.Texture;
  692. texitem.InvType = (int)InventoryType.Texture;
  693. texitem.Folder = texturesFolder;
  694. texitem.CurrentPermissions
  695. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
  696. texitem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  697. texitem.EveryOnePermissions = 0;
  698. texitem.NextPermissions = (uint)PermissionMask.All;
  699. texitem.CreationDate = Util.UnixTimeSinceEpoch();
  700. m_Scene.AddInventoryItem(client, texitem);
  701. texitem = null;
  702. }
  703. }
  704. // create and store meshs assets
  705. List<UUID> meshAssets = new List<UUID>();
  706. List<bool> meshAvatarSkeletons = new List<bool>();
  707. List<bool> meshAvatarColliders = new List<bool>();
  708. bool curAvSkeleton;
  709. bool curAvCollider;
  710. for (int i = 0; i < mesh_list.Count; i++)
  711. {
  712. curAvSkeleton = false;
  713. curAvCollider = false;
  714. // we do need to parse the mesh now
  715. OSD osd = OSDParser.DeserializeLLSDBinary(mesh_list[i]);
  716. if (osd is OSDMap)
  717. {
  718. OSDMap mosd = (OSDMap)osd;
  719. if (mosd.ContainsKey("skeleton"))
  720. {
  721. OSDMap skeleton = (OSDMap)mosd["skeleton"];
  722. int sksize = skeleton["size"].AsInteger();
  723. if (sksize > 0)
  724. curAvSkeleton = true;
  725. }
  726. }
  727. AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, creatorIDstr);
  728. meshAsset.Data = mesh_list[i].AsBinary();
  729. if (istest)
  730. meshAsset.Local = true;
  731. m_assetService.Store(meshAsset);
  732. meshAssets.Add(meshAsset.FullID);
  733. meshAvatarSkeletons.Add(curAvSkeleton);
  734. meshAvatarColliders.Add(curAvCollider);
  735. // test code
  736. if (curAvSkeleton && client != null)
  737. {
  738. string name = assetName;
  739. if (name.Length > 25)
  740. name = name.Substring(0, 24);
  741. name += "_Mesh#" + i.ToString();
  742. InventoryItemBase meshitem = new InventoryItemBase();
  743. meshitem.Owner = m_HostCapsObj.AgentID;
  744. meshitem.CreatorId = creatorIDstr;
  745. meshitem.CreatorData = String.Empty;
  746. meshitem.ID = UUID.Random();
  747. meshitem.AssetID = meshAsset.FullID;
  748. meshitem.Description = "mesh ";
  749. meshitem.Name = name;
  750. meshitem.AssetType = (int)AssetType.Mesh;
  751. meshitem.InvType = (int)InventoryType.Mesh;
  752. // meshitem.Folder = UUID.Zero; // send to default
  753. meshitem.Folder = parentFolder; // dont let it go to folder Meshes that viewers dont show
  754. // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
  755. // (owner) permissions. This becomes a problem if next permissions are changed.
  756. meshitem.CurrentPermissions
  757. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer);
  758. meshitem.BasePermissions = (uint)PermissionMask.All;
  759. meshitem.EveryOnePermissions = 0;
  760. meshitem.NextPermissions = (uint)PermissionMask.All;
  761. meshitem.CreationDate = Util.UnixTimeSinceEpoch();
  762. m_Scene.AddInventoryItem(client, meshitem);
  763. meshitem = null;
  764. }
  765. }
  766. int skipedMeshs = 0;
  767. // build prims from instances
  768. for (int i = 0; i < instance_list.Count; i++)
  769. {
  770. OSDMap inner_instance_list = (OSDMap)instance_list[i];
  771. // skip prims that are 2 small
  772. Vector3 scale = inner_instance_list["scale"].AsVector3();
  773. if (scale.X < m_PrimScaleMin || scale.Y < m_PrimScaleMin || scale.Z < m_PrimScaleMin)
  774. {
  775. skipedMeshs++;
  776. continue;
  777. }
  778. OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
  779. PrimitiveBaseShape pbs = null;
  780. if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
  781. {
  782. int meshindx = inner_instance_list["mesh"].AsInteger();
  783. if (meshAssets.Count > meshindx)
  784. {
  785. if(meshesSides != null && meshesSides.Length > meshindx)
  786. pbs = PrimitiveBaseShape.CreateMesh(meshesSides[i], meshAssets[meshindx]);
  787. else
  788. pbs = PrimitiveBaseShape.CreateMesh(face_list.Count, meshAssets[meshindx]);
  789. }
  790. }
  791. if(pbs == null) // fallback
  792. pbs = PrimitiveBaseShape.CreateBox();
  793. Primitive.TextureEntry textureEntry
  794. = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
  795. for (uint face = 0; face < face_list.Count; face++)
  796. {
  797. OSDMap faceMap = (OSDMap)face_list[(int)face];
  798. Primitive.TextureEntryFace f = textureEntry.CreateFace(face); //clone the default
  799. if (faceMap.ContainsKey("fullbright"))
  800. f.Fullbright = faceMap["fullbright"].AsBoolean();
  801. if (faceMap.ContainsKey("diffuse_color"))
  802. f.RGBA = faceMap["diffuse_color"].AsColor4();
  803. int textureNum = faceMap["image"].AsInteger();
  804. float imagerot = faceMap["imagerot"].AsInteger();
  805. float offsets = (float)faceMap["offsets"].AsReal();
  806. float offsett = (float)faceMap["offsett"].AsReal();
  807. float scales = (float)faceMap["scales"].AsReal();
  808. float scalet = (float)faceMap["scalet"].AsReal();
  809. if (imagerot != 0)
  810. f.Rotation = imagerot;
  811. if (offsets != 0)
  812. f.OffsetU = offsets;
  813. if (offsett != 0)
  814. f.OffsetV = offsett;
  815. if (scales != 0)
  816. f.RepeatU = scales;
  817. if (scalet != 0)
  818. f.RepeatV = scalet;
  819. if (textures.Count > textureNum)
  820. f.TextureID = textures[textureNum];
  821. textureEntry.FaceTextures[face] = f;
  822. }
  823. if(face_list.Count > 0)
  824. {
  825. int last = face_list.Count - 1;
  826. // we do need a better te compacting code
  827. textureEntry.DefaultTexture = textureEntry.FaceTextures[last];
  828. textureEntry.FaceTextures[last] = null;
  829. pbs.TextureEntry = textureEntry.GetBytes(last);
  830. }
  831. Vector3 position = inner_instance_list["position"].AsVector3();
  832. Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
  833. byte physicsShapeType = (byte)PhysShapeType.convex; // default is simple convex
  834. if (inner_instance_list.ContainsKey("physics_shape_type"))
  835. physicsShapeType = (byte)inner_instance_list["physics_shape_type"].AsInteger();
  836. byte material = (byte)Material.Wood;
  837. if (inner_instance_list.ContainsKey("material"))
  838. material = (byte)inner_instance_list["material"].AsInteger();
  839. SceneObjectPart prim
  840. = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);
  841. prim.Scale = scale;
  842. rotations.Add(rotation);
  843. positions.Add(position);
  844. prim.UUID = UUID.Random();
  845. prim.CreatorID = creatorID;
  846. prim.OwnerID = owner_id;
  847. prim.GroupID = UUID.Zero;
  848. prim.LastOwnerID = creatorID;
  849. prim.RezzerID = creatorID;
  850. prim.CreationDate = Util.UnixTimeSinceEpoch();
  851. if (grp == null)
  852. prim.Name = assetName;
  853. else
  854. prim.Name = assetName + "#" + i.ToString();
  855. prim.EveryoneMask = 0;
  856. prim.GroupMask = 0;
  857. if (restrictPerms)
  858. {
  859. prim.BaseMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
  860. prim.OwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
  861. prim.NextOwnerMask = 0;
  862. }
  863. else
  864. {
  865. prim.BaseMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  866. prim.OwnerMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  867. prim.GroupMask = prim.BaseMask & (uint)groupMask;
  868. prim.EveryoneMask = prim.BaseMask & (uint)everyoneMask;
  869. prim.NextOwnerMask = prim.BaseMask & (uint)nextOwnerMask;
  870. // If the viewer gives us bogus permissions, revert to the SL
  871. // default of transfer only.
  872. if ((prim.NextOwnerMask & (uint)PermissionMask.All) == 0)
  873. prim.NextOwnerMask = (uint)PermissionMask.Transfer;
  874. }
  875. if(istest)
  876. prim.Description = "For testing only. Other uses are prohibited";
  877. else
  878. prim.Description = "";
  879. prim.Material = material;
  880. prim.PhysicsShapeType = physicsShapeType;
  881. // prim.BaseMask = (uint)base_mask;
  882. // prim.EveryoneMask = (uint)everyone_mask;
  883. // prim.GroupMask = (uint)group_mask;
  884. // prim.NextOwnerMask = (uint)next_owner_mask;
  885. // prim.OwnerMask = (uint)owner_mask;
  886. if (grp == null)
  887. {
  888. grp = new SceneObjectGroup(prim);
  889. grp.LastOwnerID = creatorID;
  890. grp.RezzerID = creatorID;
  891. }
  892. else
  893. grp.AddPart(prim);
  894. }
  895. Vector3 rootPos = positions[0];
  896. if (grp.Parts.Length > 1)
  897. {
  898. // Fix first link number
  899. grp.RootPart.LinkNum++;
  900. Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
  901. Quaternion tmprot;
  902. Vector3 offset;
  903. // fix children rotations and positions
  904. for (int i = 1; i < rotations.Count; i++)
  905. {
  906. tmprot = rotations[i];
  907. tmprot = rootRotConj * tmprot;
  908. grp.Parts[i].RotationOffset = tmprot;
  909. offset = positions[i] - rootPos;
  910. offset *= rootRotConj;
  911. grp.Parts[i].OffsetPosition = offset;
  912. }
  913. grp.AbsolutePosition = rootPos;
  914. grp.UpdateGroupRotationR(rotations[0]);
  915. }
  916. else
  917. {
  918. grp.AbsolutePosition = rootPos;
  919. grp.UpdateGroupRotationR(rotations[0]);
  920. }
  921. data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
  922. }
  923. else // not a mesh model
  924. {
  925. m_log.ErrorFormat("[CAPS Asset Upload] got unsuported assetType for object upload");
  926. return;
  927. }
  928. }
  929. AssetBase asset;
  930. asset = new AssetBase(assetID, assetName, assType, creatorIDstr);
  931. asset.Data = data;
  932. if (istest)
  933. asset.Local = true;
  934. if (AddNewAsset != null)
  935. AddNewAsset(asset);
  936. else if (m_assetService != null)
  937. m_assetService.Store(asset);
  938. InventoryItemBase item = new InventoryItemBase();
  939. item.Owner = m_HostCapsObj.AgentID;
  940. item.CreatorId = creatorIDstr;
  941. item.CreatorData = String.Empty;
  942. item.ID = inventoryItem;
  943. item.AssetID = asset.FullID;
  944. if (istest)
  945. {
  946. item.Description = "For testing only. Other uses are prohibited";
  947. item.Flags = (uint) (InventoryItemFlags.SharedSingleReference);
  948. }
  949. else
  950. item.Description = assetDescription;
  951. item.Name = assetName;
  952. item.AssetType = assType;
  953. item.InvType = inType;
  954. item.Folder = parentFolder;
  955. // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
  956. // (owner) permissions. This becomes a problem if next permissions are changed.
  957. if (inType == (sbyte)CustomInventoryType.AnimationSet)
  958. {
  959. AnimationSet.setCreateItemPermitions(item);
  960. }
  961. else if (restrictPerms)
  962. {
  963. item.BasePermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
  964. item.CurrentPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
  965. item.GroupPermissions = 0;
  966. item.EveryOnePermissions = 0;
  967. item.NextPermissions = 0;
  968. }
  969. else
  970. {
  971. item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  972. item.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  973. item.GroupPermissions = item.BasePermissions & (uint)groupMask;
  974. item.EveryOnePermissions = item.BasePermissions & (uint)everyoneMask;
  975. item.NextPermissions = item.BasePermissions & (uint)nextOwnerMask;
  976. if ((item.NextPermissions & (uint)PermissionMask.All) == 0)
  977. item.NextPermissions = (uint)PermissionMask.Transfer;
  978. }
  979. item.CreationDate = Util.UnixTimeSinceEpoch();
  980. everyoneMask = (int)item.EveryOnePermissions;
  981. groupMask = (int)item.GroupPermissions;
  982. nextOwnerMask = (int)item.NextPermissions;
  983. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  984. if (AddNewInventoryItem != null)
  985. {
  986. if (istest)
  987. {
  988. m_Scene.AddInventoryItem(client, item);
  989. /*
  990. AddNewInventoryItem(m_HostCapsObj.AgentID, item, 0);
  991. if (client != null)
  992. client.SendAgentAlertMessage("Upload will have no cost, for personal test purposes only. Other uses are forbiden. Items may not work on a another region" , true);
  993. */
  994. }
  995. else
  996. {
  997. AddNewInventoryItem(m_HostCapsObj.AgentID, item, (uint)cost);
  998. // if (client != null)
  999. // {
  1000. // // let users see anything.. i don't so far
  1001. // string str;
  1002. // if (cost > 0)
  1003. // // dont remember where is money unit name to put here
  1004. // str = "Upload complete. charged " + cost.ToString() + "$";
  1005. // else
  1006. // str = "Upload complete";
  1007. // client.SendAgentAlertMessage(str, true);
  1008. // }
  1009. }
  1010. }
  1011. lock (m_ModelCost)
  1012. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  1013. }
  1014. public void CreateInventoryCategory(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1015. {
  1016. if(httpRequest.HttpMethod != "POST")
  1017. {
  1018. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1019. return;
  1020. }
  1021. if (m_Scene.InventoryService == null)
  1022. {
  1023. httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
  1024. return;
  1025. }
  1026. ScenePresence sp = m_Scene.GetScenePresence(m_AgentID);
  1027. if (sp == null || sp.IsDeleted)
  1028. {
  1029. httpResponse.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  1030. httpResponse.AddHeader("Retry-After", "60");
  1031. return;
  1032. }
  1033. OSDMap req;
  1034. OSD tmp;
  1035. try
  1036. {
  1037. req = (OSDMap)OSDParser.DeserializeLLSDXml(httpRequest.InputStream);
  1038. }
  1039. catch
  1040. {
  1041. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1042. return;
  1043. }
  1044. try
  1045. {
  1046. while (true) // kinda goto
  1047. {
  1048. if (!req.TryGetValue("folder_id", out tmp) || !(tmp is OSDUUID))
  1049. break;
  1050. UUID folderID = tmp.AsUUID();
  1051. if(folderID == UUID.Zero)
  1052. break;
  1053. if (!req.TryGetValue("parent_id", out tmp) || !(tmp is OSDUUID))
  1054. break;
  1055. UUID parentID = tmp.AsUUID();
  1056. if (!req.TryGetValue("name", out tmp) || !(tmp is OSDString))
  1057. break;
  1058. string folderName = tmp.AsString();
  1059. if(string.IsNullOrEmpty(folderName))
  1060. break;
  1061. if(folderName.Length > 63)
  1062. folderName = folderName.Substring(0, 63);
  1063. if (!req.TryGetValue("type", out tmp) || !(tmp is OSDInteger))
  1064. break;
  1065. int folderType = tmp.AsInteger();
  1066. InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, m_AgentID, (short)folderType, parentID, 1);
  1067. if (!m_Scene.InventoryService.AddFolder(folder))
  1068. break;
  1069. // costly double check plus possible service changes
  1070. folder = m_Scene.InventoryService.GetFolder(m_AgentID, folderID);
  1071. if (folder == null)
  1072. break;
  1073. osUTF8 sb = LLSDxmlEncode2.Start();
  1074. LLSDxmlEncode2.AddMap(sb);
  1075. LLSDxmlEncode2.AddElem("folder_id", folder.ID, sb);
  1076. LLSDxmlEncode2.AddElem("name", folder.Name, sb);
  1077. LLSDxmlEncode2.AddElem("parent_id", folder.ParentID, sb);
  1078. LLSDxmlEncode2.AddElem("type", folder.Type, sb);
  1079. LLSDxmlEncode2.AddEndMap(sb);
  1080. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(sb);
  1081. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1082. return;
  1083. }
  1084. }
  1085. catch { }
  1086. m_log.Debug("[CAPS]: CreateInventoryCategory failed to process request");
  1087. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1088. }
  1089. /// <summary>
  1090. /// Called by the CopyInventoryFromNotecard caps handler.
  1091. /// </summary>
  1092. /// <param name="request"></param>
  1093. /// <param name="path"></param>
  1094. /// <param name="param"></param>
  1095. public void CopyInventoryFromNotecard(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap content)
  1096. {
  1097. InventoryItemBase copyItem = null;
  1098. IClientAPI client = null;
  1099. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1100. try
  1101. {
  1102. UUID objectID = content["object-id"].AsUUID();
  1103. UUID notecardID = content["notecard-id"].AsUUID();
  1104. UUID folderID = content["folder-id"].AsUUID();
  1105. UUID itemID = content["item-id"].AsUUID();
  1106. // m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);
  1107. UUID noteAssetID = UUID.Zero;
  1108. UUID agentID = m_HostCapsObj.AgentID;
  1109. m_Scene.TryGetClient(agentID, out client);
  1110. if (!objectID.IsZero())
  1111. {
  1112. SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
  1113. if(part == null)
  1114. throw new Exception("failed to find object with notecard item" + notecardID.ToString());
  1115. TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(notecardID);
  1116. if (taskItem == null || taskItem.AssetID.IsZero())
  1117. throw new Exception("Failed to find notecard item" + notecardID.ToString());
  1118. if (!m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, agentID))
  1119. throw new Exception("No permission to copy notecard from object");
  1120. noteAssetID = taskItem.AssetID;
  1121. }
  1122. else
  1123. {
  1124. // we may have the item around...
  1125. InventoryItemBase localitem = m_Scene.InventoryService.GetItem(agentID, itemID);
  1126. if (localitem != null)
  1127. {
  1128. string message;
  1129. copyItem = m_Scene.GiveInventoryItem(agentID, localitem.Owner, itemID, folderID, out message);
  1130. if (copyItem == null)
  1131. throw new Exception("Failed to find notecard item" + notecardID.ToString());
  1132. m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
  1133. if (client != null)
  1134. client.SendBulkUpdateInventory(copyItem);
  1135. return;
  1136. }
  1137. if (!notecardID.IsZero())
  1138. {
  1139. InventoryItemBase noteItem = m_Scene.InventoryService.GetItem(agentID, notecardID);
  1140. if (noteItem == null || noteItem.AssetID.IsZero())
  1141. throw new Exception("Failed to find notecard item" + notecardID.ToString());
  1142. noteAssetID = noteItem.AssetID;
  1143. }
  1144. }
  1145. AssetBase noteAsset = m_Scene.AssetService.Get(noteAssetID.ToString());
  1146. if (noteAsset == null || noteAsset.Type != (sbyte)AssetType.Notecard)
  1147. throw new Exception("Failed to find the notecard asset" + notecardID.ToString());
  1148. InventoryItemBase item = SLUtil.GetEmbeddedItem(noteAsset.Data, itemID);
  1149. if(item == null)
  1150. throw new Exception("Failed to find the notecard item" + notecardID.ToString());
  1151. if (!m_Scene.Permissions.CanTransferUserInventory(itemID, item.Owner, agentID))
  1152. throw new Exception("Notecard item permissions check fail" + notecardID.ToString());
  1153. if (!m_Scene.Permissions.BypassPermissions())
  1154. {
  1155. if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
  1156. throw new Exception("Notecard item permissions check fail" + notecardID.ToString());
  1157. }
  1158. // check if we do have the item asset
  1159. noteAsset = m_Scene.AssetService.Get(item.AssetID.ToString());
  1160. if (noteAsset == null)
  1161. throw new Exception("Failed to find the notecard " + notecardID.ToString() +" item asset");
  1162. // find where to put it
  1163. InventoryFolderBase folder = null;
  1164. if (!folderID.IsZero())
  1165. folder = m_Scene.InventoryService.GetFolder(agentID, folderID);
  1166. if (folder == null && Enum.IsDefined(typeof(FolderType), (sbyte)item.AssetType))
  1167. folder = m_Scene.InventoryService.GetFolderForType(agentID, (FolderType)item.AssetType);
  1168. if (folder == null)
  1169. folder = m_Scene.InventoryService.GetRootFolder(agentID);
  1170. if (folder == null)
  1171. throw new Exception("Failed to find a folder for the notecard item" + notecardID.ToString());
  1172. item.Folder = folder.ID;
  1173. // do change owner permissions (c&p from scene inventory code)
  1174. if (m_Scene.Permissions.PropagatePermissions() && item.Owner != agentID)
  1175. {
  1176. uint permsMask = ~((uint)PermissionMask.Copy |
  1177. (uint)PermissionMask.Transfer |
  1178. (uint)PermissionMask.Modify |
  1179. (uint)PermissionMask.Export);
  1180. uint nextPerms = permsMask | (item.NextPermissions &
  1181. ((uint)PermissionMask.Copy |
  1182. (uint)PermissionMask.Transfer |
  1183. (uint)PermissionMask.Modify));
  1184. if (nextPerms == permsMask)
  1185. nextPerms |= (uint)PermissionMask.Transfer;
  1186. uint basePerms = item.BasePermissions | (uint)PermissionMask.Move;
  1187. uint ownerPerms = item.CurrentPermissions;
  1188. uint foldedPerms = (item.CurrentPermissions & (uint)PermissionMask.FoldedMask) << (int)PermissionMask.FoldingShift;
  1189. if (foldedPerms != 0 && item.InvType == (int)InventoryType.Object)
  1190. {
  1191. foldedPerms |= permsMask;
  1192. bool isRootMod = (item.CurrentPermissions &
  1193. (uint)PermissionMask.Modify) != 0 ?
  1194. true : false;
  1195. ownerPerms &= foldedPerms;
  1196. basePerms &= foldedPerms;
  1197. if (isRootMod)
  1198. {
  1199. ownerPerms |= (uint)PermissionMask.Modify;
  1200. basePerms |= (uint)PermissionMask.Modify;
  1201. }
  1202. }
  1203. ownerPerms &= nextPerms;
  1204. basePerms &= nextPerms;
  1205. basePerms &= ~(uint)PermissionMask.FoldedMask;
  1206. basePerms |= ((basePerms >> 13) & 7) | (((basePerms & (uint)PermissionMask.Export) != 0) ? (uint)PermissionMask.FoldedExport : 0);
  1207. item.BasePermissions = basePerms;
  1208. item.CurrentPermissions = ownerPerms;
  1209. item.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
  1210. item.Flags &= ~(uint)(InventoryItemFlags.ObjectOverwriteBase | InventoryItemFlags.ObjectOverwriteOwner | InventoryItemFlags.ObjectOverwriteGroup | InventoryItemFlags.ObjectOverwriteEveryone | InventoryItemFlags.ObjectOverwriteNextOwner);
  1211. item.NextPermissions = item.NextPermissions;
  1212. item.EveryOnePermissions = item.EveryOnePermissions & nextPerms;
  1213. }
  1214. else
  1215. {
  1216. //??
  1217. item.EveryOnePermissions &= item.NextPermissions;
  1218. }
  1219. item.GroupPermissions = 0; // we killed the group
  1220. item.Owner = agentID;
  1221. if (!m_Scene.InventoryService.AddItem(item))
  1222. throw new Exception("Failed create the notecard item" + notecardID.ToString());
  1223. m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0} FolderID:{1}", item.ID, item.Folder);
  1224. if (client != null)
  1225. client.SendBulkUpdateInventory(item);
  1226. return;
  1227. }
  1228. catch (Exception e)
  1229. {
  1230. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.Message);
  1231. copyItem = null;
  1232. }
  1233. if(copyItem == null)
  1234. {
  1235. if (client != null)
  1236. client.SendAlertMessage("Failed to retrieve item");
  1237. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1238. }
  1239. }
  1240. public void GetObjectPhysicsData(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap req)
  1241. {
  1242. OSDArray object_ids;
  1243. try
  1244. {
  1245. object_ids = (OSDArray)req["object_ids"];
  1246. }
  1247. catch
  1248. {
  1249. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1250. return;
  1251. }
  1252. osUTF8 lsl = LLSDxmlEncode2.Start();
  1253. if(object_ids.Count == 0)
  1254. LLSDxmlEncode2.AddEmptyMap(lsl);
  1255. else
  1256. {
  1257. LLSDxmlEncode2.AddMap(lsl);
  1258. for (int i = 0 ; i < object_ids.Count ; i++)
  1259. {
  1260. UUID uuid = object_ids[i].AsUUID();
  1261. SceneObjectPart obj = m_Scene.GetSceneObjectPart(uuid);
  1262. if (obj != null)
  1263. {
  1264. LLSDxmlEncode2.AddMap(uuid.ToString(),lsl);
  1265. LLSDxmlEncode2.AddElem("PhysicsShapeType", obj.PhysicsShapeType, lsl);
  1266. LLSDxmlEncode2.AddElem("Density", obj.Density, lsl);
  1267. LLSDxmlEncode2.AddElem("Friction", obj.Friction, lsl);
  1268. LLSDxmlEncode2.AddElem("Restitution", obj.Restitution, lsl);
  1269. LLSDxmlEncode2.AddElem("GravityMultiplier", obj.GravityModifier, lsl);
  1270. LLSDxmlEncode2.AddEndMap(lsl);
  1271. }
  1272. LLSDxmlEncode2.AddEndMap(lsl);
  1273. }
  1274. }
  1275. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(lsl);
  1276. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1277. }
  1278. public void GetObjectCost(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap req)
  1279. {
  1280. OSDArray object_ids;
  1281. try
  1282. {
  1283. object_ids = (OSDArray)req["object_ids"];
  1284. }
  1285. catch
  1286. {
  1287. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1288. return;
  1289. }
  1290. osUTF8 lsl = LLSDxmlEncode2.Start(512);
  1291. if(object_ids.Count == 0)
  1292. LLSDxmlEncode2.AddEmptyMap(lsl);
  1293. else
  1294. {
  1295. bool haveone = false;
  1296. LLSDxmlEncode2.AddMap(lsl);
  1297. for (int i = 0; i < object_ids.Count; i++)
  1298. {
  1299. UUID uuid = object_ids[i].AsUUID();
  1300. SceneObjectPart part = m_Scene.GetSceneObjectPart(uuid);
  1301. SceneObjectGroup grp = null;
  1302. if (part != null)
  1303. grp = part.ParentGroup;
  1304. if (grp != null)
  1305. {
  1306. haveone = true;
  1307. float linksetCost;
  1308. float linksetPhysCost;
  1309. float partCost;
  1310. float partPhysCost;
  1311. grp.GetResourcesCosts(part,out linksetCost,out linksetPhysCost,out partCost,out partPhysCost);
  1312. LLSDxmlEncode2.AddMap(uuid.ToString(), lsl);
  1313. LLSDxmlEncode2.AddElem("linked_set_resource_cost", linksetCost, lsl);
  1314. LLSDxmlEncode2.AddElem("resource_cost", partCost, lsl);
  1315. LLSDxmlEncode2.AddElem("physics_cost", partPhysCost, lsl);
  1316. LLSDxmlEncode2.AddElem("linked_set_physics_cost", linksetPhysCost, lsl);
  1317. LLSDxmlEncode2.AddElem("resource_limiting_type", "legacy", lsl);
  1318. LLSDxmlEncode2.AddEndMap(lsl);
  1319. }
  1320. }
  1321. if(!haveone)
  1322. {
  1323. LLSDxmlEncode2.AddMap(UUID.Zero.ToString(), lsl);
  1324. LLSDxmlEncode2.AddElem("linked_set_resource_cost", 0, lsl);
  1325. LLSDxmlEncode2.AddElem("resource_cost", 0, lsl);
  1326. LLSDxmlEncode2.AddElem("physics_cost", 0, lsl);
  1327. LLSDxmlEncode2.AddElem("linked_set_physics_cost", 0, lsl);
  1328. LLSDxmlEncode2.AddElem("resource_limiting_type", "legacy", lsl);
  1329. LLSDxmlEncode2.AddEndMap(lsl);
  1330. }
  1331. LLSDxmlEncode2.AddEndMap(lsl);
  1332. }
  1333. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(lsl);
  1334. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1335. }
  1336. public struct AttachmentScriptInfo
  1337. {
  1338. public UUID id;
  1339. public string name;
  1340. public Vector3 pos;
  1341. public int memory;
  1342. public int urls;
  1343. };
  1344. public void AttachmentResources(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1345. {
  1346. if(m_Scene.TryGetScenePresence(m_AgentID, out ScenePresence sp) && !sp.IsChildAgent && !sp.IsDeleted && !sp.IsInTransit)
  1347. {
  1348. int totalmem = 0;
  1349. int totalurls = 0;
  1350. List<SceneObjectGroup> atts = sp.GetAttachments();
  1351. Dictionary<byte, List<AttachmentScriptInfo>> perAttPoints = null;
  1352. if (atts.Count > 0)
  1353. {
  1354. IUrlModule urlModule = m_Scene.RequestModuleInterface<IUrlModule>();
  1355. perAttPoints = new Dictionary<byte, List<AttachmentScriptInfo>>();
  1356. foreach (SceneObjectGroup so in atts)
  1357. {
  1358. byte attp = so.GetAttachmentPoint();
  1359. if(!so.ScriptsMemory(out int mem))
  1360. continue;
  1361. int urls_used = 0;
  1362. totalmem += mem;
  1363. if (urlModule != null)
  1364. {
  1365. urls_used = urlModule.GetUrlCount(so.UUID);
  1366. totalurls += urls_used;
  1367. }
  1368. AttachmentScriptInfo info = new AttachmentScriptInfo()
  1369. {
  1370. id = so.UUID,
  1371. name = so.Name,
  1372. memory = mem,
  1373. urls = urls_used,
  1374. pos = so.AbsolutePosition
  1375. };
  1376. if(perAttPoints.TryGetValue(attp, out List<AttachmentScriptInfo> la))
  1377. la.Add(info);
  1378. else
  1379. perAttPoints[attp] = new List<AttachmentScriptInfo>(){ info };
  1380. }
  1381. }
  1382. osUTF8 sb = LLSDxmlEncode2.Start();
  1383. LLSDxmlEncode2.AddMap(sb);
  1384. if (atts.Count > 0)
  1385. {
  1386. LLSDxmlEncode2.AddArray("attachments", sb);
  1387. foreach (KeyValuePair<byte, List<AttachmentScriptInfo>> kvp in perAttPoints)
  1388. {
  1389. LLSDxmlEncode2.AddMap(sb);
  1390. LLSDxmlEncode2.AddElem("location", SLUtil.GetAttachmentName(kvp.Key), sb);
  1391. LLSDxmlEncode2.AddArray("objects", sb);
  1392. foreach(AttachmentScriptInfo asi in kvp.Value)
  1393. {
  1394. LLSDxmlEncode2.AddMap(sb);
  1395. LLSDxmlEncode2.AddElem("id", asi.id, sb);
  1396. LLSDxmlEncode2.AddElem("is_group_owned", (int)0, sb);
  1397. LLSDxmlEncode2.AddElem("location", asi.pos, sb);
  1398. LLSDxmlEncode2.AddElem("name", asi.name, sb);
  1399. LLSDxmlEncode2.AddElem("owner_id", m_AgentID, sb);
  1400. LLSDxmlEncode2.AddMap("resources", sb);
  1401. if (asi.memory > 0)
  1402. LLSDxmlEncode2.AddElem("memory", asi.memory, sb);
  1403. if (asi.urls > 0)
  1404. LLSDxmlEncode2.AddElem("urls", asi.urls, sb);
  1405. LLSDxmlEncode2.AddEndMap(sb);
  1406. LLSDxmlEncode2.AddEndMap(sb);
  1407. }
  1408. LLSDxmlEncode2.AddEndArray(sb);
  1409. LLSDxmlEncode2.AddEndMap(sb);
  1410. }
  1411. LLSDxmlEncode2.AddEndArray(sb); //attachments
  1412. }
  1413. else
  1414. LLSDxmlEncode2.AddEmptyArray("attachments", sb);
  1415. LLSDxmlEncode2.AddMap("summary", sb);
  1416. LLSDxmlEncode2.AddArray("available", sb);
  1417. int maxurls = totalurls <= 38? 38: totalurls; // we don't limit this
  1418. LLSDxmlEncode2.AddMap(sb);
  1419. LLSDxmlEncode2.AddElem("amount", maxurls, sb);
  1420. LLSDxmlEncode2.AddElem("type", "urls", sb);
  1421. LLSDxmlEncode2.AddEndMap(sb);
  1422. LLSDxmlEncode2.AddMap(sb);
  1423. LLSDxmlEncode2.AddElem("amount", (int)-1, sb);
  1424. LLSDxmlEncode2.AddElem("type", "memory", sb);
  1425. LLSDxmlEncode2.AddEndMap(sb);
  1426. LLSDxmlEncode2.AddEndArray(sb); //available
  1427. LLSDxmlEncode2.AddArray("used", sb);
  1428. LLSDxmlEncode2.AddMap(sb);
  1429. LLSDxmlEncode2.AddElem("amount",totalurls, sb);
  1430. LLSDxmlEncode2.AddElem("type", "urls", sb);
  1431. LLSDxmlEncode2.AddEndMap(sb);
  1432. LLSDxmlEncode2.AddMap(sb);
  1433. LLSDxmlEncode2.AddElem("amount", totalmem, sb);
  1434. LLSDxmlEncode2.AddElem("type", "memory", sb);
  1435. LLSDxmlEncode2.AddEndMap(sb);
  1436. LLSDxmlEncode2.AddEndArray(sb); //used
  1437. LLSDxmlEncode2.AddEndMap(sb); // summary
  1438. LLSDxmlEncode2.AddEndMap(sb);
  1439. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(sb);
  1440. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1441. return;
  1442. }
  1443. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1444. }
  1445. public class ScriptInfoForParcel
  1446. {
  1447. public UUID id;
  1448. public UUID owner;
  1449. public string name;
  1450. public int memory;
  1451. public int urls;
  1452. public bool groupOwned;
  1453. public Vector3 pos;
  1454. };
  1455. public class ParcelScriptInfo
  1456. {
  1457. public UUID id;
  1458. public string name;
  1459. public int localID;
  1460. public List<ScriptInfoForParcel> objects;
  1461. };
  1462. public void LandResources(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap req)
  1463. {
  1464. if (!m_Scene.TryGetScenePresence(m_AgentID, out ScenePresence sp))
  1465. {
  1466. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1467. return;
  1468. }
  1469. UUID parcelOwner;
  1470. LandData landdata = null;
  1471. ulong myHandler = m_Scene.RegionInfo.RegionHandle;
  1472. if (req.TryGetValue("parcel_id", out OSD tmp) && tmp is OSDUUID)
  1473. {
  1474. UUID parcelID = tmp.AsUUID();
  1475. if (Util.ParseFakeParcelID(parcelID, out ulong regionHandle, out uint x, out uint y) && regionHandle == myHandler)
  1476. {
  1477. ILandObject land = m_Scene.LandChannel.GetLandObjectClippedXY(x, y);
  1478. if (land != null)
  1479. landdata = land.LandData;
  1480. land = null;
  1481. }
  1482. }
  1483. if(landdata == null)
  1484. {
  1485. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1486. return;
  1487. }
  1488. parcelOwner = landdata.OwnerID;
  1489. int showType = 0;
  1490. if (sp.IsGod || m_Scene.Permissions.IsEstateManager(m_AgentID))
  1491. showType = 1;
  1492. else
  1493. {
  1494. if (parcelOwner == m_AgentID)
  1495. showType = 2;
  1496. else if (!landdata.GroupID.IsZero())
  1497. {
  1498. ulong powers = sp.ControllingClient.GetGroupPowers(landdata.GroupID);
  1499. if ((powers & (ulong)(GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup)) != 0)
  1500. showType = 2;
  1501. }
  1502. }
  1503. landdata = null;
  1504. int totalmem = 0;
  1505. int totalurls = 0;
  1506. bool ownerparcels = showType != 1;
  1507. bool showdetail = showType != 0;
  1508. List<ParcelScriptInfo> parcelsInfo = null;
  1509. IUrlModule urlModule = m_Scene.RequestModuleInterface<IUrlModule>();
  1510. List<ILandObject> allParcels = m_Scene.LandChannel.AllParcels();
  1511. if (showdetail)
  1512. parcelsInfo = new List<ParcelScriptInfo>(allParcels.Count);
  1513. for (int p = 0; p < allParcels.Count; ++p)
  1514. {
  1515. ILandObject parcel = allParcels[p];
  1516. landdata = parcel.LandData;
  1517. if (landdata == null)
  1518. continue;
  1519. if(ownerparcels && landdata.OwnerID != parcelOwner)
  1520. continue;
  1521. ParcelScriptInfo pi = null;
  1522. if (showdetail)
  1523. {
  1524. pi = new ParcelScriptInfo
  1525. {
  1526. name = landdata.Name,
  1527. localID = landdata.LocalID,
  1528. id = landdata.FakeID,
  1529. objects = new List<ScriptInfoForParcel>()
  1530. };
  1531. }
  1532. ISceneObject[] isops = parcel.GetSceneObjectGroups();
  1533. for(int i = 0; i < isops.Length; ++i)
  1534. {
  1535. SceneObjectGroup so = isops[i] as SceneObjectGroup;
  1536. if(so == null || so.IsDeleted || so.inTransit || so.IsAttachment)
  1537. continue;
  1538. if(!so.ScriptsMemory(out int mem))
  1539. continue;
  1540. int urls_used = 0;
  1541. totalmem += mem;
  1542. if (urlModule != null)
  1543. {
  1544. urls_used = urlModule.GetUrlCount(so.UUID);
  1545. totalurls += urls_used;
  1546. }
  1547. if (showdetail)
  1548. {
  1549. ScriptInfoForParcel sip = new ScriptInfoForParcel()
  1550. {
  1551. id = so.UUID,
  1552. owner = so.OwnerID,
  1553. name = so.Name,
  1554. memory = mem,
  1555. urls = urls_used,
  1556. groupOwned = (so.OwnerID == so.GroupID),
  1557. pos = so.AbsolutePosition
  1558. };
  1559. pi.objects.Add(sip);
  1560. }
  1561. }
  1562. if (showdetail)
  1563. parcelsInfo.Add(pi);
  1564. }
  1565. landdata = null;
  1566. osUTF8 lsl = LLSDxmlEncode2.Start();
  1567. LLSDxmlEncode2.AddMap(lsl);
  1568. string baseurl = m_HostCapsObj.SSLCaps ? "https://" : "http://";
  1569. baseurl += m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString();
  1570. string SRSPath = GetNewCapPath();
  1571. ScriptResourceSummary srs =
  1572. new ScriptResourceSummary(m_Scene, m_AgentID, m_HostCapsObj.HttpListener, SRSPath, httpRequest.RemoteIPEndPoint.Address,
  1573. totalmem, totalurls);
  1574. m_HostCapsObj.HttpListener.AddSimpleStreamHandler(new SimpleStreamHandler(SRSPath, srs.ScriptResourceSummaryCap));
  1575. string SRSURL = baseurl + SRSPath;
  1576. LLSDxmlEncode2.AddElem("ScriptResourceSummary", SRSURL, lsl);
  1577. if(showdetail)
  1578. {
  1579. string SRDPath = GetNewCapPath();
  1580. string SRDURL = baseurl + SRDPath;
  1581. ScriptResourceDetails srd =
  1582. new ScriptResourceDetails(m_Scene, m_AgentID, m_HostCapsObj.HttpListener, SRDPath, httpRequest.RemoteIPEndPoint.Address,
  1583. parcelsInfo);
  1584. m_HostCapsObj.HttpListener.AddSimpleStreamHandler(new SimpleStreamHandler(SRDPath, srd.ScriptResourceDetailsCap));
  1585. LLSDxmlEncode2.AddElem("ScriptResourceDetails", SRDURL, lsl);
  1586. }
  1587. LLSDxmlEncode2.AddEndMap(lsl);
  1588. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(lsl);
  1589. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1590. return;
  1591. }
  1592. public void ResourceCostSelected(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap req)
  1593. {
  1594. float phys=0;
  1595. float stream=0;
  1596. float simul=0;
  1597. if (req.ContainsKey("selected_roots"))
  1598. {
  1599. OSDArray object_ids = (OSDArray)req["selected_roots"];
  1600. // should go by SOG suming costs for all parts
  1601. // ll v3 works ok with several objects select we get the list and adds ok
  1602. // FS calls per object so results are wrong guess fs bug
  1603. for (int i = 0; i < object_ids.Count; i++)
  1604. {
  1605. UUID uuid = object_ids[i].AsUUID();
  1606. float Physc;
  1607. float simulc;
  1608. float streamc;
  1609. SceneObjectGroup grp = m_Scene.GetGroupByPrim(uuid);
  1610. if (grp != null)
  1611. {
  1612. grp.GetSelectedCosts(out Physc, out streamc, out simulc);
  1613. phys += Physc;
  1614. stream += streamc;
  1615. simul += simulc;
  1616. }
  1617. }
  1618. }
  1619. else if (req.ContainsKey("selected_prims"))
  1620. {
  1621. OSDArray object_ids = (OSDArray)req["selected_prims"];
  1622. // don't see in use in any of the 2 viewers
  1623. // guess it should be for edit linked but... nothing
  1624. // should go to SOP per part
  1625. for (int i = 0; i < object_ids.Count; i++)
  1626. {
  1627. UUID uuid = object_ids[i].AsUUID();
  1628. SceneObjectPart part = m_Scene.GetSceneObjectPart(uuid);
  1629. if (part != null)
  1630. {
  1631. phys += part.PhysicsCost;
  1632. stream += part.StreamingCost;
  1633. simul += part.SimulationCost;
  1634. }
  1635. }
  1636. }
  1637. osUTF8 lsl = LLSDxmlEncode2.Start();
  1638. LLSDxmlEncode2.AddMap(lsl);
  1639. LLSDxmlEncode2.AddMap("selected", lsl);
  1640. LLSDxmlEncode2.AddElem("physics", phys, lsl);
  1641. LLSDxmlEncode2.AddElem("streaming", stream, lsl);
  1642. LLSDxmlEncode2.AddElem("simulation", simul, lsl);
  1643. LLSDxmlEncode2.AddEndMap(lsl);
  1644. LLSDxmlEncode2.AddEndMap(lsl);
  1645. // resp["transaction_id"] = "undef";
  1646. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(lsl);
  1647. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1648. }
  1649. public void UpdateAgentInformation(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1650. {
  1651. if (httpRequest.HttpMethod != "POST")
  1652. {
  1653. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1654. return;
  1655. }
  1656. // this is wrong now ignores request and sends same result for all
  1657. // we don't store and worse don't use that to filter contents
  1658. // OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1659. OSDMap resp = new OSDMap();
  1660. OSDMap accessPrefs = new OSDMap();
  1661. accessPrefs["max"] = "A";
  1662. resp["access_prefs"] = accessPrefs;
  1663. httpResponse.RawBuffer = OSDParser.SerializeLLSDXmlBytes(resp);
  1664. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1665. }
  1666. public bool OSDMapTOVector3(OSDMap map, out Vector3 v)
  1667. {
  1668. v = Vector3.Zero;
  1669. if(!map.ContainsKey("X"))
  1670. return false;
  1671. if(!map.ContainsKey("Y"))
  1672. return false;
  1673. if(!map.ContainsKey("Z"))
  1674. return false;
  1675. v.X = (float)map["X"].AsReal();
  1676. v.Y = (float)map["Y"].AsReal();
  1677. v.Z = (float)map["Z"].AsReal();
  1678. return true;
  1679. }
  1680. public void HomeLocation(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1681. {
  1682. if (httpRequest.HttpMethod != "POST")
  1683. {
  1684. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1685. return;
  1686. }
  1687. bool fail = true;
  1688. string message = "Set Home request failed";
  1689. //int locationID = 1;
  1690. Vector3 pos = Vector3.Zero;
  1691. Vector3 lookAt = Vector3.Zero;
  1692. IClientAPI client = null;
  1693. ScenePresence sp;
  1694. while(true)
  1695. {
  1696. if(m_Scene.GridUserService == null)
  1697. break;
  1698. if(m_Scene.UserManagementModule == null)
  1699. break;
  1700. m_Scene.TryGetScenePresence(m_AgentID, out sp);
  1701. if(sp == null || sp.IsChildAgent || sp.IsDeleted)
  1702. break;
  1703. if(sp.IsInTransit && !sp.IsInLocalTransit)
  1704. break;
  1705. client = sp.ControllingClient;
  1706. if(!m_Scene.UserManagementModule.IsLocalGridUser(m_AgentID))
  1707. break;
  1708. OSDMap req;
  1709. try
  1710. {
  1711. req = (OSDMap)OSDParser.DeserializeLLSDXml(httpRequest.InputStream);
  1712. }
  1713. catch
  1714. {
  1715. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1716. return;
  1717. }
  1718. OSD tmp;
  1719. if (!req.TryGetValue("HomeLocation", out tmp) || !(tmp is OSDMap))
  1720. break;
  1721. OSDMap HLocation = (OSDMap)tmp;
  1722. if(!HLocation.TryGetValue("LocationPos", out tmp) || !(tmp is OSDMap))
  1723. break;
  1724. if (!OSDMapTOVector3((OSDMap)tmp, out pos))
  1725. break;
  1726. if (!HLocation.TryGetValue("LocationLookAt", out tmp) || !(tmp is OSDMap))
  1727. break;
  1728. if (!OSDMapTOVector3((OSDMap)tmp, out lookAt))
  1729. break;
  1730. //locationID = HLocation["LocationId"].AsInteger();
  1731. ILandObject land = m_Scene.LandChannel.GetLandObject(pos);
  1732. if(land == null)
  1733. break;
  1734. ulong gpowers = client.GetGroupPowers(land.LandData.GroupID);
  1735. SceneObjectGroup telehub = null;
  1736. if (!m_Scene.RegionInfo.RegionSettings.TelehubObject.IsZero())
  1737. // Does the telehub exist in the scene?
  1738. telehub = m_Scene.GetSceneObjectGroup(m_Scene.RegionInfo.RegionSettings.TelehubObject);
  1739. if (!m_Scene.Permissions.IsAdministrator(m_AgentID) && // (a) gods and land managers can set home
  1740. !m_Scene.Permissions.IsGod(m_AgentID) &&
  1741. m_AgentID != land.LandData.OwnerID && // (b) land owners can set home
  1742. // (c) members of the land-associated group in roles that can set home
  1743. ((gpowers & (ulong)GroupPowers.AllowSetHome) != (ulong)GroupPowers.AllowSetHome) &&
  1744. // (d) parcels with telehubs can be the home of anyone
  1745. (telehub == null || !land.ContainsPoint((int)telehub.AbsolutePosition.X, (int)telehub.AbsolutePosition.Y)))
  1746. {
  1747. message = "You are not allowed to set your home location in this parcel.";
  1748. break;
  1749. }
  1750. string userId;
  1751. UUID test;
  1752. if (!m_Scene.UserManagementModule.GetUserUUI(m_AgentID, out userId))
  1753. {
  1754. message = "Set Home request failed. (User Lookup)";
  1755. break;
  1756. }
  1757. if (!UUID.TryParse(userId, out test))
  1758. {
  1759. message = "Set Home request failed. (HG visitor)";
  1760. break;
  1761. }
  1762. if (m_Scene.GridUserService.SetHome(userId, land.RegionUUID, pos, lookAt))
  1763. fail = false;
  1764. break;
  1765. }
  1766. OSDMap resp = new OSDMap();
  1767. if(fail)
  1768. {
  1769. if(client != null)
  1770. client.SendAlertMessage(message);
  1771. resp["success"] = "false";
  1772. }
  1773. else
  1774. {
  1775. // so its http but still needs a udp reply to inform user? crap :p
  1776. if(client != null)
  1777. client.SendAlertMessage("Home position set.","HomePositionSet");
  1778. resp["success"] = "true";
  1779. OSDMap homeloc = new OSDMap();
  1780. OSDMap homelocpos = new OSDMap();
  1781. // for some odd reason viewers send pos as reals but read as integer
  1782. homelocpos["X"] = new OSDReal(pos.X);
  1783. homelocpos["Y"] = new OSDReal(pos.Y);
  1784. homelocpos["Z"] = new OSDReal(pos.Z);
  1785. homeloc["LocationPos"] = homelocpos;
  1786. resp["HomeLocation"] = homeloc;
  1787. }
  1788. httpResponse.RawBuffer = Util.UTF8NBGetbytes(OSDParser.SerializeLLSDXmlString(resp));
  1789. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1790. }
  1791. private static int CompareRolesByMembersDesc(GroupRolesData x, GroupRolesData y)
  1792. {
  1793. return -(x.Members.CompareTo(y.Members));
  1794. }
  1795. public void GroupMemberData(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1796. {
  1797. if (httpRequest.HttpMethod != "POST")
  1798. {
  1799. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1800. return;
  1801. }
  1802. OSDMap resp = new OSDMap();
  1803. bool fail = true;
  1804. IClientAPI client = null;
  1805. ScenePresence sp;
  1806. IGroupsModule m_GroupsModule;
  1807. UUID groupID = UUID.Zero;
  1808. while(true)
  1809. {
  1810. m_GroupsModule = m_Scene.RequestModuleInterface<IGroupsModule>();
  1811. if(m_GroupsModule == null)
  1812. break;
  1813. m_Scene.TryGetScenePresence(m_AgentID, out sp);
  1814. if(sp == null || sp.IsChildAgent || sp.IsDeleted)
  1815. break;
  1816. if(sp.IsInTransit && !sp.IsInLocalTransit)
  1817. break;
  1818. client = sp.ControllingClient;
  1819. OSDMap req;
  1820. try
  1821. {
  1822. req = (OSDMap)OSDParser.DeserializeLLSDXml(httpRequest.InputStream);
  1823. }
  1824. catch
  1825. {
  1826. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  1827. return;
  1828. }
  1829. OSD tmp;
  1830. if(!req.TryGetValue("group_id", out tmp) || !(tmp is OSDUUID))
  1831. break;
  1832. groupID = tmp.AsUUID();
  1833. if(groupID.IsZero())
  1834. break;
  1835. List<GroupRolesData> roles = m_GroupsModule.GroupRoleDataRequest(client, groupID);
  1836. if(roles == null || roles.Count == 0)
  1837. break;
  1838. List<GroupMembersData> members = m_GroupsModule.GroupMembersRequest(client, groupID);
  1839. if(members == null || members.Count == 0)
  1840. break;
  1841. int memberCount = members.Count;
  1842. Dictionary<string,int> titles = new Dictionary<string,int>();
  1843. int i = 0;
  1844. ulong defaultPowers = 0;
  1845. // build titles array and index
  1846. roles.Sort(CompareRolesByMembersDesc);
  1847. OSDArray osdtitles = new OSDArray();
  1848. foreach(GroupRolesData grd in roles)
  1849. {
  1850. if(grd.Title == null)
  1851. continue;
  1852. string title = grd.Title;
  1853. if(i==0)
  1854. defaultPowers = grd.Powers;
  1855. if(!titles.ContainsKey(title))
  1856. {
  1857. titles[title] = i++;
  1858. osdtitles.Add(new OSDString(title));
  1859. }
  1860. }
  1861. if(titles.Count == 0)
  1862. break;
  1863. OSDMap osdmembers = new OSDMap();
  1864. foreach(GroupMembersData gmd in members)
  1865. {
  1866. OSDMap m = new OSDMap();
  1867. if(gmd.OnlineStatus != null && gmd.OnlineStatus != "")
  1868. m["last_login"] = new OSDString(gmd.OnlineStatus);
  1869. if(gmd.AgentPowers != defaultPowers)
  1870. m["powers"] = new OSDString((gmd.AgentPowers).ToString("X"));
  1871. if(gmd.Title != null && titles.ContainsKey(gmd.Title) && titles[gmd.Title] != 0)
  1872. m["title"] = new OSDInteger(titles[gmd.Title]);
  1873. if(gmd.IsOwner)
  1874. m["owner"] = new OSDString("true");
  1875. if(gmd.Contribution != 0)
  1876. m["donated_square_meters"] = new OSDInteger(gmd.Contribution);
  1877. osdmembers[(gmd.AgentID).ToString()] = m;
  1878. }
  1879. OSDMap osddefaults = new OSDMap();
  1880. osddefaults["default_powers"] = new OSDString(defaultPowers.ToString("X"));
  1881. resp["group_id"] = new OSDUUID(groupID);
  1882. resp["agent_id"] = new OSDUUID(m_AgentID);
  1883. resp["member_count"] = new OSDInteger(memberCount);
  1884. resp["defaults"] = osddefaults;
  1885. resp["titles"] = osdtitles;
  1886. resp["members"] = osdmembers;
  1887. fail = false;
  1888. break;
  1889. }
  1890. if(fail)
  1891. {
  1892. resp["group_id"] = new OSDUUID(groupID);
  1893. resp["agent_id"] = new OSDUUID(m_AgentID);
  1894. resp["member_count"] = new OSDInteger(0);
  1895. resp["defaults"] = new OSDMap();
  1896. resp["titles"] = new OSDArray();
  1897. resp["members"] = new OSDMap();
  1898. }
  1899. httpResponse.RawBuffer = Util.UTF8NBGetbytes(OSDParser.SerializeLLSDXmlString(resp));
  1900. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1901. }
  1902. public void GetDisplayNames(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1903. {
  1904. if (httpRequest.HttpMethod != "GET")
  1905. {
  1906. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  1907. return;
  1908. }
  1909. ScenePresence sp = m_Scene.GetScenePresence(m_AgentID);
  1910. if(sp == null || sp.IsDeleted)
  1911. {
  1912. httpResponse.StatusCode = (int)HttpStatusCode.Gone;
  1913. return;
  1914. }
  1915. if(sp.IsInTransit && !sp.IsInLocalTransit)
  1916. {
  1917. httpResponse.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  1918. httpResponse.AddHeader("Retry-After","30");
  1919. return;
  1920. }
  1921. // Full content request
  1922. NameValueCollection query = httpRequest.QueryString;
  1923. string[] ids = query.GetValues("ids");
  1924. osUTF8 lsl;
  1925. if(ids.Length == 0)
  1926. {
  1927. lsl = LLSDxmlEncode2.Start();
  1928. LLSDxmlEncode2.AddMap(lsl);
  1929. LLSDxmlEncode2.AddEmptyArray("agents", lsl);
  1930. }
  1931. else
  1932. {
  1933. List<UserData> names = m_UserManager.GetKnownUsers(ids, m_scopeID);
  1934. lsl = LLSDxmlEncode2.Start(names.Count * 256 + 256);
  1935. LLSDxmlEncode2.AddMap(lsl);
  1936. if (names.Count == 0)
  1937. LLSDxmlEncode2.AddEmptyArray("agents", lsl);
  1938. else
  1939. {
  1940. LLSDxmlEncode2.AddArray("agents", lsl);
  1941. foreach (UserData ud in names)
  1942. {
  1943. // dont tell about unknown users, we can't send them back on Bad either
  1944. if (string.IsNullOrEmpty(ud.FirstName) || ud.FirstName.Equals("Unkown"))
  1945. continue;
  1946. string fullname = ud.FirstName + " " + ud.LastName;
  1947. LLSDxmlEncode2.AddMap(lsl);
  1948. LLSDxmlEncode2.AddElem("username", fullname, lsl);
  1949. LLSDxmlEncode2.AddElem("display_name", fullname, lsl);
  1950. LLSDxmlEncode2.AddElem("display_name_next_update", DateTime.UtcNow.AddDays(8), lsl);
  1951. LLSDxmlEncode2.AddElem("display_name_expires", DateTime.UtcNow.AddMonths(1), lsl);
  1952. LLSDxmlEncode2.AddElem("legacy_first_name", ud.FirstName, lsl);
  1953. LLSDxmlEncode2.AddElem("legacy_last_name", ud.LastName, lsl);
  1954. LLSDxmlEncode2.AddElem("id", ud.Id, lsl);
  1955. LLSDxmlEncode2.AddElem("is_display_name_default", true, lsl);
  1956. LLSDxmlEncode2.AddEndMap(lsl);
  1957. }
  1958. LLSDxmlEncode2.AddEndArray(lsl);
  1959. }
  1960. }
  1961. LLSDxmlEncode2.AddEndMap(lsl);
  1962. httpResponse.RawBuffer = LLSDxmlEncode2.EndToNBBytes(lsl);
  1963. httpResponse.ContentType = "application/llsd+xml";
  1964. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  1965. }
  1966. public class AssetUploader
  1967. {
  1968. private static readonly ILog m_log =
  1969. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1970. public event UpLoadedAsset OnUpLoad;
  1971. private UpLoadedAsset handlerUpLoad = null;
  1972. private string uploaderPath = String.Empty;
  1973. private UUID newAssetID;
  1974. private UUID inventoryItemID;
  1975. private UUID parentFolder;
  1976. private IHttpServer httpListener;
  1977. private bool m_dumpAssetsToFile;
  1978. private string m_assetName = String.Empty;
  1979. private string m_assetDes = String.Empty;
  1980. private string m_invType = String.Empty;
  1981. private string m_assetType = String.Empty;
  1982. private int m_cost;
  1983. private string m_error = String.Empty;
  1984. private System.Timers.Timer m_timeoutTimer;
  1985. private UUID m_texturesFolder;
  1986. private int m_nreqtextures;
  1987. private int m_nreqmeshs;
  1988. private int m_nreqinstances;
  1989. private bool m_IsAtestUpload;
  1990. private int m_nextOwnerMask;
  1991. private int m_groupMask;
  1992. private int m_everyoneMask;
  1993. private int[] m_meshesSides;
  1994. public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
  1995. UUID parentFolderID, string invType, string assetType, string path,
  1996. IHttpServer httpServer, bool dumpAssetsToFile,
  1997. int totalCost, UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
  1998. bool IsAtestUpload, int nextOwnerMask, int groupMask, int everyoneMask, int[] meshesSides)
  1999. {
  2000. m_assetName = assetName;
  2001. m_assetDes = description;
  2002. newAssetID = assetID;
  2003. inventoryItemID = inventoryItem;
  2004. uploaderPath = path;
  2005. httpListener = httpServer;
  2006. parentFolder = parentFolderID;
  2007. m_assetType = assetType;
  2008. m_invType = invType;
  2009. m_dumpAssetsToFile = dumpAssetsToFile;
  2010. m_cost = totalCost;
  2011. m_texturesFolder = texturesFolder;
  2012. m_nreqtextures = nreqtextures;
  2013. m_nreqmeshs = nreqmeshs;
  2014. m_nreqinstances = nreqinstances;
  2015. m_IsAtestUpload = IsAtestUpload;
  2016. m_timeoutTimer = new System.Timers.Timer();
  2017. m_timeoutTimer.Elapsed += TimedOut;
  2018. m_timeoutTimer.Interval = 120000;
  2019. m_timeoutTimer.AutoReset = false;
  2020. m_timeoutTimer.Start();
  2021. m_nextOwnerMask = nextOwnerMask;
  2022. m_groupMask = groupMask;
  2023. m_everyoneMask = everyoneMask;
  2024. m_meshesSides = meshesSides;
  2025. }
  2026. /// <summary>
  2027. /// Handle raw asset upload data via the capability.
  2028. /// </summary>
  2029. /// <param name="data"></param>
  2030. /// <param name="path"></param>
  2031. /// <param name="param"></param>
  2032. /// <returns></returns>
  2033. public string uploaderCaps(byte[] data, string path, string param)
  2034. {
  2035. UUID inv = inventoryItemID;
  2036. string res = String.Empty;
  2037. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  2038. /*
  2039. uploadComplete.new_asset = newAssetID.ToString();
  2040. uploadComplete.new_inventory_item = inv;
  2041. uploadComplete.state = "complete";
  2042. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  2043. */
  2044. m_timeoutTimer.Stop();
  2045. httpListener.RemoveStreamHandler("POST", uploaderPath);
  2046. // TODO: probably make this a better set of extensions here
  2047. string extension = ".jp2";
  2048. if (m_invType != "image")
  2049. {
  2050. extension = ".dat";
  2051. }
  2052. if (m_dumpAssetsToFile)
  2053. {
  2054. SaveAssetToFile(m_assetName + extension, data);
  2055. }
  2056. handlerUpLoad = OnUpLoad;
  2057. if (handlerUpLoad != null)
  2058. {
  2059. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType,
  2060. m_cost, m_texturesFolder, m_nreqtextures, m_nreqmeshs, m_nreqinstances, m_IsAtestUpload,
  2061. ref m_error, ref m_nextOwnerMask, ref m_groupMask, ref m_everyoneMask, m_meshesSides);
  2062. }
  2063. uploadComplete.new_next_owner_mask = m_nextOwnerMask;
  2064. uploadComplete.new_group_mask = m_groupMask;
  2065. uploadComplete.new_everyone_mask = m_everyoneMask;
  2066. if (m_error == String.Empty)
  2067. {
  2068. uploadComplete.new_asset = newAssetID.ToString();
  2069. uploadComplete.new_inventory_item = inv;
  2070. // if (m_texturesFolder != UUID.Zero)
  2071. // uploadComplete.new_texture_folder_id = m_texturesFolder;
  2072. if (m_IsAtestUpload)
  2073. {
  2074. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  2075. resperror.message = "Upload SUCCESSFUL for testing purposes only. Other uses are prohibited. Item will not work after 48 hours or on other regions";
  2076. resperror.identifier = inv;
  2077. uploadComplete.error = resperror;
  2078. }
  2079. uploadComplete.state = "complete";
  2080. }
  2081. else
  2082. {
  2083. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  2084. resperror.message = m_error;
  2085. resperror.identifier = inv;
  2086. uploadComplete.error = resperror;
  2087. uploadComplete.state = "failed";
  2088. }
  2089. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  2090. return res;
  2091. }
  2092. private void TimedOut(object sender, ElapsedEventArgs args)
  2093. {
  2094. m_log.InfoFormat("[CAPS]: Removing URL and handler for timed out mesh upload");
  2095. httpListener.RemoveStreamHandler("POST", uploaderPath);
  2096. }
  2097. private static void SaveAssetToFile(string filename, byte[] data)
  2098. {
  2099. string assetPath = "UserAssets";
  2100. if (!Directory.Exists(assetPath))
  2101. {
  2102. Directory.CreateDirectory(assetPath);
  2103. }
  2104. FileStream fs = File.Create(Path.Combine(assetPath, Util.SafeFileName(filename)));
  2105. BinaryWriter bw = new BinaryWriter(fs);
  2106. bw.Write(data);
  2107. bw.Close();
  2108. fs.Close();
  2109. }
  2110. }
  2111. public class ExpiringCapBase
  2112. {
  2113. protected IHttpServer m_httpListener;
  2114. protected string m_mypath;
  2115. protected Timer m_timeoutTimer;
  2116. public ExpiringCapBase(IHttpServer httpServer, string path)
  2117. {
  2118. m_httpListener = httpServer;
  2119. m_mypath = path;
  2120. }
  2121. public virtual void Start(int timeout)
  2122. {
  2123. m_timeoutTimer = new Timer(Timedout, null, timeout, Timeout.Infinite);
  2124. }
  2125. public virtual void Stop()
  2126. {
  2127. m_httpListener.RemoveSimpleStreamHandler(m_mypath);
  2128. m_timeoutTimer.Dispose();
  2129. m_timeoutTimer = null;
  2130. }
  2131. public virtual void Timedout(object state)
  2132. {
  2133. Stop();
  2134. m_log.InfoFormat("[CAPS]: Removing URL and handler for timed out service");
  2135. }
  2136. }
  2137. public class ScriptResourceSummary : ExpiringCapBase
  2138. {
  2139. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  2140. private Scene m_scene;
  2141. private UUID m_agentID;
  2142. private int m_memory;
  2143. private int m_urls;
  2144. private IPAddress m_address;
  2145. public ScriptResourceSummary(Scene scene, UUID agentID, IHttpServer httpServer, string path, IPAddress address,
  2146. int memory, int urls) : base(httpServer, path)
  2147. {
  2148. m_address = address;
  2149. m_scene = scene;
  2150. m_agentID = agentID;
  2151. m_memory = memory;
  2152. m_urls = urls;
  2153. Start(30000);
  2154. }
  2155. /// <summary>
  2156. /// Handle raw asset upload data via the capability.
  2157. /// </summary>
  2158. /// <param name="data"></param>
  2159. /// <param name="path"></param>
  2160. /// <param name="param"></param>
  2161. /// <returns></returns>
  2162. public void ScriptResourceSummaryCap(IOSHttpRequest request, IOSHttpResponse response)
  2163. {
  2164. Stop();
  2165. if (!request.RemoteIPEndPoint.Address.Equals(m_address))
  2166. {
  2167. response.StatusCode = (int)HttpStatusCode.Unauthorized;
  2168. return;
  2169. }
  2170. if (m_scene.ShuttingDown || !m_scene.TryGetScenePresence(m_agentID, out ScenePresence sp) || sp.IsChildAgent || sp.IsInTransit)
  2171. {
  2172. response.StatusCode = (int)HttpStatusCode.Unauthorized;
  2173. return;
  2174. }
  2175. osUTF8 sb = LLSDxmlEncode2.Start();
  2176. LLSDxmlEncode2.AddMap(sb);
  2177. LLSDxmlEncode2.AddMap("summary", sb);
  2178. LLSDxmlEncode2.AddArray("available", sb);
  2179. int maxurls = m_urls + 5000; // we don't limit this
  2180. LLSDxmlEncode2.AddMap(sb);
  2181. LLSDxmlEncode2.AddElem("amount", maxurls, sb);
  2182. LLSDxmlEncode2.AddElem("type", "urls", sb);
  2183. LLSDxmlEncode2.AddEndMap(sb);
  2184. LLSDxmlEncode2.AddMap(sb);
  2185. LLSDxmlEncode2.AddElem("amount", (int)-1, sb);
  2186. LLSDxmlEncode2.AddElem("type", "memory", sb);
  2187. LLSDxmlEncode2.AddEndMap(sb);
  2188. LLSDxmlEncode2.AddEndArray(sb); //available
  2189. LLSDxmlEncode2.AddArray("used", sb);
  2190. LLSDxmlEncode2.AddMap(sb);
  2191. LLSDxmlEncode2.AddElem("amount", m_urls, sb);
  2192. LLSDxmlEncode2.AddElem("type", "urls", sb);
  2193. LLSDxmlEncode2.AddEndMap(sb);
  2194. LLSDxmlEncode2.AddMap(sb);
  2195. LLSDxmlEncode2.AddElem("amount", m_memory, sb);
  2196. LLSDxmlEncode2.AddElem("type", "memory", sb);
  2197. LLSDxmlEncode2.AddEndMap(sb);
  2198. LLSDxmlEncode2.AddEndArray(sb); //used
  2199. LLSDxmlEncode2.AddEndMap(sb); // summary
  2200. LLSDxmlEncode2.AddEndMap(sb);
  2201. response.RawBuffer = LLSDxmlEncode2.EndToNBBytes(sb);
  2202. response.StatusCode = (int)HttpStatusCode.OK;
  2203. }
  2204. }
  2205. public class ScriptResourceDetails : ExpiringCapBase
  2206. {
  2207. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  2208. private Scene m_scene;
  2209. private UUID m_agentID;
  2210. private List<ParcelScriptInfo> m_parcelsInfo;
  2211. private IPAddress m_address;
  2212. public ScriptResourceDetails(Scene scene, UUID agentID, IHttpServer httpServer, string path, IPAddress address,
  2213. List<ParcelScriptInfo> parcelsInfo) :base(httpServer, path)
  2214. {
  2215. m_address = address;
  2216. m_scene = scene;
  2217. m_agentID = agentID;
  2218. m_parcelsInfo = parcelsInfo;
  2219. Start(30000);
  2220. }
  2221. /// <summary>
  2222. /// Handle raw asset upload data via the capability.
  2223. /// </summary>
  2224. /// <param name="data"></param>
  2225. /// <param name="path"></param>
  2226. /// <param name="param"></param>
  2227. /// <returns></returns>
  2228. public void ScriptResourceDetailsCap(IOSHttpRequest request, IOSHttpResponse response)
  2229. {
  2230. Stop();
  2231. if (!request.RemoteIPEndPoint.Address.Equals(m_address))
  2232. {
  2233. response.StatusCode = (int)HttpStatusCode.Unauthorized;
  2234. return;
  2235. }
  2236. if (m_scene.ShuttingDown || !m_scene.TryGetScenePresence(m_agentID, out ScenePresence sp) || sp.IsChildAgent || sp.IsInTransit)
  2237. {
  2238. response.StatusCode = (int)HttpStatusCode.Unauthorized;
  2239. return;
  2240. }
  2241. osUTF8 sb = LLSDxmlEncode2.Start();
  2242. LLSDxmlEncode2.AddMap(sb);
  2243. if (m_parcelsInfo.Count > 0)
  2244. {
  2245. LLSDxmlEncode2.AddArray("parcels", sb);
  2246. foreach (ParcelScriptInfo ps in m_parcelsInfo)
  2247. {
  2248. LLSDxmlEncode2.AddMap(sb);
  2249. LLSDxmlEncode2.AddElem("name", ps.name, sb);
  2250. LLSDxmlEncode2.AddElem("id", ps.id, sb);
  2251. LLSDxmlEncode2.AddElem("local_id", ps.localID, sb);
  2252. if(ps.objects.Count > 0)
  2253. {
  2254. LLSDxmlEncode2.AddArray("objects", sb);
  2255. foreach (ScriptInfoForParcel sip in ps.objects)
  2256. {
  2257. LLSDxmlEncode2.AddMap(sb);
  2258. LLSDxmlEncode2.AddElem("id", sip.id, sb);
  2259. LLSDxmlEncode2.AddElem("is_group_owned", sip.groupOwned, sb);
  2260. LLSDxmlEncode2.AddElem("location", sip.pos, sb);
  2261. LLSDxmlEncode2.AddElem("name", sip.name, sb);
  2262. LLSDxmlEncode2.AddElem("owner_id", sip.owner, sb);
  2263. LLSDxmlEncode2.AddMap("resources", sb);
  2264. LLSDxmlEncode2.AddElem("memory", sip.memory, sb);
  2265. LLSDxmlEncode2.AddElem("urls", sip.urls, sb);
  2266. LLSDxmlEncode2.AddEndMap(sb);
  2267. LLSDxmlEncode2.AddEndMap(sb);
  2268. }
  2269. LLSDxmlEncode2.AddEndArray(sb);
  2270. }
  2271. else
  2272. LLSDxmlEncode2.AddEmptyArray("objects", sb);
  2273. LLSDxmlEncode2.AddEndMap(sb);
  2274. }
  2275. LLSDxmlEncode2.AddEndArray(sb); //parcels
  2276. }
  2277. else
  2278. LLSDxmlEncode2.AddEmptyArray("parcels", sb);
  2279. LLSDxmlEncode2.AddEndMap(sb);
  2280. response.RawBuffer = LLSDxmlEncode2.EndToNBBytes(sb);
  2281. response.StatusCode = (int)HttpStatusCode.OK;
  2282. }
  2283. }
  2284. }
  2285. }