BunchOfCaps.cs 111 KB

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