1
0

Caps.cs 43 KB

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