BunchOfCaps.cs 114 KB

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