Caps.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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.DebugFormat(
  135. "[CAPS]: Registered seed capability {0} for {1}", capsBase + m_requestPath, m_agentID);
  136. //m_capsHandlers["MapLayer"] =
  137. // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
  138. // capsBase + m_mapLayerPath,
  139. // GetMapLayer);
  140. m_capsHandlers["NewFileAgentInventory"] =
  141. new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>("POST",
  142. capsBase + m_newInventory,
  143. NewAgentInventoryRequest);
  144. m_capsHandlers["UpdateNotecardAgentInventory"] =
  145. new RestStreamHandler("POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory);
  146. m_capsHandlers["UpdateScriptAgentInventory"] = m_capsHandlers["UpdateNotecardAgentInventory"];
  147. m_capsHandlers["UpdateScriptTaskInventory"] =
  148. new RestStreamHandler("POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
  149. m_capsHandlers["UpdateScriptAgent"] = m_capsHandlers["UpdateScriptAgentInventory"];
  150. m_capsHandlers["UpdateScriptTask"] = m_capsHandlers["UpdateScriptTaskInventory"];
  151. // justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
  152. // subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
  153. // enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
  154. // but when I went on the Linden grid, the
  155. // simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
  156. // the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
  157. //
  158. // This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
  159. // we will be
  160. // able to get the data we need to implement the necessary part of the protocol to fix the issue above.
  161. // m_capsHandlers["FetchInventoryDescendents"] =
  162. // new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
  163. // m_capsHandlers["FetchInventoryDescendents"] =
  164. // new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
  165. // capsBase + m_fetchInventory,
  166. // FetchInventory));
  167. // m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
  168. // capsBase + m_requestTexture,
  169. // RequestTexture);
  170. }
  171. catch (Exception e)
  172. {
  173. m_log.Error("[CAPS]: " + e.ToString());
  174. }
  175. }
  176. /// <summary>
  177. /// Register a handler. This allows modules to register handlers.
  178. /// </summary>
  179. /// <param name="capName"></param>
  180. /// <param name="handler"></param>
  181. public void RegisterHandler(string capName, IRequestHandler handler)
  182. {
  183. m_capsHandlers[capName] = handler;
  184. //m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
  185. }
  186. /// <summary>
  187. /// Remove all CAPS service handlers.
  188. ///
  189. /// </summary>
  190. /// <param name="httpListener"></param>
  191. /// <param name="path"></param>
  192. /// <param name="restMethod"></param>
  193. public void DeregisterHandlers()
  194. {
  195. if (m_capsHandlers != null)
  196. {
  197. foreach (string capsName in m_capsHandlers.Caps)
  198. {
  199. m_capsHandlers.Remove(capsName);
  200. }
  201. }
  202. }
  203. /// <summary>
  204. /// Construct a client response detailing all the capabilities this server can provide.
  205. /// </summary>
  206. /// <param name="request"></param>
  207. /// <param name="path"></param>
  208. /// <param name="param"></param>
  209. /// <param name="httpRequest">HTTP request header object</param>
  210. /// <param name="httpResponse">HTTP response header object</param>
  211. /// <returns></returns>
  212. public string CapsRequest(string request, string path, string param,
  213. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  214. {
  215. //m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName);
  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. }