BunchOfCaps.cs 99 KB

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