BunchOfCaps.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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_copyFromNotecardPath = "0007/";
  82. // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
  83. // These are callbacks which will be setup by the scene so that we can update scene data when we
  84. // receive capability calls
  85. public NewInventoryItem AddNewInventoryItem = null;
  86. public NewAsset AddNewAsset = null;
  87. public ItemUpdatedCallback ItemUpdatedCall = null;
  88. public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
  89. public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
  90. public GetClientDelegate GetClient = null;
  91. private bool m_persistBakedTextures = false;
  92. private IAssetService m_assetService;
  93. private bool m_dumpAssetsToFile = false;
  94. private string m_regionName;
  95. public BunchOfCaps(Scene scene, Caps caps)
  96. {
  97. m_Scene = scene;
  98. m_HostCapsObj = caps;
  99. IConfigSource config = m_Scene.Config;
  100. if (config != null)
  101. {
  102. IConfig sconfig = config.Configs["Startup"];
  103. if (sconfig != null)
  104. m_persistBakedTextures = sconfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
  105. }
  106. m_assetService = m_Scene.AssetService;
  107. m_regionName = m_Scene.RegionInfo.RegionName;
  108. RegisterHandlers();
  109. AddNewInventoryItem = m_Scene.AddUploadedInventoryItem;
  110. ItemUpdatedCall = m_Scene.CapsUpdateInventoryItemAsset;
  111. TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset;
  112. GetClient = m_Scene.SceneGraph.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. m_HostCapsObj.RegisterHandler("CopyInventoryFromNotecard", new RestStreamHandler("POST", capsBase + m_copyFromNotecardPath, CopyInventoryFromNotecard));
  157. // As of RC 1.22.9 of the Linden client this is
  158. // supported
  159. //m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
  160. // justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
  161. // subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
  162. // enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
  163. // but when I went on the Linden grid, the
  164. // simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
  165. // the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
  166. //
  167. // This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
  168. // we will be
  169. // able to get the data we need to implement the necessary part of the protocol to fix the issue above.
  170. // m_capsHandlers["FetchInventoryDescendents"] =
  171. // new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
  172. // m_capsHandlers["FetchInventoryDescendents"] =
  173. // new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
  174. // capsBase + m_fetchInventory,
  175. // FetchInventory));
  176. // m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
  177. // capsBase + m_requestTexture,
  178. // RequestTexture);
  179. }
  180. catch (Exception e)
  181. {
  182. m_log.Error("[CAPS]: " + e.ToString());
  183. }
  184. }
  185. /// <summary>
  186. /// Construct a client response detailing all the capabilities this server can provide.
  187. /// </summary>
  188. /// <param name="request"></param>
  189. /// <param name="path"></param>
  190. /// <param name="param"></param>
  191. /// <param name="httpRequest">HTTP request header object</param>
  192. /// <param name="httpResponse">HTTP response header object</param>
  193. /// <returns></returns>
  194. public string SeedCapRequest(string request, string path, string param,
  195. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  196. {
  197. // m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName);
  198. if (!m_Scene.CheckClient(m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint))
  199. {
  200. m_log.DebugFormat("[CAPS]: Unauthorized CAPS client");
  201. return string.Empty;
  202. }
  203. Hashtable caps = m_HostCapsObj.CapsHandlers.GetCapsDetails(true);
  204. // Add the external too
  205. foreach (KeyValuePair<string, string> kvp in m_HostCapsObj.ExternalCapsHandlers)
  206. caps[kvp.Key] = kvp.Value;
  207. string result = LLSDHelpers.SerialiseLLSDReply(caps);
  208. //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
  209. return result;
  210. }
  211. /// <summary>
  212. /// Called by the script task update handler. Provides a URL to which the client can upload a new asset.
  213. /// </summary>
  214. /// <param name="request"></param>
  215. /// <param name="path"></param>
  216. /// <param name="param"></param>
  217. /// <param name="httpRequest">HTTP request header object</param>
  218. /// <param name="httpResponse">HTTP response header object</param>
  219. /// <returns></returns>
  220. public string ScriptTaskInventory(string request, string path, string param,
  221. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  222. {
  223. try
  224. {
  225. m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
  226. //m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
  227. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  228. LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
  229. LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
  230. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  231. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  232. TaskInventoryScriptUpdater uploader =
  233. new TaskInventoryScriptUpdater(
  234. llsdUpdateRequest.item_id,
  235. llsdUpdateRequest.task_id,
  236. llsdUpdateRequest.is_script_running,
  237. capsBase + uploaderPath,
  238. m_HostCapsObj.HttpListener,
  239. m_dumpAssetsToFile);
  240. uploader.OnUpLoad += TaskScriptUpdated;
  241. m_HostCapsObj.HttpListener.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  242. string protocol = "http://";
  243. if (m_HostCapsObj.SSLCaps)
  244. protocol = "https://";
  245. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  246. uploaderPath;
  247. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  248. uploadResponse.uploader = uploaderURL;
  249. uploadResponse.state = "upload";
  250. // m_log.InfoFormat("[CAPS]: " +
  251. // "ScriptTaskInventory response: {0}",
  252. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  253. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  254. }
  255. catch (Exception e)
  256. {
  257. m_log.Error("[CAPS]: " + e.ToString());
  258. }
  259. return null;
  260. }
  261. /// <summary>
  262. /// Called when new asset data for an agent inventory item update has been uploaded.
  263. /// </summary>
  264. /// <param name="itemID">Item to update</param>
  265. /// <param name="primID">Prim containing item to update</param>
  266. /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
  267. /// <param name="data">New asset data</param>
  268. public void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors)
  269. {
  270. if (TaskScriptUpdatedCall != null)
  271. {
  272. ArrayList e = TaskScriptUpdatedCall(m_HostCapsObj.AgentID, itemID, primID, isScriptRunning, data);
  273. foreach (Object item in e)
  274. errors.Add(item);
  275. }
  276. }
  277. /// <summary>
  278. /// Called when new asset data for an agent inventory item update has been uploaded.
  279. /// </summary>
  280. /// <param name="itemID">Item to update</param>
  281. /// <param name="data">New asset data</param>
  282. /// <returns></returns>
  283. public UUID ItemUpdated(UUID itemID, byte[] data)
  284. {
  285. if (ItemUpdatedCall != null)
  286. {
  287. return ItemUpdatedCall(m_HostCapsObj.AgentID, itemID, data);
  288. }
  289. return UUID.Zero;
  290. }
  291. /// <summary>
  292. ///
  293. /// </summary>
  294. /// <param name="llsdRequest"></param>
  295. /// <returns></returns>
  296. public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
  297. {
  298. //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
  299. //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
  300. if (llsdRequest.asset_type == "texture" ||
  301. llsdRequest.asset_type == "animation" ||
  302. llsdRequest.asset_type == "sound")
  303. {
  304. IClientAPI client = null;
  305. IScene scene = null;
  306. if (GetClient != null)
  307. {
  308. client = GetClient(m_HostCapsObj.AgentID);
  309. scene = client.Scene;
  310. IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>();
  311. if (mm != null)
  312. {
  313. if (!mm.UploadCovered(client.AgentId, mm.UploadCharge))
  314. {
  315. if (client != null)
  316. client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
  317. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  318. errorResponse.uploader = "";
  319. errorResponse.state = "error";
  320. return errorResponse;
  321. }
  322. }
  323. }
  324. }
  325. string assetName = llsdRequest.name;
  326. string assetDes = llsdRequest.description;
  327. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  328. UUID newAsset = UUID.Random();
  329. UUID newInvItem = UUID.Random();
  330. UUID parentFolder = llsdRequest.folder_id;
  331. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  332. AssetUploader uploader =
  333. new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
  334. llsdRequest.asset_type, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  335. m_HostCapsObj.HttpListener.AddStreamHandler(
  336. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  337. string protocol = "http://";
  338. if (m_HostCapsObj.SSLCaps)
  339. protocol = "https://";
  340. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  341. uploaderPath;
  342. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  343. uploadResponse.uploader = uploaderURL;
  344. uploadResponse.state = "upload";
  345. uploader.OnUpLoad += UploadCompleteHandler;
  346. return uploadResponse;
  347. }
  348. /// <summary>
  349. /// Convert raw uploaded data into the appropriate asset and item.
  350. /// </summary>
  351. /// <param name="assetID"></param>
  352. /// <param name="inventoryItem"></param>
  353. /// <param name="data"></param>
  354. public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
  355. UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
  356. string assetType)
  357. {
  358. m_log.DebugFormat(
  359. "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
  360. assetID, inventoryItem, inventoryType, assetType);
  361. sbyte assType = 0;
  362. sbyte inType = 0;
  363. if (inventoryType == "sound")
  364. {
  365. inType = 1;
  366. assType = 1;
  367. }
  368. else if (inventoryType == "animation")
  369. {
  370. inType = 19;
  371. assType = 20;
  372. }
  373. else if (inventoryType == "wearable")
  374. {
  375. inType = 18;
  376. switch (assetType)
  377. {
  378. case "bodypart":
  379. assType = 13;
  380. break;
  381. case "clothing":
  382. assType = 5;
  383. break;
  384. }
  385. }
  386. else if (inventoryType == "object")
  387. {
  388. inType = (sbyte)InventoryType.Object;
  389. assType = (sbyte)AssetType.Object;
  390. List<Vector3> positions = new List<Vector3>();
  391. List<Quaternion> rotations = new List<Quaternion>();
  392. OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  393. OSDArray instance_list = (OSDArray)request["instance_list"];
  394. OSDArray mesh_list = (OSDArray)request["mesh_list"];
  395. OSDArray texture_list = (OSDArray)request["texture_list"];
  396. SceneObjectGroup grp = null;
  397. List<UUID> textures = new List<UUID>();
  398. for (int i = 0; i < texture_list.Count; i++)
  399. {
  400. AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
  401. textureAsset.Data = texture_list[i].AsBinary();
  402. m_assetService.Store(textureAsset);
  403. textures.Add(textureAsset.FullID);
  404. }
  405. for (int i = 0; i < mesh_list.Count; i++)
  406. {
  407. PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
  408. Primitive.TextureEntry textureEntry
  409. = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
  410. OSDMap inner_instance_list = (OSDMap)instance_list[i];
  411. OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
  412. for (uint face = 0; face < face_list.Count; face++)
  413. {
  414. OSDMap faceMap = (OSDMap)face_list[(int)face];
  415. Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
  416. if(faceMap.ContainsKey("fullbright"))
  417. f.Fullbright = faceMap["fullbright"].AsBoolean();
  418. if (faceMap.ContainsKey ("diffuse_color"))
  419. f.RGBA = faceMap["diffuse_color"].AsColor4();
  420. int textureNum = faceMap["image"].AsInteger();
  421. float imagerot = faceMap["imagerot"].AsInteger();
  422. float offsets = (float)faceMap["offsets"].AsReal();
  423. float offsett = (float)faceMap["offsett"].AsReal();
  424. float scales = (float)faceMap["scales"].AsReal();
  425. float scalet = (float)faceMap["scalet"].AsReal();
  426. if(imagerot != 0)
  427. f.Rotation = imagerot;
  428. if(offsets != 0)
  429. f.OffsetU = offsets;
  430. if (offsett != 0)
  431. f.OffsetV = offsett;
  432. if (scales != 0)
  433. f.RepeatU = scales;
  434. if (scalet != 0)
  435. f.RepeatV = scalet;
  436. if (textures.Count > textureNum)
  437. f.TextureID = textures[textureNum];
  438. else
  439. f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
  440. textureEntry.FaceTextures[face] = f;
  441. }
  442. pbs.TextureEntry = textureEntry.GetBytes();
  443. AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
  444. meshAsset.Data = mesh_list[i].AsBinary();
  445. m_assetService.Store(meshAsset);
  446. pbs.SculptEntry = true;
  447. pbs.SculptTexture = meshAsset.FullID;
  448. pbs.SculptType = (byte)SculptType.Mesh;
  449. pbs.SculptData = meshAsset.Data;
  450. Vector3 position = inner_instance_list["position"].AsVector3();
  451. Vector3 scale = inner_instance_list["scale"].AsVector3();
  452. Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
  453. // no longer used - begin ------------------------
  454. // int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
  455. // int material = inner_instance_list["material"].AsInteger();
  456. // int mesh = inner_instance_list["mesh"].AsInteger();
  457. // OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
  458. // int base_mask = permissions["base_mask"].AsInteger();
  459. // int everyone_mask = permissions["everyone_mask"].AsInteger();
  460. // UUID creator_id = permissions["creator_id"].AsUUID();
  461. // UUID group_id = permissions["group_id"].AsUUID();
  462. // int group_mask = permissions["group_mask"].AsInteger();
  463. // bool is_owner_group = permissions["is_owner_group"].AsBoolean();
  464. // UUID last_owner_id = permissions["last_owner_id"].AsUUID();
  465. // int next_owner_mask = permissions["next_owner_mask"].AsInteger();
  466. // UUID owner_id = permissions["owner_id"].AsUUID();
  467. // int owner_mask = permissions["owner_mask"].AsInteger();
  468. // no longer used - end ------------------------
  469. UUID owner_id = m_HostCapsObj.AgentID;
  470. SceneObjectPart prim
  471. = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);
  472. prim.Scale = scale;
  473. prim.OffsetPosition = position;
  474. rotations.Add(rotation);
  475. positions.Add(position);
  476. prim.UUID = UUID.Random();
  477. prim.CreatorID = owner_id;
  478. prim.OwnerID = owner_id;
  479. prim.GroupID = UUID.Zero;
  480. prim.LastOwnerID = prim.OwnerID;
  481. prim.CreationDate = Util.UnixTimeSinceEpoch();
  482. prim.Name = assetName;
  483. prim.Description = "";
  484. // prim.BaseMask = (uint)base_mask;
  485. // prim.EveryoneMask = (uint)everyone_mask;
  486. // prim.GroupMask = (uint)group_mask;
  487. // prim.NextOwnerMask = (uint)next_owner_mask;
  488. // prim.OwnerMask = (uint)owner_mask;
  489. if (grp == null)
  490. grp = new SceneObjectGroup(prim);
  491. else
  492. grp.AddPart(prim);
  493. }
  494. // Fix first link number
  495. if (grp.Parts.Length > 1)
  496. grp.RootPart.LinkNum++;
  497. Vector3 rootPos = positions[0];
  498. grp.AbsolutePosition = rootPos;
  499. for (int i = 0; i < positions.Count; i++)
  500. {
  501. Vector3 offset = positions[i] - rootPos;
  502. grp.Parts[i].OffsetPosition = offset;
  503. }
  504. for (int i = 0; i < rotations.Count; i++)
  505. {
  506. if (i != 0)
  507. grp.Parts[i].RotationOffset = rotations[i];
  508. }
  509. grp.UpdateGroupRotationR(rotations[0]);
  510. data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
  511. }
  512. AssetBase asset;
  513. asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString());
  514. asset.Data = data;
  515. if (AddNewAsset != null)
  516. AddNewAsset(asset);
  517. else if (m_assetService != null)
  518. m_assetService.Store(asset);
  519. InventoryItemBase item = new InventoryItemBase();
  520. item.Owner = m_HostCapsObj.AgentID;
  521. item.CreatorId = m_HostCapsObj.AgentID.ToString();
  522. item.CreatorData = String.Empty;
  523. item.ID = inventoryItem;
  524. item.AssetID = asset.FullID;
  525. item.Description = assetDescription;
  526. item.Name = assetName;
  527. item.AssetType = assType;
  528. item.InvType = inType;
  529. item.Folder = parentFolder;
  530. // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
  531. // (owner) permissions. This becomes a problem if next permissions are changed.
  532. item.CurrentPermissions
  533. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer);
  534. item.BasePermissions = (uint)PermissionMask.All;
  535. item.EveryOnePermissions = 0;
  536. item.NextPermissions = (uint)PermissionMask.All;
  537. item.CreationDate = Util.UnixTimeSinceEpoch();
  538. if (AddNewInventoryItem != null)
  539. {
  540. AddNewInventoryItem(m_HostCapsObj.AgentID, item);
  541. }
  542. }
  543. /// <summary>
  544. ///
  545. /// </summary>
  546. /// <param name="mapReq"></param>
  547. /// <returns></returns>
  548. public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
  549. {
  550. m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
  551. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  552. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  553. return mapResponse;
  554. }
  555. /// <summary>
  556. ///
  557. /// </summary>
  558. /// <returns></returns>
  559. protected static OSDMapLayer GetOSDMapLayerResponse()
  560. {
  561. OSDMapLayer mapLayer = new OSDMapLayer();
  562. mapLayer.Right = 5000;
  563. mapLayer.Top = 5000;
  564. mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
  565. return mapLayer;
  566. }
  567. /// <summary>
  568. ///
  569. /// </summary>
  570. /// <param name="request"></param>
  571. /// <param name="path"></param>
  572. /// <param name="param"></param>
  573. /// <returns></returns>
  574. public string RequestTexture(string request, string path, string param)
  575. {
  576. m_log.Debug("texture request " + request);
  577. // Needs implementing (added to remove compiler warning)
  578. return String.Empty;
  579. }
  580. /// <summary>
  581. /// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
  582. /// </summary>
  583. /// <param name="request"></param>
  584. /// <param name="path"></param>
  585. /// <param name="param"></param>
  586. /// <returns></returns>
  587. public string NoteCardAgentInventory(string request, string path, string param,
  588. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  589. {
  590. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
  591. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
  592. //OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
  593. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  594. LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
  595. LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
  596. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  597. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  598. ItemUpdater uploader =
  599. new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  600. uploader.OnUpLoad += ItemUpdated;
  601. m_HostCapsObj.HttpListener.AddStreamHandler(
  602. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  603. string protocol = "http://";
  604. if (m_HostCapsObj.SSLCaps)
  605. protocol = "https://";
  606. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  607. uploaderPath;
  608. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  609. uploadResponse.uploader = uploaderURL;
  610. uploadResponse.state = "upload";
  611. // m_log.InfoFormat("[CAPS]: " +
  612. // "NoteCardAgentInventory response: {0}",
  613. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  614. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  615. }
  616. /// <summary>
  617. /// Called by the CopyInventoryFromNotecard caps handler.
  618. /// </summary>
  619. /// <param name="request"></param>
  620. /// <param name="path"></param>
  621. /// <param name="param"></param>
  622. public string CopyInventoryFromNotecard(string request, string path, string param,
  623. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  624. {
  625. Hashtable response = new Hashtable();
  626. response["int_response_code"] = 404;
  627. response["content_type"] = "text/plain";
  628. response["keepalive"] = false;
  629. response["str_response_string"] = "";
  630. try
  631. {
  632. OSDMap content = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  633. UUID objectID = content["object-id"].AsUUID();
  634. UUID notecardID = content["notecard-id"].AsUUID();
  635. UUID folderID = content["folder-id"].AsUUID();
  636. UUID itemID = content["item-id"].AsUUID();
  637. // m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);
  638. if (objectID != UUID.Zero)
  639. {
  640. SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
  641. if (part != null)
  642. {
  643. TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(notecardID);
  644. if (!m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, m_HostCapsObj.AgentID))
  645. {
  646. return LLSDHelpers.SerialiseLLSDReply(response);
  647. }
  648. }
  649. }
  650. InventoryItemBase item = null;
  651. InventoryItemBase copyItem = null;
  652. IClientAPI client = null;
  653. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  654. item = m_Scene.InventoryService.GetItem(new InventoryItemBase(itemID));
  655. if (item != null)
  656. {
  657. copyItem = m_Scene.GiveInventoryItem(m_HostCapsObj.AgentID, item.Owner, itemID, folderID);
  658. if (copyItem != null && client != null)
  659. {
  660. m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
  661. client.SendBulkUpdateInventory(copyItem);
  662. }
  663. }
  664. else
  665. {
  666. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard - Failed to retrieve item {0} from notecard {1}", itemID, notecardID);
  667. if (client != null)
  668. client.SendAlertMessage("Failed to retrieve item");
  669. }
  670. }
  671. catch (Exception e)
  672. {
  673. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.ToString());
  674. }
  675. response["int_response_code"] = 200;
  676. return LLSDHelpers.SerialiseLLSDReply(response);
  677. }
  678. }
  679. public class AssetUploader
  680. {
  681. public event UpLoadedAsset OnUpLoad;
  682. private UpLoadedAsset handlerUpLoad = null;
  683. private string uploaderPath = String.Empty;
  684. private UUID newAssetID;
  685. private UUID inventoryItemID;
  686. private UUID parentFolder;
  687. private IHttpServer httpListener;
  688. private bool m_dumpAssetsToFile;
  689. private string m_assetName = String.Empty;
  690. private string m_assetDes = String.Empty;
  691. private string m_invType = String.Empty;
  692. private string m_assetType = String.Empty;
  693. public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
  694. UUID parentFolderID, string invType, string assetType, string path,
  695. IHttpServer httpServer, bool dumpAssetsToFile)
  696. {
  697. m_assetName = assetName;
  698. m_assetDes = description;
  699. newAssetID = assetID;
  700. inventoryItemID = inventoryItem;
  701. uploaderPath = path;
  702. httpListener = httpServer;
  703. parentFolder = parentFolderID;
  704. m_assetType = assetType;
  705. m_invType = invType;
  706. m_dumpAssetsToFile = dumpAssetsToFile;
  707. }
  708. /// <summary>
  709. /// Handle raw asset upload data via the capability.
  710. /// </summary>
  711. /// <param name="data"></param>
  712. /// <param name="path"></param>
  713. /// <param name="param"></param>
  714. /// <returns></returns>
  715. public string uploaderCaps(byte[] data, string path, string param)
  716. {
  717. UUID inv = inventoryItemID;
  718. string res = String.Empty;
  719. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  720. uploadComplete.new_asset = newAssetID.ToString();
  721. uploadComplete.new_inventory_item = inv;
  722. uploadComplete.state = "complete";
  723. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  724. httpListener.RemoveStreamHandler("POST", uploaderPath);
  725. // TODO: probably make this a better set of extensions here
  726. string extension = ".jp2";
  727. if (m_invType != "image")
  728. {
  729. extension = ".dat";
  730. }
  731. if (m_dumpAssetsToFile)
  732. {
  733. SaveAssetToFile(m_assetName + extension, data);
  734. }
  735. handlerUpLoad = OnUpLoad;
  736. if (handlerUpLoad != null)
  737. {
  738. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
  739. }
  740. return res;
  741. }
  742. ///Left this in and commented in case there are unforseen issues
  743. //private void SaveAssetToFile(string filename, byte[] data)
  744. //{
  745. // FileStream fs = File.Create(filename);
  746. // BinaryWriter bw = new BinaryWriter(fs);
  747. // bw.Write(data);
  748. // bw.Close();
  749. // fs.Close();
  750. //}
  751. private static void SaveAssetToFile(string filename, byte[] data)
  752. {
  753. string assetPath = "UserAssets";
  754. if (!Directory.Exists(assetPath))
  755. {
  756. Directory.CreateDirectory(assetPath);
  757. }
  758. FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
  759. BinaryWriter bw = new BinaryWriter(fs);
  760. bw.Write(data);
  761. bw.Close();
  762. fs.Close();
  763. }
  764. }
  765. /// <summary>
  766. /// This class is a callback invoked when a client sends asset data to
  767. /// an agent inventory notecard update url
  768. /// </summary>
  769. public class ItemUpdater
  770. {
  771. public event UpdateItem OnUpLoad;
  772. private UpdateItem handlerUpdateItem = null;
  773. private string uploaderPath = String.Empty;
  774. private UUID inventoryItemID;
  775. private IHttpServer httpListener;
  776. private bool m_dumpAssetToFile;
  777. public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer, bool dumpAssetToFile)
  778. {
  779. m_dumpAssetToFile = dumpAssetToFile;
  780. inventoryItemID = inventoryItem;
  781. uploaderPath = path;
  782. httpListener = httpServer;
  783. }
  784. /// <summary>
  785. /// Handle raw uploaded asset data.
  786. /// </summary>
  787. /// <param name="data"></param>
  788. /// <param name="path"></param>
  789. /// <param name="param"></param>
  790. /// <returns></returns>
  791. public string uploaderCaps(byte[] data, string path, string param)
  792. {
  793. UUID inv = inventoryItemID;
  794. string res = String.Empty;
  795. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  796. UUID assetID = UUID.Zero;
  797. handlerUpdateItem = OnUpLoad;
  798. if (handlerUpdateItem != null)
  799. {
  800. assetID = handlerUpdateItem(inv, data);
  801. }
  802. uploadComplete.new_asset = assetID.ToString();
  803. uploadComplete.new_inventory_item = inv;
  804. uploadComplete.state = "complete";
  805. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  806. httpListener.RemoveStreamHandler("POST", uploaderPath);
  807. if (m_dumpAssetToFile)
  808. {
  809. SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  810. }
  811. return res;
  812. }
  813. ///Left this in and commented in case there are unforseen issues
  814. //private void SaveAssetToFile(string filename, byte[] data)
  815. //{
  816. // FileStream fs = File.Create(filename);
  817. // BinaryWriter bw = new BinaryWriter(fs);
  818. // bw.Write(data);
  819. // bw.Close();
  820. // fs.Close();
  821. //}
  822. private static void SaveAssetToFile(string filename, byte[] data)
  823. {
  824. string assetPath = "UserAssets";
  825. if (!Directory.Exists(assetPath))
  826. {
  827. Directory.CreateDirectory(assetPath);
  828. }
  829. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  830. BinaryWriter bw = new BinaryWriter(fs);
  831. bw.Write(data);
  832. bw.Close();
  833. fs.Close();
  834. }
  835. }
  836. /// <summary>
  837. /// This class is a callback invoked when a client sends asset data to
  838. /// a task inventory script update url
  839. /// </summary>
  840. public class TaskInventoryScriptUpdater
  841. {
  842. private static readonly ILog m_log =
  843. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  844. public event UpdateTaskScript OnUpLoad;
  845. private UpdateTaskScript handlerUpdateTaskScript = null;
  846. private string uploaderPath = String.Empty;
  847. private UUID inventoryItemID;
  848. private UUID primID;
  849. private bool isScriptRunning;
  850. private IHttpServer httpListener;
  851. private bool m_dumpAssetToFile;
  852. public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
  853. string path, IHttpServer httpServer, bool dumpAssetToFile)
  854. {
  855. m_dumpAssetToFile = dumpAssetToFile;
  856. this.inventoryItemID = inventoryItemID;
  857. this.primID = primID;
  858. // This comes in over the packet as an integer, but actually appears to be treated as a bool
  859. this.isScriptRunning = (0 == isScriptRunning ? false : true);
  860. uploaderPath = path;
  861. httpListener = httpServer;
  862. }
  863. /// <summary>
  864. ///
  865. /// </summary>
  866. /// <param name="data"></param>
  867. /// <param name="path"></param>
  868. /// <param name="param"></param>
  869. /// <returns></returns>
  870. public string uploaderCaps(byte[] data, string path, string param)
  871. {
  872. try
  873. {
  874. // m_log.InfoFormat("[CAPS]: " +
  875. // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
  876. // data, path, param));
  877. string res = String.Empty;
  878. LLSDTaskScriptUploadComplete uploadComplete = new LLSDTaskScriptUploadComplete();
  879. ArrayList errors = new ArrayList();
  880. handlerUpdateTaskScript = OnUpLoad;
  881. if (handlerUpdateTaskScript != null)
  882. {
  883. handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data, ref errors);
  884. }
  885. uploadComplete.new_asset = inventoryItemID;
  886. uploadComplete.compiled = errors.Count > 0 ? false : true;
  887. uploadComplete.state = "complete";
  888. uploadComplete.errors = new OpenSim.Framework.Capabilities.OSDArray();
  889. uploadComplete.errors.Array = errors;
  890. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  891. httpListener.RemoveStreamHandler("POST", uploaderPath);
  892. if (m_dumpAssetToFile)
  893. {
  894. SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  895. }
  896. // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
  897. return res;
  898. }
  899. catch (Exception e)
  900. {
  901. m_log.Error("[CAPS]: " + e.ToString());
  902. }
  903. // XXX Maybe this should be some meaningful error packet
  904. return null;
  905. }
  906. ///Left this in and commented in case there are unforseen issues
  907. //private void SaveAssetToFile(string filename, byte[] data)
  908. //{
  909. // FileStream fs = File.Create(filename);
  910. // BinaryWriter bw = new BinaryWriter(fs);
  911. // bw.Write(data);
  912. // bw.Close();
  913. // fs.Close();
  914. //}
  915. private static void SaveAssetToFile(string filename, byte[] data)
  916. {
  917. string assetPath = "UserAssets";
  918. if (!Directory.Exists(assetPath))
  919. {
  920. Directory.CreateDirectory(assetPath);
  921. }
  922. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  923. BinaryWriter bw = new BinaryWriter(fs);
  924. bw.Write(data);
  925. bw.Close();
  926. fs.Close();
  927. }
  928. }
  929. }