Caps.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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 OpenSim 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 log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Framework.Servers;
  35. // using OpenSim.Region.Framework.Interfaces;
  36. namespace OpenSim.Framework.Communications.Capabilities
  37. {
  38. public delegate void UpLoadedAsset(
  39. string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
  40. byte[] data, string inventoryType, string assetType);
  41. public delegate UUID UpdateItem(UUID itemID, byte[] data);
  42. public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data);
  43. public delegate void NewInventoryItem(UUID userID, InventoryItemBase item);
  44. public delegate UUID ItemUpdatedCallback(UUID userID, UUID itemID, byte[] data);
  45. public delegate void TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
  46. bool isScriptRunning, byte[] data);
  47. public delegate List<InventoryItemBase> FetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
  48. bool fetchFolders, bool fetchItems, int sortOrder);
  49. /// <summary>
  50. /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
  51. /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
  52. /// to just pass the whole Scene into CAPS.
  53. /// </summary>
  54. public delegate IClientAPI GetClientDelegate(UUID agentID);
  55. public class Caps
  56. {
  57. private static readonly ILog m_log =
  58. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. private string m_httpListenerHostName;
  60. private uint m_httpListenPort;
  61. /// <summary>
  62. /// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester.
  63. /// </summary>
  64. private string m_capsObjectPath;
  65. public string CapsObjectPath { get { return m_capsObjectPath; } }
  66. private CapsHandlers m_capsHandlers;
  67. private static readonly string m_requestPath = "0000/";
  68. // private static readonly string m_mapLayerPath = "0001/";
  69. private static readonly string m_newInventory = "0002/";
  70. //private static readonly string m_requestTexture = "0003/";
  71. private static readonly string m_notecardUpdatePath = "0004/";
  72. private static readonly string m_notecardTaskUpdatePath = "0005/";
  73. // private static readonly string m_fetchInventoryPath = "0006/";
  74. // The following entries are in a module, however, they are also here so that we don't re-assign
  75. // the path to another cap by mistake.
  76. // private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; // This is in a module.
  77. // private static readonly string m_provisionVoiceAccountRequestPath = "0008/";// This is in a module.
  78. // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
  79. //private string eventQueue = "0100/";
  80. private BaseHttpServer m_httpListener;
  81. private UUID m_agentID;
  82. private IAssetCache m_assetCache;
  83. private int m_eventQueueCount = 1;
  84. private Queue<string> m_capsEventQueue = new Queue<string>();
  85. private bool m_dumpAssetsToFile;
  86. private string m_regionName;
  87. public bool SSLCaps
  88. {
  89. get { return m_httpListener.UseSSL; }
  90. }
  91. public string SSLCommonName
  92. {
  93. get { return m_httpListener.SSLCommonName; }
  94. }
  95. // These are callbacks which will be setup by the scene so that we can update scene data when we
  96. // receive capability calls
  97. public NewInventoryItem AddNewInventoryItem = null;
  98. public ItemUpdatedCallback ItemUpdatedCall = null;
  99. public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
  100. public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
  101. public GetClientDelegate GetClient = null;
  102. public Caps(IAssetCache assetCache, BaseHttpServer httpServer, string httpListen, uint httpPort, string capsPath,
  103. UUID agent, bool dumpAssetsToFile, string regionName)
  104. {
  105. m_assetCache = assetCache;
  106. m_capsObjectPath = capsPath;
  107. m_httpListener = httpServer;
  108. m_httpListenerHostName = httpListen;
  109. m_httpListenPort = httpPort;
  110. if (httpServer.UseSSL)
  111. {
  112. m_httpListenPort = httpServer.SSLPort;
  113. httpListen = httpServer.SSLCommonName;
  114. httpPort = httpServer.SSLPort;
  115. }
  116. m_agentID = agent;
  117. m_dumpAssetsToFile = dumpAssetsToFile;
  118. m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort, httpServer.UseSSL);
  119. m_regionName = regionName;
  120. }
  121. /// <summary>
  122. /// Register all CAPS http service handlers
  123. /// </summary>
  124. public void RegisterHandlers()
  125. {
  126. DeregisterHandlers();
  127. string capsBase = "/CAPS/" + m_capsObjectPath;
  128. try
  129. {
  130. // the root of all evil
  131. m_capsHandlers["SEED"] = new RestStreamHandler("POST", capsBase + m_requestPath, CapsRequest);
  132. m_log.DebugFormat(
  133. "[CAPS]: Registered seed capability {0} for {1}", capsBase + m_requestPath, m_agentID);
  134. //m_capsHandlers["MapLayer"] =
  135. // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
  136. // capsBase + m_mapLayerPath,
  137. // GetMapLayer);
  138. m_capsHandlers["NewFileAgentInventory"] =
  139. new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>("POST",
  140. capsBase + m_newInventory,
  141. NewAgentInventoryRequest);
  142. m_capsHandlers["UpdateNotecardAgentInventory"] =
  143. new RestStreamHandler("POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory);
  144. m_capsHandlers["UpdateScriptAgentInventory"] = m_capsHandlers["UpdateNotecardAgentInventory"];
  145. m_capsHandlers["UpdateScriptTaskInventory"] =
  146. new RestStreamHandler("POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
  147. m_capsHandlers["UpdateScriptAgent"] = m_capsHandlers["UpdateScriptAgentInventory"];
  148. m_capsHandlers["UpdateScriptTask"] = m_capsHandlers["UpdateScriptTaskInventory"];
  149. // justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
  150. // subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
  151. // enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
  152. // but when I went on the Linden grid, the
  153. // simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
  154. // the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
  155. //
  156. // This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
  157. // we will be
  158. // able to get the data we need to implement the necessary part of the protocol to fix the issue above.
  159. // m_capsHandlers["FetchInventoryDescendents"] =
  160. // new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
  161. // m_capsHandlers["FetchInventoryDescendents"] =
  162. // new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
  163. // capsBase + m_fetchInventory,
  164. // FetchInventory));
  165. // m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
  166. // capsBase + m_requestTexture,
  167. // RequestTexture);
  168. }
  169. catch (Exception e)
  170. {
  171. m_log.Error("[CAPS]: " + e.ToString());
  172. }
  173. }
  174. /// <summary>
  175. /// Register a handler. This allows modules to register handlers.
  176. /// </summary>
  177. /// <param name="capName"></param>
  178. /// <param name="handler"></param>
  179. public void RegisterHandler(string capName, IRequestHandler handler)
  180. {
  181. m_capsHandlers[capName] = handler;
  182. //m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
  183. }
  184. /// <summary>
  185. /// Remove all CAPS service handlers.
  186. ///
  187. /// </summary>
  188. /// <param name="httpListener"></param>
  189. /// <param name="path"></param>
  190. /// <param name="restMethod"></param>
  191. public void DeregisterHandlers()
  192. {
  193. if (m_capsHandlers != null)
  194. {
  195. foreach (string capsName in m_capsHandlers.Caps)
  196. {
  197. m_capsHandlers.Remove(capsName);
  198. }
  199. }
  200. }
  201. /// <summary>
  202. /// Construct a client response detailing all the capabilities this server can provide.
  203. /// </summary>
  204. /// <param name="request"></param>
  205. /// <param name="path"></param>
  206. /// <param name="param"></param>
  207. /// <param name="httpRequest">HTTP request header object</param>
  208. /// <param name="httpResponse">HTTP response header object</param>
  209. /// <returns></returns>
  210. public string CapsRequest(string request, string path, string param,
  211. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  212. {
  213. //m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName);
  214. string result = LLSDHelpers.SerialiseLLSDReply(m_capsHandlers.CapsDetails);
  215. //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
  216. return result;
  217. }
  218. // FIXME: these all should probably go into the respective region
  219. // modules
  220. /// <summary>
  221. /// Processes a fetch inventory request and sends the reply
  222. /// </summary>
  223. /// <param name="request"></param>
  224. /// <param name="path"></param>
  225. /// <param name="param"></param>
  226. /// <returns></returns>
  227. // Request is like:
  228. //<llsd>
  229. // <map><key>folders</key>
  230. // <array>
  231. // <map>
  232. // <key>fetch-folders</key><boolean>1</boolean><key>fetch-items</key><boolean>1</boolean><key>folder-id</key><uuid>8e1e3a30-b9bf-11dc-95ff-0800200c9a66</uuid><key>owner-id</key><uuid>11111111-1111-0000-0000-000100bba000</uuid><key>sort-order</key><integer>1</integer>
  233. // </map>
  234. // </array>
  235. // </map>
  236. //</llsd>
  237. //
  238. // multiple fetch-folder maps are allowed within the larger folders map.
  239. public string FetchInventoryRequest(string request, string path, string param)
  240. {
  241. // string unmodifiedRequest = request.ToString();
  242. //m_log.DebugFormat("[AGENT INVENTORY]: Received CAPS fetch inventory request {0}", unmodifiedRequest);
  243. m_log.Debug("[CAPS]: Inventory Request in region: " + m_regionName);
  244. Hashtable hash = new Hashtable();
  245. try
  246. {
  247. hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  248. }
  249. catch (LLSD.LLSDParseException pe)
  250. {
  251. m_log.Error("[AGENT INVENTORY]: Fetch error: " + pe.Message);
  252. m_log.Error("Request: " + request.ToString());
  253. }
  254. ArrayList foldersrequested = (ArrayList)hash["folders"];
  255. string response = "";
  256. for (int i = 0; i < foldersrequested.Count; i++)
  257. {
  258. string inventoryitemstr = "";
  259. Hashtable inventoryhash = (Hashtable)foldersrequested[i];
  260. LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
  261. LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
  262. LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest);
  263. inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
  264. inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
  265. inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
  266. response += inventoryitemstr;
  267. }
  268. if (response.Length == 0)
  269. {
  270. // Ter-guess: If requests fail a lot, the client seems to stop requesting descendants.
  271. // Therefore, I'm concluding that the client only has so many threads available to do requests
  272. // and when a thread stalls.. is stays stalled.
  273. // Therefore we need to return something valid
  274. response = "<llsd><map><key>folders</key><array /></map></llsd>";
  275. }
  276. else
  277. {
  278. response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
  279. }
  280. //m_log.DebugFormat("[AGENT INVENTORY]: Replying to CAPS fetch inventory request with following xml");
  281. //m_log.Debug(Util.GetFormattedXml(response));
  282. return response;
  283. }
  284. /// <summary>
  285. /// Construct an LLSD reply packet to a CAPS inventory request
  286. /// </summary>
  287. /// <param name="invFetch"></param>
  288. /// <returns></returns>
  289. private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch)
  290. {
  291. LLSDInventoryDescendents reply = new LLSDInventoryDescendents();
  292. LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents();
  293. contents.agent___id = m_agentID;
  294. contents.owner___id = invFetch.owner_id;
  295. contents.folder___id = invFetch.folder_id;
  296. // The version number being sent back was originally 1.
  297. // Unfortunately, on 1.19.1.4, this means that we see a problem where on subsequent logins
  298. // without clearing client cache, objects in the root folder disappear until the cache is cleared,
  299. // at which point they reappear.
  300. //
  301. // Seeing the version to something other than 0 may be the right thing to do, but there is
  302. // a greater subtlety of the second life protocol that needs to be understood first.
  303. contents.version = 0;
  304. contents.descendents = 0;
  305. reply.folders.Array.Add(contents);
  306. List<InventoryItemBase> itemList = null;
  307. if (CAPSFetchInventoryDescendents != null)
  308. {
  309. itemList = CAPSFetchInventoryDescendents(m_agentID, invFetch.folder_id, invFetch.owner_id, invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order);
  310. }
  311. if (itemList != null)
  312. {
  313. foreach (InventoryItemBase invItem in itemList)
  314. {
  315. contents.items.Array.Add(ConvertInventoryItem(invItem));
  316. }
  317. }
  318. else
  319. {
  320. IClientAPI client = GetClient(m_agentID);
  321. // We're going to both notify the client of inventory service failure and send back a 'no folder contents' response.
  322. // If we don't send back the response,
  323. // the client becomes unhappy (see Teravus' comment in FetchInventoryRequest())
  324. if (client != null)
  325. {
  326. client.SendAgentAlertMessage(
  327. "AGIN0001E: The inventory service has either failed or is not responding. Your inventory will not function properly for the rest of this session. Please clear your cache and relog.",
  328. true);
  329. }
  330. else
  331. {
  332. m_log.ErrorFormat(
  333. "[AGENT INVENTORY]: Could not lookup controlling client for {0} in order to notify them of the inventory service failure",
  334. m_agentID);
  335. }
  336. }
  337. contents.descendents = contents.items.Array.Count;
  338. return reply;
  339. }
  340. /// <summary>
  341. /// Convert an internal inventory item object into an LLSD object.
  342. /// </summary>
  343. /// <param name="invItem"></param>
  344. /// <returns></returns>
  345. private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem)
  346. {
  347. LLSDInventoryItem llsdItem = new LLSDInventoryItem();
  348. llsdItem.asset_id = invItem.AssetID;
  349. llsdItem.created_at = invItem.CreationDate;
  350. llsdItem.desc = invItem.Description;
  351. llsdItem.flags = 0;
  352. llsdItem.item_id = invItem.ID;
  353. llsdItem.name = invItem.Name;
  354. llsdItem.parent_id = invItem.Folder;
  355. llsdItem.type = Enum.GetName(typeof(AssetType), invItem.AssetType).ToLower();
  356. llsdItem.inv_type = Enum.GetName(typeof(InventoryType), invItem.InvType).ToLower();
  357. llsdItem.permissions = new LLSDPermissions();
  358. llsdItem.permissions.creator_id = invItem.Creator;
  359. llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions;
  360. llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions;
  361. llsdItem.permissions.group_id = UUID.Zero;
  362. llsdItem.permissions.group_mask = 0;
  363. llsdItem.permissions.is_owner_group = false;
  364. llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions;
  365. llsdItem.permissions.owner_id = m_agentID; // FixMe
  366. llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
  367. llsdItem.sale_info = new LLSDSaleInfo();
  368. llsdItem.sale_info.sale_price = 10;
  369. llsdItem.sale_info.sale_type = "not";
  370. return llsdItem;
  371. }
  372. /// <summary>
  373. ///
  374. /// </summary>
  375. /// <param name="mapReq"></param>
  376. /// <returns></returns>
  377. public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
  378. {
  379. m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
  380. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  381. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  382. return mapResponse;
  383. }
  384. /// <summary>
  385. ///
  386. /// </summary>
  387. /// <returns></returns>
  388. protected static OSDMapLayer GetOSDMapLayerResponse()
  389. {
  390. OSDMapLayer mapLayer = new OSDMapLayer();
  391. mapLayer.Right = 5000;
  392. mapLayer.Top = 5000;
  393. mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
  394. return mapLayer;
  395. }
  396. /// <summary>
  397. ///
  398. /// </summary>
  399. /// <param name="request"></param>
  400. /// <param name="path"></param>
  401. /// <param name="param"></param>
  402. /// <returns></returns>
  403. public string RequestTexture(string request, string path, string param)
  404. {
  405. System.Console.WriteLine("texture request " + request);
  406. // Needs implementing (added to remove compiler warning)
  407. return String.Empty;
  408. }
  409. #region EventQueue (Currently not enabled)
  410. /// <summary>
  411. ///
  412. /// </summary>
  413. /// <param name="request"></param>
  414. /// <param name="path"></param>
  415. /// <param name="param"></param>
  416. /// <returns></returns>
  417. public string ProcessEventQueue(string request, string path, string param)
  418. {
  419. string res = String.Empty;
  420. if (m_capsEventQueue.Count > 0)
  421. {
  422. lock (m_capsEventQueue)
  423. {
  424. string item = m_capsEventQueue.Dequeue();
  425. res = item;
  426. }
  427. }
  428. else
  429. {
  430. res = CreateEmptyEventResponse();
  431. }
  432. return res;
  433. }
  434. /// <summary>
  435. ///
  436. /// </summary>
  437. /// <param name="caps"></param>
  438. /// <param name="ipAddressPort"></param>
  439. /// <returns></returns>
  440. public string CreateEstablishAgentComms(string caps, string ipAddressPort)
  441. {
  442. LLSDCapEvent eventItem = new LLSDCapEvent();
  443. eventItem.id = m_eventQueueCount;
  444. //should be creating a EstablishAgentComms item, but there isn't a class for it yet
  445. eventItem.events.Array.Add(new LLSDEmpty());
  446. string res = LLSDHelpers.SerialiseLLSDReply(eventItem);
  447. m_eventQueueCount++;
  448. m_capsEventQueue.Enqueue(res);
  449. return res;
  450. }
  451. /// <summary>
  452. ///
  453. /// </summary>
  454. /// <returns></returns>
  455. public string CreateEmptyEventResponse()
  456. {
  457. LLSDCapEvent eventItem = new LLSDCapEvent();
  458. eventItem.id = m_eventQueueCount;
  459. eventItem.events.Array.Add(new LLSDEmpty());
  460. string res = LLSDHelpers.SerialiseLLSDReply(eventItem);
  461. m_eventQueueCount++;
  462. return res;
  463. }
  464. #endregion
  465. /// <summary>
  466. /// Called by the script task update handler. Provides a URL to which the client can upload a new asset.
  467. /// </summary>
  468. /// <param name="request"></param>
  469. /// <param name="path"></param>
  470. /// <param name="param"></param>
  471. /// <param name="httpRequest">HTTP request header object</param>
  472. /// <param name="httpResponse">HTTP response header object</param>
  473. /// <returns></returns>
  474. public string ScriptTaskInventory(string request, string path, string param,
  475. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  476. {
  477. try
  478. {
  479. m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
  480. //m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
  481. Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  482. LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
  483. LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
  484. string capsBase = "/CAPS/" + m_capsObjectPath;
  485. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  486. TaskInventoryScriptUpdater uploader =
  487. new TaskInventoryScriptUpdater(
  488. llsdUpdateRequest.item_id,
  489. llsdUpdateRequest.task_id,
  490. llsdUpdateRequest.is_script_running,
  491. capsBase + uploaderPath,
  492. m_httpListener,
  493. m_dumpAssetsToFile);
  494. uploader.OnUpLoad += TaskScriptUpdated;
  495. m_httpListener.AddStreamHandler(
  496. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  497. string protocol = "http://";
  498. if (m_httpListener.UseSSL)
  499. protocol = "https://";
  500. string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
  501. uploaderPath;
  502. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  503. uploadResponse.uploader = uploaderURL;
  504. uploadResponse.state = "upload";
  505. // m_log.InfoFormat("[CAPS]: " +
  506. // "ScriptTaskInventory response: {0}",
  507. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  508. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  509. }
  510. catch (Exception e)
  511. {
  512. m_log.Error("[CAPS]: " + e.ToString());
  513. }
  514. return null;
  515. }
  516. /// <summary>
  517. /// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
  518. /// </summary>
  519. /// <param name="request"></param>
  520. /// <param name="path"></param>
  521. /// <param name="param"></param>
  522. /// <returns></returns>
  523. public string NoteCardAgentInventory(string request, string path, string param,
  524. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  525. {
  526. m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName);
  527. //OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
  528. Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  529. LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
  530. LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
  531. string capsBase = "/CAPS/" + m_capsObjectPath;
  532. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  533. ItemUpdater uploader =
  534. new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_httpListener, m_dumpAssetsToFile);
  535. uploader.OnUpLoad += ItemUpdated;
  536. m_httpListener.AddStreamHandler(
  537. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  538. string protocol = "http://";
  539. if (m_httpListener.UseSSL)
  540. protocol = "https://";
  541. string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
  542. uploaderPath;
  543. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  544. uploadResponse.uploader = uploaderURL;
  545. uploadResponse.state = "upload";
  546. // m_log.InfoFormat("[CAPS]: " +
  547. // "NoteCardAgentInventory response: {0}",
  548. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  549. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  550. }
  551. /// <summary>
  552. ///
  553. /// </summary>
  554. /// <param name="llsdRequest"></param>
  555. /// <returns></returns>
  556. public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
  557. {
  558. if (llsdRequest.asset_type == "texture" ||
  559. llsdRequest.asset_type == "animation" ||
  560. llsdRequest.asset_type == "sound")
  561. {
  562. IClientAPI client = GetClient(m_agentID);
  563. IScene scene = client.Scene;
  564. IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>();
  565. if (mm != null)
  566. {
  567. if (!mm.UploadCovered(client))
  568. {
  569. client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
  570. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  571. errorResponse.uploader = "";
  572. errorResponse.state = "error";
  573. return errorResponse;
  574. }
  575. }
  576. }
  577. //System.Console.WriteLine("asset upload request via CAPS" + llsdRequest.inventory_type +" , "+ llsdRequest.asset_type);
  578. string assetName = llsdRequest.name;
  579. string assetDes = llsdRequest.description;
  580. string capsBase = "/CAPS/" + m_capsObjectPath;
  581. UUID newAsset = UUID.Random();
  582. UUID newInvItem = UUID.Random();
  583. UUID parentFolder = llsdRequest.folder_id;
  584. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  585. AssetUploader uploader =
  586. new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
  587. llsdRequest.asset_type, capsBase + uploaderPath, m_httpListener, m_dumpAssetsToFile);
  588. m_httpListener.AddStreamHandler(
  589. new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
  590. string protocol = "http://";
  591. if (m_httpListener.UseSSL)
  592. protocol = "https://";
  593. string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
  594. uploaderPath;
  595. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  596. uploadResponse.uploader = uploaderURL;
  597. uploadResponse.state = "upload";
  598. uploader.OnUpLoad += UploadCompleteHandler;
  599. return uploadResponse;
  600. }
  601. /// <summary>
  602. ///
  603. /// </summary>
  604. /// <param name="assetID"></param>
  605. /// <param name="inventoryItem"></param>
  606. /// <param name="data"></param>
  607. public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
  608. UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
  609. string assetType)
  610. {
  611. sbyte assType = 0;
  612. sbyte inType = 0;
  613. if (inventoryType == "sound")
  614. {
  615. inType = 1;
  616. assType = 1;
  617. }
  618. else if (inventoryType == "animation")
  619. {
  620. inType = 19;
  621. assType = 20;
  622. }
  623. else if (inventoryType == "wearable")
  624. {
  625. inType = 18;
  626. switch (assetType)
  627. {
  628. case "bodypart":
  629. assType = 13;
  630. break;
  631. case "clothing":
  632. assType = 5;
  633. break;
  634. }
  635. }
  636. AssetBase asset;
  637. asset = new AssetBase();
  638. asset.FullID = assetID;
  639. asset.Type = assType;
  640. asset.Name = assetName;
  641. asset.Data = data;
  642. m_assetCache.AddAsset(asset);
  643. InventoryItemBase item = new InventoryItemBase();
  644. item.Owner = m_agentID;
  645. item.Creator = m_agentID;
  646. item.ID = inventoryItem;
  647. item.AssetID = asset.FullID;
  648. item.Description = assetDescription;
  649. item.Name = assetName;
  650. item.AssetType = assType;
  651. item.InvType = inType;
  652. item.Folder = parentFolder;
  653. item.CurrentPermissions = 2147483647;
  654. item.BasePermissions = 2147483647;
  655. item.EveryOnePermissions = 0;
  656. item.NextPermissions = 2147483647;
  657. item.CreationDate = Util.UnixTimeSinceEpoch();
  658. if (AddNewInventoryItem != null)
  659. {
  660. AddNewInventoryItem(m_agentID, item);
  661. }
  662. }
  663. /// <summary>
  664. /// Called when new asset data for an agent inventory item update has been uploaded.
  665. /// </summary>
  666. /// <param name="itemID">Item to update</param>
  667. /// <param name="data">New asset data</param>
  668. /// <returns></returns>
  669. public UUID ItemUpdated(UUID itemID, byte[] data)
  670. {
  671. if (ItemUpdatedCall != null)
  672. {
  673. return ItemUpdatedCall(m_agentID, itemID, data);
  674. }
  675. return UUID.Zero;
  676. }
  677. /// <summary>
  678. /// Called when new asset data for an agent inventory item update has been uploaded.
  679. /// </summary>
  680. /// <param name="itemID">Item to update</param>
  681. /// <param name="primID">Prim containing item to update</param>
  682. /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
  683. /// <param name="data">New asset data</param>
  684. public void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data)
  685. {
  686. if (TaskScriptUpdatedCall != null)
  687. {
  688. TaskScriptUpdatedCall(m_agentID, itemID, primID, isScriptRunning, data);
  689. }
  690. }
  691. public class AssetUploader
  692. {
  693. public event UpLoadedAsset OnUpLoad;
  694. private UpLoadedAsset handlerUpLoad = null;
  695. private string uploaderPath = String.Empty;
  696. private UUID newAssetID;
  697. private UUID inventoryItemID;
  698. private UUID parentFolder;
  699. private BaseHttpServer httpListener;
  700. private bool m_dumpAssetsToFile;
  701. private string m_assetName = String.Empty;
  702. private string m_assetDes = String.Empty;
  703. private string m_invType = String.Empty;
  704. private string m_assetType = String.Empty;
  705. public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
  706. UUID parentFolderID, string invType, string assetType, string path,
  707. BaseHttpServer httpServer, bool dumpAssetsToFile)
  708. {
  709. m_assetName = assetName;
  710. m_assetDes = description;
  711. newAssetID = assetID;
  712. inventoryItemID = inventoryItem;
  713. uploaderPath = path;
  714. httpListener = httpServer;
  715. parentFolder = parentFolderID;
  716. m_assetType = assetType;
  717. m_invType = invType;
  718. m_dumpAssetsToFile = dumpAssetsToFile;
  719. }
  720. /// <summary>
  721. ///
  722. /// </summary>
  723. /// <param name="data"></param>
  724. /// <param name="path"></param>
  725. /// <param name="param"></param>
  726. /// <returns></returns>
  727. public string uploaderCaps(byte[] data, string path, string param)
  728. {
  729. UUID inv = inventoryItemID;
  730. string res = String.Empty;
  731. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  732. uploadComplete.new_asset = newAssetID.ToString();
  733. uploadComplete.new_inventory_item = inv;
  734. uploadComplete.state = "complete";
  735. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  736. httpListener.RemoveStreamHandler("POST", uploaderPath);
  737. // TODO: probably make this a better set of extensions here
  738. string extension = ".jp2";
  739. if (m_invType != "image")
  740. {
  741. extension = ".dat";
  742. }
  743. if (m_dumpAssetsToFile)
  744. {
  745. SaveAssetToFile(m_assetName + extension, data);
  746. }
  747. handlerUpLoad = OnUpLoad;
  748. if (handlerUpLoad != null)
  749. {
  750. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
  751. }
  752. return res;
  753. }
  754. ///Left this in and commented in case there are unforseen issues
  755. //private void SaveAssetToFile(string filename, byte[] data)
  756. //{
  757. // FileStream fs = File.Create(filename);
  758. // BinaryWriter bw = new BinaryWriter(fs);
  759. // bw.Write(data);
  760. // bw.Close();
  761. // fs.Close();
  762. //}
  763. private static void SaveAssetToFile(string filename, byte[] data)
  764. {
  765. string assetPath = "UserAssets";
  766. if (!Directory.Exists(assetPath))
  767. {
  768. Directory.CreateDirectory(assetPath);
  769. }
  770. FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
  771. BinaryWriter bw = new BinaryWriter(fs);
  772. bw.Write(data);
  773. bw.Close();
  774. fs.Close();
  775. }
  776. }
  777. /// <summary>
  778. /// This class is a callback invoked when a client sends asset data to
  779. /// an agent inventory notecard update url
  780. /// </summary>
  781. public class ItemUpdater
  782. {
  783. public event UpdateItem OnUpLoad;
  784. private UpdateItem handlerUpdateItem = null;
  785. private string uploaderPath = String.Empty;
  786. private UUID inventoryItemID;
  787. private BaseHttpServer httpListener;
  788. private bool m_dumpAssetToFile;
  789. public ItemUpdater(UUID inventoryItem, string path, BaseHttpServer httpServer, bool dumpAssetToFile)
  790. {
  791. m_dumpAssetToFile = dumpAssetToFile;
  792. inventoryItemID = inventoryItem;
  793. uploaderPath = path;
  794. httpListener = httpServer;
  795. }
  796. /// <summary>
  797. ///
  798. /// </summary>
  799. /// <param name="data"></param>
  800. /// <param name="path"></param>
  801. /// <param name="param"></param>
  802. /// <returns></returns>
  803. public string uploaderCaps(byte[] data, string path, string param)
  804. {
  805. UUID inv = inventoryItemID;
  806. string res = String.Empty;
  807. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  808. UUID assetID = UUID.Zero;
  809. handlerUpdateItem = OnUpLoad;
  810. if (handlerUpdateItem != null)
  811. {
  812. assetID = handlerUpdateItem(inv, data);
  813. }
  814. uploadComplete.new_asset = assetID.ToString();
  815. uploadComplete.new_inventory_item = inv;
  816. uploadComplete.state = "complete";
  817. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  818. httpListener.RemoveStreamHandler("POST", uploaderPath);
  819. if (m_dumpAssetToFile)
  820. {
  821. SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  822. }
  823. return res;
  824. }
  825. ///Left this in and commented in case there are unforseen issues
  826. //private void SaveAssetToFile(string filename, byte[] data)
  827. //{
  828. // FileStream fs = File.Create(filename);
  829. // BinaryWriter bw = new BinaryWriter(fs);
  830. // bw.Write(data);
  831. // bw.Close();
  832. // fs.Close();
  833. //}
  834. private static void SaveAssetToFile(string filename, byte[] data)
  835. {
  836. string assetPath = "UserAssets";
  837. if (!Directory.Exists(assetPath))
  838. {
  839. Directory.CreateDirectory(assetPath);
  840. }
  841. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  842. BinaryWriter bw = new BinaryWriter(fs);
  843. bw.Write(data);
  844. bw.Close();
  845. fs.Close();
  846. }
  847. }
  848. /// <summary>
  849. /// This class is a callback invoked when a client sends asset data to
  850. /// a task inventory script update url
  851. /// </summary>
  852. public class TaskInventoryScriptUpdater
  853. {
  854. public event UpdateTaskScript OnUpLoad;
  855. private UpdateTaskScript handlerUpdateTaskScript = null;
  856. private string uploaderPath = String.Empty;
  857. private UUID inventoryItemID;
  858. private UUID primID;
  859. private bool isScriptRunning;
  860. private BaseHttpServer httpListener;
  861. private bool m_dumpAssetToFile;
  862. public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
  863. string path, BaseHttpServer httpServer, bool dumpAssetToFile)
  864. {
  865. m_dumpAssetToFile = dumpAssetToFile;
  866. this.inventoryItemID = inventoryItemID;
  867. this.primID = primID;
  868. // This comes in over the packet as an integer, but actually appears to be treated as a bool
  869. this.isScriptRunning = (0 == isScriptRunning ? false : true);
  870. uploaderPath = path;
  871. httpListener = httpServer;
  872. }
  873. /// <summary>
  874. ///
  875. /// </summary>
  876. /// <param name="data"></param>
  877. /// <param name="path"></param>
  878. /// <param name="param"></param>
  879. /// <returns></returns>
  880. public string uploaderCaps(byte[] data, string path, string param)
  881. {
  882. try
  883. {
  884. // m_log.InfoFormat("[CAPS]: " +
  885. // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
  886. // data, path, param));
  887. string res = String.Empty;
  888. LLSDTaskInventoryUploadComplete uploadComplete = new LLSDTaskInventoryUploadComplete();
  889. handlerUpdateTaskScript = OnUpLoad;
  890. if (handlerUpdateTaskScript != null)
  891. {
  892. handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data);
  893. }
  894. uploadComplete.item_id = inventoryItemID;
  895. uploadComplete.task_id = primID;
  896. uploadComplete.state = "complete";
  897. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  898. httpListener.RemoveStreamHandler("POST", uploaderPath);
  899. if (m_dumpAssetToFile)
  900. {
  901. SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  902. }
  903. // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
  904. return res;
  905. }
  906. catch (Exception e)
  907. {
  908. m_log.Error("[CAPS]: " + e.ToString());
  909. }
  910. // XXX Maybe this should be some meaningful error packet
  911. return null;
  912. }
  913. ///Left this in and commented in case there are unforseen issues
  914. //private void SaveAssetToFile(string filename, byte[] data)
  915. //{
  916. // FileStream fs = File.Create(filename);
  917. // BinaryWriter bw = new BinaryWriter(fs);
  918. // bw.Write(data);
  919. // bw.Close();
  920. // fs.Close();
  921. //}
  922. private static void SaveAssetToFile(string filename, byte[] data)
  923. {
  924. string assetPath = "UserAssets";
  925. if (!Directory.Exists(assetPath))
  926. {
  927. Directory.CreateDirectory(assetPath);
  928. }
  929. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  930. BinaryWriter bw = new BinaryWriter(fs);
  931. bw.Write(data);
  932. bw.Close();
  933. fs.Close();
  934. }
  935. }
  936. }
  937. }