Caps.cs 45 KB

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