1
0

BunchOfCaps.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Text;
  33. using OpenMetaverse;
  34. using OpenMetaverse.StructuredData;
  35. using Nini.Config;
  36. using log4net;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Capabilities;
  39. using OpenSim.Region.Framework;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Region.Framework.Scenes.Serialization;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Framework.Servers.HttpServer;
  44. using OpenSim.Services.Interfaces;
  45. using Caps = OpenSim.Framework.Capabilities.Caps;
  46. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  47. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  48. namespace OpenSim.Region.ClientStack.Linden
  49. {
  50. public delegate void UpLoadedAsset(
  51. string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
  52. byte[] data, string inventoryType, string assetType);
  53. public delegate UUID UpdateItem(UUID itemID, byte[] data);
  54. public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
  55. public delegate void NewInventoryItem(UUID userID, InventoryItemBase item);
  56. public delegate void NewAsset(AssetBase asset);
  57. public delegate UUID ItemUpdatedCallback(UUID userID, UUID itemID, byte[] data);
  58. public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
  59. bool isScriptRunning, byte[] data);
  60. public delegate InventoryCollection FetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
  61. bool fetchFolders, bool fetchItems, int sortOrder, out int version);
  62. /// <summary>
  63. /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
  64. /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
  65. /// to just pass the whole Scene into CAPS.
  66. /// </summary>
  67. public delegate IClientAPI GetClientDelegate(UUID agentID);
  68. public class BunchOfCaps
  69. {
  70. private static readonly ILog m_log =
  71. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  72. private Scene m_Scene;
  73. private Caps m_HostCapsObj;
  74. private static readonly string m_requestPath = "0000/";
  75. // private static readonly string m_mapLayerPath = "0001/";
  76. private static readonly string m_newInventory = "0002/";
  77. //private static readonly string m_requestTexture = "0003/";
  78. private static readonly string m_notecardUpdatePath = "0004/";
  79. private static readonly string m_notecardTaskUpdatePath = "0005/";
  80. // private static readonly string m_fetchInventoryPath = "0006/";
  81. // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
  82. // These are callbacks which will be setup by the scene so that we can update scene data when we
  83. // receive capability calls
  84. public NewInventoryItem AddNewInventoryItem = null;
  85. public NewAsset AddNewAsset = null;
  86. public ItemUpdatedCallback ItemUpdatedCall = null;
  87. public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
  88. public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
  89. public GetClientDelegate GetClient = null;
  90. private bool m_persistBakedTextures = false;
  91. private IAssetService m_assetService;
  92. private bool m_dumpAssetsToFile = false;
  93. private string m_regionName;
  94. public BunchOfCaps(Scene scene, Caps caps)
  95. {
  96. m_Scene = scene;
  97. m_HostCapsObj = caps;
  98. IConfigSource config = m_Scene.Config;
  99. if (config != null)
  100. {
  101. IConfig sconfig = config.Configs["Startup"];
  102. if (sconfig != null)
  103. m_persistBakedTextures = sconfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
  104. }
  105. m_assetService = m_Scene.AssetService;
  106. m_regionName = m_Scene.RegionInfo.RegionName;
  107. RegisterHandlers();
  108. AddNewInventoryItem = m_Scene.AddUploadedInventoryItem;
  109. ItemUpdatedCall = m_Scene.CapsUpdateInventoryItemAsset;
  110. TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset;
  111. CAPSFetchInventoryDescendents = m_Scene.HandleFetchInventoryDescendentsCAPS;
  112. GetClient = m_Scene.SceneContents.GetControllingClient;
  113. }
  114. /// <summary>
  115. /// Register a bunch of CAPS http service handlers
  116. /// </summary>
  117. public void RegisterHandlers()
  118. {
  119. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  120. RegisterRegionServiceHandlers(capsBase);
  121. RegisterInventoryServiceHandlers(capsBase);
  122. }
  123. public void RegisterRegionServiceHandlers(string capsBase)
  124. {
  125. try
  126. {
  127. // the root of all evil
  128. m_HostCapsObj.RegisterHandler("SEED", new RestStreamHandler("POST", capsBase + m_requestPath, SeedCapRequest));
  129. m_log.DebugFormat(
  130. "[CAPS]: Registered seed capability {0} for {1}", capsBase + m_requestPath, m_HostCapsObj.AgentID);
  131. //m_capsHandlers["MapLayer"] =
  132. // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
  133. // capsBase + m_mapLayerPath,
  134. // GetMapLayer);
  135. IRequestHandler req = new RestStreamHandler("POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
  136. m_HostCapsObj.RegisterHandler("UpdateScriptTaskInventory", req);
  137. m_HostCapsObj.RegisterHandler("UpdateScriptTask", req);
  138. }
  139. catch (Exception e)
  140. {
  141. m_log.Error("[CAPS]: " + e.ToString());
  142. }
  143. }
  144. public void RegisterInventoryServiceHandlers(string capsBase)
  145. {
  146. try
  147. {
  148. // I don't think this one works...
  149. m_HostCapsObj.RegisterHandler("NewFileAgentInventory", new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>("POST",
  150. capsBase + m_newInventory,
  151. NewAgentInventoryRequest));
  152. IRequestHandler req = new RestStreamHandler("POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory);
  153. m_HostCapsObj.RegisterHandler("UpdateNotecardAgentInventory", req);
  154. m_HostCapsObj.RegisterHandler("UpdateScriptAgentInventory", req);
  155. m_HostCapsObj.RegisterHandler("UpdateScriptAgent", req);
  156. // As of RC 1.22.9 of the Linden client this is
  157. // supported
  158. //m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
  159. // justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
  160. // subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
  161. // enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
  162. // but when I went on the Linden grid, the
  163. // simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
  164. // the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
  165. //
  166. // This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
  167. // we will be
  168. // able to get the data we need to implement the necessary part of the protocol to fix the issue above.
  169. // m_capsHandlers["FetchInventoryDescendents"] =
  170. // new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
  171. // m_capsHandlers["FetchInventoryDescendents"] =
  172. // new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
  173. // capsBase + m_fetchInventory,
  174. // FetchInventory));
  175. // m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
  176. // capsBase + m_requestTexture,
  177. // RequestTexture);
  178. }
  179. catch (Exception e)
  180. {
  181. m_log.Error("[CAPS]: " + e.ToString());
  182. }
  183. }
  184. /// <summary>
  185. /// Construct a client response detailing all the capabilities this server can provide.
  186. /// </summary>
  187. /// <param name="request"></param>
  188. /// <param name="path"></param>
  189. /// <param name="param"></param>
  190. /// <param name="httpRequest">HTTP request header object</param>
  191. /// <param name="httpResponse">HTTP response header object</param>
  192. /// <returns></returns>
  193. public string SeedCapRequest(string request, string path, string param,
  194. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  195. {
  196. // m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName);
  197. if (!m_Scene.CheckClient(m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint))
  198. {
  199. m_log.DebugFormat("[CAPS]: Unauthorized CAPS client");
  200. return string.Empty;
  201. }
  202. Hashtable caps = m_HostCapsObj.CapsHandlers.GetCapsDetails(true);
  203. // Add the external too
  204. foreach (KeyValuePair<string, string> kvp in m_HostCapsObj.ExternalCapsHandlers)
  205. caps[kvp.Key] = kvp.Value;
  206. string result = LLSDHelpers.SerialiseLLSDReply(caps);
  207. //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
  208. return result;
  209. }
  210. /// <summary>
  211. /// Called by the script task update handler. Provides a URL to which the client can upload a new asset.
  212. /// </summary>
  213. /// <param name="request"></param>
  214. /// <param name="path"></param>
  215. /// <param name="param"></param>
  216. /// <param name="httpRequest">HTTP request header object</param>
  217. /// <param name="httpResponse">HTTP response header object</param>
  218. /// <returns></returns>
  219. public string ScriptTaskInventory(string request, string path, string param,
  220. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  221. {
  222. try
  223. {
  224. m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
  225. //m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
  226. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  227. LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
  228. LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
  229. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  230. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  231. TaskInventoryScriptUpdater uploader =
  232. new TaskInventoryScriptUpdater(
  233. llsdUpdateRequest.item_id,
  234. llsdUpdateRequest.task_id,
  235. llsdUpdateRequest.is_script_running,
  236. capsBase + uploaderPath,
  237. m_HostCapsObj.HttpListener,
  238. m_dumpAssetsToFile);
  239. uploader.OnUpLoad += TaskScriptUpdated;
  240. m_HostCapsObj.HttpListener.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  241. string protocol = "http://";
  242. if (m_HostCapsObj.SSLCaps)
  243. protocol = "https://";
  244. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  245. uploaderPath;
  246. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  247. uploadResponse.uploader = uploaderURL;
  248. uploadResponse.state = "upload";
  249. // m_log.InfoFormat("[CAPS]: " +
  250. // "ScriptTaskInventory response: {0}",
  251. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  252. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  253. }
  254. catch (Exception e)
  255. {
  256. m_log.Error("[CAPS]: " + e.ToString());
  257. }
  258. return null;
  259. }
  260. /// <summary>
  261. /// Called when new asset data for an agent inventory item update has been uploaded.
  262. /// </summary>
  263. /// <param name="itemID">Item to update</param>
  264. /// <param name="primID">Prim containing item to update</param>
  265. /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
  266. /// <param name="data">New asset data</param>
  267. public void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors)
  268. {
  269. if (TaskScriptUpdatedCall != null)
  270. {
  271. ArrayList e = TaskScriptUpdatedCall(m_HostCapsObj.AgentID, itemID, primID, isScriptRunning, data);
  272. foreach (Object item in e)
  273. errors.Add(item);
  274. }
  275. }
  276. /// <summary>
  277. /// Called when new asset data for an agent inventory item update has been uploaded.
  278. /// </summary>
  279. /// <param name="itemID">Item to update</param>
  280. /// <param name="data">New asset data</param>
  281. /// <returns></returns>
  282. public UUID ItemUpdated(UUID itemID, byte[] data)
  283. {
  284. if (ItemUpdatedCall != null)
  285. {
  286. return ItemUpdatedCall(m_HostCapsObj.AgentID, itemID, data);
  287. }
  288. return UUID.Zero;
  289. }
  290. /// <summary>
  291. ///
  292. /// </summary>
  293. /// <param name="llsdRequest"></param>
  294. /// <returns></returns>
  295. public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
  296. {
  297. //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
  298. //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
  299. if (llsdRequest.asset_type == "texture" ||
  300. llsdRequest.asset_type == "animation" ||
  301. llsdRequest.asset_type == "sound")
  302. {
  303. IClientAPI client = null;
  304. IScene scene = null;
  305. if (GetClient != null)
  306. {
  307. client = GetClient(m_HostCapsObj.AgentID);
  308. scene = client.Scene;
  309. IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>();
  310. if (mm != null)
  311. {
  312. if (!mm.UploadCovered(client, mm.UploadCharge))
  313. {
  314. if (client != null)
  315. client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
  316. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  317. errorResponse.uploader = "";
  318. errorResponse.state = "error";
  319. return errorResponse;
  320. }
  321. }
  322. }
  323. }
  324. string assetName = llsdRequest.name;
  325. string assetDes = llsdRequest.description;
  326. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  327. UUID newAsset = UUID.Random();
  328. UUID newInvItem = UUID.Random();
  329. UUID parentFolder = llsdRequest.folder_id;
  330. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  331. AssetUploader uploader =
  332. new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
  333. llsdRequest.asset_type, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  334. m_HostCapsObj.HttpListener.AddStreamHandler(
  335. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  336. string protocol = "http://";
  337. if (m_HostCapsObj.SSLCaps)
  338. protocol = "https://";
  339. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  340. uploaderPath;
  341. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  342. uploadResponse.uploader = uploaderURL;
  343. uploadResponse.state = "upload";
  344. uploader.OnUpLoad += UploadCompleteHandler;
  345. return uploadResponse;
  346. }
  347. /// <summary>
  348. /// Convert raw uploaded data into the appropriate asset and item.
  349. /// </summary>
  350. /// <param name="assetID"></param>
  351. /// <param name="inventoryItem"></param>
  352. /// <param name="data"></param>
  353. public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
  354. UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
  355. string assetType)
  356. {
  357. m_log.DebugFormat(
  358. "Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
  359. assetID, inventoryItem, inventoryType, assetType);
  360. sbyte assType = 0;
  361. sbyte inType = 0;
  362. if (inventoryType == "sound")
  363. {
  364. inType = 1;
  365. assType = 1;
  366. }
  367. else if (inventoryType == "animation")
  368. {
  369. inType = 19;
  370. assType = 20;
  371. }
  372. else if (inventoryType == "wearable")
  373. {
  374. inType = 18;
  375. switch (assetType)
  376. {
  377. case "bodypart":
  378. assType = 13;
  379. break;
  380. case "clothing":
  381. assType = 5;
  382. break;
  383. }
  384. }
  385. else if (inventoryType == "object")
  386. {
  387. inType = (sbyte)InventoryType.Object;
  388. assType = (sbyte)AssetType.Object;
  389. List<Vector3> positions = new List<Vector3>();
  390. List<Quaternion> rotations = new List<Quaternion>();
  391. OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  392. OSDArray instance_list = (OSDArray)request["instance_list"];
  393. OSDArray mesh_list = (OSDArray)request["mesh_list"];
  394. OSDArray texture_list = (OSDArray)request["texture_list"];
  395. SceneObjectGroup grp = null;
  396. List<UUID> textures = new List<UUID>();
  397. for (int i = 0; i < texture_list.Count; i++)
  398. {
  399. AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
  400. textureAsset.Data = texture_list[i].AsBinary();
  401. m_assetService.Store(textureAsset);
  402. textures.Add(textureAsset.FullID);
  403. }
  404. for (int i = 0; i < mesh_list.Count; i++)
  405. {
  406. PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
  407. Primitive.TextureEntry textureEntry
  408. = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
  409. OSDMap inner_instance_list = (OSDMap)instance_list[i];
  410. OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
  411. for (uint face = 0; face < face_list.Count; face++)
  412. {
  413. OSDMap faceMap = (OSDMap)face_list[(int)face];
  414. Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
  415. if(faceMap.ContainsKey("fullbright"))
  416. f.Fullbright = faceMap["fullbright"].AsBoolean();
  417. if (faceMap.ContainsKey ("diffuse_color"))
  418. f.RGBA = faceMap["diffuse_color"].AsColor4();
  419. int textureNum = faceMap["image"].AsInteger();
  420. float imagerot = faceMap["imagerot"].AsInteger();
  421. float offsets = (float)faceMap["offsets"].AsReal();
  422. float offsett = (float)faceMap["offsett"].AsReal();
  423. float scales = (float)faceMap["scales"].AsReal();
  424. float scalet = (float)faceMap["scalet"].AsReal();
  425. if(imagerot != 0)
  426. f.Rotation = imagerot;
  427. if(offsets != 0)
  428. f.OffsetU = offsets;
  429. if (offsett != 0)
  430. f.OffsetV = offsett;
  431. if (scales != 0)
  432. f.RepeatU = scales;
  433. if (scalet != 0)
  434. f.RepeatV = scalet;
  435. if (textures.Count > textureNum)
  436. f.TextureID = textures[textureNum];
  437. else
  438. f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
  439. textureEntry.FaceTextures[face] = f;
  440. }
  441. pbs.TextureEntry = textureEntry.GetBytes();
  442. AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
  443. meshAsset.Data = mesh_list[i].AsBinary();
  444. m_assetService.Store(meshAsset);
  445. pbs.SculptEntry = true;
  446. pbs.SculptTexture = meshAsset.FullID;
  447. pbs.SculptType = (byte)SculptType.Mesh;
  448. pbs.SculptData = meshAsset.Data;
  449. Vector3 position = inner_instance_list["position"].AsVector3();
  450. Vector3 scale = inner_instance_list["scale"].AsVector3();
  451. Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
  452. // no longer used - begin ------------------------
  453. // int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
  454. // int material = inner_instance_list["material"].AsInteger();
  455. // int mesh = inner_instance_list["mesh"].AsInteger();
  456. // OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
  457. // int base_mask = permissions["base_mask"].AsInteger();
  458. // int everyone_mask = permissions["everyone_mask"].AsInteger();
  459. // UUID creator_id = permissions["creator_id"].AsUUID();
  460. // UUID group_id = permissions["group_id"].AsUUID();
  461. // int group_mask = permissions["group_mask"].AsInteger();
  462. // bool is_owner_group = permissions["is_owner_group"].AsBoolean();
  463. // UUID last_owner_id = permissions["last_owner_id"].AsUUID();
  464. // int next_owner_mask = permissions["next_owner_mask"].AsInteger();
  465. // UUID owner_id = permissions["owner_id"].AsUUID();
  466. // int owner_mask = permissions["owner_mask"].AsInteger();
  467. // no longer used - end ------------------------
  468. UUID owner_id = m_HostCapsObj.AgentID;
  469. SceneObjectPart prim
  470. = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);
  471. prim.Scale = scale;
  472. prim.OffsetPosition = position;
  473. rotations.Add(rotation);
  474. positions.Add(position);
  475. prim.UUID = UUID.Random();
  476. prim.CreatorID = owner_id;
  477. prim.OwnerID = owner_id;
  478. prim.GroupID = UUID.Zero;
  479. prim.LastOwnerID = prim.OwnerID;
  480. prim.CreationDate = Util.UnixTimeSinceEpoch();
  481. prim.Name = assetName;
  482. prim.Description = "";
  483. // prim.BaseMask = (uint)base_mask;
  484. // prim.EveryoneMask = (uint)everyone_mask;
  485. // prim.GroupMask = (uint)group_mask;
  486. // prim.NextOwnerMask = (uint)next_owner_mask;
  487. // prim.OwnerMask = (uint)owner_mask;
  488. if (grp == null)
  489. grp = new SceneObjectGroup(prim);
  490. else
  491. grp.AddPart(prim);
  492. }
  493. // Fix first link number
  494. if (grp.Parts.Length > 1)
  495. grp.RootPart.LinkNum++;
  496. Vector3 rootPos = positions[0];
  497. grp.AbsolutePosition = rootPos;
  498. for (int i = 0; i < positions.Count; i++)
  499. {
  500. Vector3 offset = positions[i] - rootPos;
  501. grp.Parts[i].OffsetPosition = offset;
  502. }
  503. for (int i = 0; i < rotations.Count; i++)
  504. {
  505. if (i != 0)
  506. grp.Parts[i].RotationOffset = rotations[i];
  507. }
  508. grp.UpdateGroupRotationR(rotations[0]);
  509. data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
  510. }
  511. AssetBase asset;
  512. asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString());
  513. asset.Data = data;
  514. if (AddNewAsset != null)
  515. AddNewAsset(asset);
  516. else if (m_assetService != null)
  517. m_assetService.Store(asset);
  518. InventoryItemBase item = new InventoryItemBase();
  519. item.Owner = m_HostCapsObj.AgentID;
  520. item.CreatorId = m_HostCapsObj.AgentID.ToString();
  521. item.CreatorData = String.Empty;
  522. item.ID = inventoryItem;
  523. item.AssetID = asset.FullID;
  524. item.Description = assetDescription;
  525. item.Name = assetName;
  526. item.AssetType = assType;
  527. item.InvType = inType;
  528. item.Folder = parentFolder;
  529. item.CurrentPermissions = (uint)PermissionMask.All;
  530. item.BasePermissions = (uint)PermissionMask.All;
  531. item.EveryOnePermissions = 0;
  532. item.NextPermissions = (uint)PermissionMask.All;
  533. item.CreationDate = Util.UnixTimeSinceEpoch();
  534. if (AddNewInventoryItem != null)
  535. {
  536. AddNewInventoryItem(m_HostCapsObj.AgentID, item);
  537. }
  538. }
  539. /// <summary>
  540. ///
  541. /// </summary>
  542. /// <param name="mapReq"></param>
  543. /// <returns></returns>
  544. public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
  545. {
  546. m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
  547. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  548. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  549. return mapResponse;
  550. }
  551. /// <summary>
  552. ///
  553. /// </summary>
  554. /// <returns></returns>
  555. protected static OSDMapLayer GetOSDMapLayerResponse()
  556. {
  557. OSDMapLayer mapLayer = new OSDMapLayer();
  558. mapLayer.Right = 5000;
  559. mapLayer.Top = 5000;
  560. mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
  561. return mapLayer;
  562. }
  563. /// <summary>
  564. ///
  565. /// </summary>
  566. /// <param name="request"></param>
  567. /// <param name="path"></param>
  568. /// <param name="param"></param>
  569. /// <returns></returns>
  570. public string RequestTexture(string request, string path, string param)
  571. {
  572. m_log.Debug("texture request " + request);
  573. // Needs implementing (added to remove compiler warning)
  574. return String.Empty;
  575. }
  576. /// <summary>
  577. /// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
  578. /// </summary>
  579. /// <param name="request"></param>
  580. /// <param name="path"></param>
  581. /// <param name="param"></param>
  582. /// <returns></returns>
  583. public string NoteCardAgentInventory(string request, string path, string param,
  584. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  585. {
  586. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
  587. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
  588. //OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
  589. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  590. LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
  591. LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
  592. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  593. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  594. ItemUpdater uploader =
  595. new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  596. uploader.OnUpLoad += ItemUpdated;
  597. m_HostCapsObj.HttpListener.AddStreamHandler(
  598. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  599. string protocol = "http://";
  600. if (m_HostCapsObj.SSLCaps)
  601. protocol = "https://";
  602. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  603. uploaderPath;
  604. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  605. uploadResponse.uploader = uploaderURL;
  606. uploadResponse.state = "upload";
  607. // m_log.InfoFormat("[CAPS]: " +
  608. // "NoteCardAgentInventory response: {0}",
  609. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  610. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  611. }
  612. }
  613. public class AssetUploader
  614. {
  615. public event UpLoadedAsset OnUpLoad;
  616. private UpLoadedAsset handlerUpLoad = null;
  617. private string uploaderPath = String.Empty;
  618. private UUID newAssetID;
  619. private UUID inventoryItemID;
  620. private UUID parentFolder;
  621. private IHttpServer httpListener;
  622. private bool m_dumpAssetsToFile;
  623. private string m_assetName = String.Empty;
  624. private string m_assetDes = String.Empty;
  625. private string m_invType = String.Empty;
  626. private string m_assetType = String.Empty;
  627. public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
  628. UUID parentFolderID, string invType, string assetType, string path,
  629. IHttpServer httpServer, bool dumpAssetsToFile)
  630. {
  631. m_assetName = assetName;
  632. m_assetDes = description;
  633. newAssetID = assetID;
  634. inventoryItemID = inventoryItem;
  635. uploaderPath = path;
  636. httpListener = httpServer;
  637. parentFolder = parentFolderID;
  638. m_assetType = assetType;
  639. m_invType = invType;
  640. m_dumpAssetsToFile = dumpAssetsToFile;
  641. }
  642. /// <summary>
  643. /// Handle raw asset upload data via the capability.
  644. /// </summary>
  645. /// <param name="data"></param>
  646. /// <param name="path"></param>
  647. /// <param name="param"></param>
  648. /// <returns></returns>
  649. public string uploaderCaps(byte[] data, string path, string param)
  650. {
  651. UUID inv = inventoryItemID;
  652. string res = String.Empty;
  653. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  654. uploadComplete.new_asset = newAssetID.ToString();
  655. uploadComplete.new_inventory_item = inv;
  656. uploadComplete.state = "complete";
  657. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  658. httpListener.RemoveStreamHandler("POST", uploaderPath);
  659. // TODO: probably make this a better set of extensions here
  660. string extension = ".jp2";
  661. if (m_invType != "image")
  662. {
  663. extension = ".dat";
  664. }
  665. if (m_dumpAssetsToFile)
  666. {
  667. SaveAssetToFile(m_assetName + extension, data);
  668. }
  669. handlerUpLoad = OnUpLoad;
  670. if (handlerUpLoad != null)
  671. {
  672. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
  673. }
  674. return res;
  675. }
  676. ///Left this in and commented in case there are unforseen issues
  677. //private void SaveAssetToFile(string filename, byte[] data)
  678. //{
  679. // FileStream fs = File.Create(filename);
  680. // BinaryWriter bw = new BinaryWriter(fs);
  681. // bw.Write(data);
  682. // bw.Close();
  683. // fs.Close();
  684. //}
  685. private static void SaveAssetToFile(string filename, byte[] data)
  686. {
  687. string assetPath = "UserAssets";
  688. if (!Directory.Exists(assetPath))
  689. {
  690. Directory.CreateDirectory(assetPath);
  691. }
  692. FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
  693. BinaryWriter bw = new BinaryWriter(fs);
  694. bw.Write(data);
  695. bw.Close();
  696. fs.Close();
  697. }
  698. }
  699. /// <summary>
  700. /// This class is a callback invoked when a client sends asset data to
  701. /// an agent inventory notecard update url
  702. /// </summary>
  703. public class ItemUpdater
  704. {
  705. public event UpdateItem OnUpLoad;
  706. private UpdateItem handlerUpdateItem = null;
  707. private string uploaderPath = String.Empty;
  708. private UUID inventoryItemID;
  709. private IHttpServer httpListener;
  710. private bool m_dumpAssetToFile;
  711. public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer, bool dumpAssetToFile)
  712. {
  713. m_dumpAssetToFile = dumpAssetToFile;
  714. inventoryItemID = inventoryItem;
  715. uploaderPath = path;
  716. httpListener = httpServer;
  717. }
  718. /// <summary>
  719. /// Handle raw uploaded asset data.
  720. /// </summary>
  721. /// <param name="data"></param>
  722. /// <param name="path"></param>
  723. /// <param name="param"></param>
  724. /// <returns></returns>
  725. public string uploaderCaps(byte[] data, string path, string param)
  726. {
  727. UUID inv = inventoryItemID;
  728. string res = String.Empty;
  729. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  730. UUID assetID = UUID.Zero;
  731. handlerUpdateItem = OnUpLoad;
  732. if (handlerUpdateItem != null)
  733. {
  734. assetID = handlerUpdateItem(inv, data);
  735. }
  736. uploadComplete.new_asset = assetID.ToString();
  737. uploadComplete.new_inventory_item = inv;
  738. uploadComplete.state = "complete";
  739. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  740. httpListener.RemoveStreamHandler("POST", uploaderPath);
  741. if (m_dumpAssetToFile)
  742. {
  743. SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  744. }
  745. return res;
  746. }
  747. ///Left this in and commented in case there are unforseen issues
  748. //private void SaveAssetToFile(string filename, byte[] data)
  749. //{
  750. // FileStream fs = File.Create(filename);
  751. // BinaryWriter bw = new BinaryWriter(fs);
  752. // bw.Write(data);
  753. // bw.Close();
  754. // fs.Close();
  755. //}
  756. private static void SaveAssetToFile(string filename, byte[] data)
  757. {
  758. string assetPath = "UserAssets";
  759. if (!Directory.Exists(assetPath))
  760. {
  761. Directory.CreateDirectory(assetPath);
  762. }
  763. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  764. BinaryWriter bw = new BinaryWriter(fs);
  765. bw.Write(data);
  766. bw.Close();
  767. fs.Close();
  768. }
  769. }
  770. /// <summary>
  771. /// This class is a callback invoked when a client sends asset data to
  772. /// a task inventory script update url
  773. /// </summary>
  774. public class TaskInventoryScriptUpdater
  775. {
  776. private static readonly ILog m_log =
  777. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  778. public event UpdateTaskScript OnUpLoad;
  779. private UpdateTaskScript handlerUpdateTaskScript = null;
  780. private string uploaderPath = String.Empty;
  781. private UUID inventoryItemID;
  782. private UUID primID;
  783. private bool isScriptRunning;
  784. private IHttpServer httpListener;
  785. private bool m_dumpAssetToFile;
  786. public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
  787. string path, IHttpServer httpServer, bool dumpAssetToFile)
  788. {
  789. m_dumpAssetToFile = dumpAssetToFile;
  790. this.inventoryItemID = inventoryItemID;
  791. this.primID = primID;
  792. // This comes in over the packet as an integer, but actually appears to be treated as a bool
  793. this.isScriptRunning = (0 == isScriptRunning ? false : true);
  794. uploaderPath = path;
  795. httpListener = httpServer;
  796. }
  797. /// <summary>
  798. ///
  799. /// </summary>
  800. /// <param name="data"></param>
  801. /// <param name="path"></param>
  802. /// <param name="param"></param>
  803. /// <returns></returns>
  804. public string uploaderCaps(byte[] data, string path, string param)
  805. {
  806. try
  807. {
  808. // m_log.InfoFormat("[CAPS]: " +
  809. // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
  810. // data, path, param));
  811. string res = String.Empty;
  812. LLSDTaskScriptUploadComplete uploadComplete = new LLSDTaskScriptUploadComplete();
  813. ArrayList errors = new ArrayList();
  814. handlerUpdateTaskScript = OnUpLoad;
  815. if (handlerUpdateTaskScript != null)
  816. {
  817. handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data, ref errors);
  818. }
  819. uploadComplete.new_asset = inventoryItemID;
  820. uploadComplete.compiled = errors.Count > 0 ? false : true;
  821. uploadComplete.state = "complete";
  822. uploadComplete.errors = new OpenSim.Framework.Capabilities.OSDArray();
  823. uploadComplete.errors.Array = errors;
  824. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  825. httpListener.RemoveStreamHandler("POST", uploaderPath);
  826. if (m_dumpAssetToFile)
  827. {
  828. SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  829. }
  830. // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
  831. return res;
  832. }
  833. catch (Exception e)
  834. {
  835. m_log.Error("[CAPS]: " + e.ToString());
  836. }
  837. // XXX Maybe this should be some meaningful error packet
  838. return null;
  839. }
  840. ///Left this in and commented in case there are unforseen issues
  841. //private void SaveAssetToFile(string filename, byte[] data)
  842. //{
  843. // FileStream fs = File.Create(filename);
  844. // BinaryWriter bw = new BinaryWriter(fs);
  845. // bw.Write(data);
  846. // bw.Close();
  847. // fs.Close();
  848. //}
  849. private static void SaveAssetToFile(string filename, byte[] data)
  850. {
  851. string assetPath = "UserAssets";
  852. if (!Directory.Exists(assetPath))
  853. {
  854. Directory.CreateDirectory(assetPath);
  855. }
  856. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  857. BinaryWriter bw = new BinaryWriter(fs);
  858. bw.Write(data);
  859. bw.Close();
  860. fs.Close();
  861. }
  862. }
  863. }