Caps.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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.Name = assetName;
  592. asset.Data = data;
  593. m_assetCache.AddAsset(asset);
  594. InventoryItemBase item = new InventoryItemBase();
  595. item.Owner = m_agentID;
  596. item.Creator = m_agentID;
  597. item.ID = inventoryItem;
  598. item.AssetID = asset.FullID;
  599. item.Description = assetDescription;
  600. item.Name = assetName;
  601. item.AssetType = assType;
  602. item.InvType = inType;
  603. item.Folder = parentFolder;
  604. item.CurrentPermissions = 2147483647;
  605. item.BasePermissions = 2147483647;
  606. item.EveryOnePermissions = 0;
  607. item.NextPermissions = 2147483647;
  608. if (AddNewInventoryItem != null)
  609. {
  610. AddNewInventoryItem(m_agentID, item);
  611. }
  612. }
  613. /// <summary>
  614. /// Called when new asset data for an agent inventory item update has been uploaded.
  615. /// </summary>
  616. /// <param name="itemID">Item to update</param>
  617. /// <param name="data">New asset data</param>
  618. /// <returns></returns>
  619. public LLUUID ItemUpdated(LLUUID itemID, byte[] data)
  620. {
  621. if (ItemUpdatedCall != null)
  622. {
  623. return ItemUpdatedCall(m_agentID, itemID, data);
  624. }
  625. return LLUUID.Zero;
  626. }
  627. /// <summary>
  628. /// Called when new asset data for an agent inventory item update has been uploaded.
  629. /// </summary>
  630. /// <param name="itemID">Item to update</param>
  631. /// <param name="primID">Prim containing item to update</param>
  632. /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
  633. /// <param name="data">New asset data</param>
  634. public void TaskScriptUpdated(LLUUID itemID, LLUUID primID, bool isScriptRunning, byte[] data)
  635. {
  636. if (TaskScriptUpdatedCall != null)
  637. {
  638. TaskScriptUpdatedCall(m_agentID, itemID, primID, isScriptRunning, data);
  639. }
  640. }
  641. public class AssetUploader
  642. {
  643. public event UpLoadedAsset OnUpLoad;
  644. private UpLoadedAsset handlerUpLoad = null;
  645. private string uploaderPath = String.Empty;
  646. private LLUUID newAssetID;
  647. private LLUUID inventoryItemID;
  648. private LLUUID parentFolder;
  649. private BaseHttpServer httpListener;
  650. private bool m_dumpAssetsToFile;
  651. private string m_assetName = String.Empty;
  652. private string m_assetDes = String.Empty;
  653. private string m_invType = String.Empty;
  654. private string m_assetType = String.Empty;
  655. public AssetUploader(string assetName, string description, LLUUID assetID, LLUUID inventoryItem,
  656. LLUUID parentFolderID, string invType, string assetType, string path,
  657. BaseHttpServer httpServer, bool dumpAssetsToFile)
  658. {
  659. m_assetName = assetName;
  660. m_assetDes = description;
  661. newAssetID = assetID;
  662. inventoryItemID = inventoryItem;
  663. uploaderPath = path;
  664. httpListener = httpServer;
  665. parentFolder = parentFolderID;
  666. m_assetType = assetType;
  667. m_invType = invType;
  668. m_dumpAssetsToFile = dumpAssetsToFile;
  669. }
  670. /// <summary>
  671. ///
  672. /// </summary>
  673. /// <param name="data"></param>
  674. /// <param name="path"></param>
  675. /// <param name="param"></param>
  676. /// <returns></returns>
  677. public string uploaderCaps(byte[] data, string path, string param)
  678. {
  679. LLUUID inv = inventoryItemID;
  680. string res = String.Empty;
  681. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  682. uploadComplete.new_asset = newAssetID.ToString();
  683. uploadComplete.new_inventory_item = inv;
  684. uploadComplete.state = "complete";
  685. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  686. httpListener.RemoveStreamHandler("POST", uploaderPath);
  687. // TODO: probably make this a better set of extensions here
  688. string extension = ".jp2";
  689. if (m_invType != "image")
  690. {
  691. extension = ".dat";
  692. }
  693. if (m_dumpAssetsToFile)
  694. {
  695. SaveAssetToFile(m_assetName + extension, data);
  696. }
  697. handlerUpLoad = OnUpLoad;
  698. if (handlerUpLoad != null)
  699. {
  700. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
  701. }
  702. return res;
  703. }
  704. ///Left this in and commented in case there are unforseen issues
  705. //private void SaveAssetToFile(string filename, byte[] data)
  706. //{
  707. // FileStream fs = File.Create(filename);
  708. // BinaryWriter bw = new BinaryWriter(fs);
  709. // bw.Write(data);
  710. // bw.Close();
  711. // fs.Close();
  712. //}
  713. private static void SaveAssetToFile(string filename, byte[] data)
  714. {
  715. string assetPath = "UserAssets";
  716. if (!Directory.Exists(assetPath))
  717. {
  718. Directory.CreateDirectory(assetPath);
  719. }
  720. FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
  721. BinaryWriter bw = new BinaryWriter(fs);
  722. bw.Write(data);
  723. bw.Close();
  724. fs.Close();
  725. }
  726. }
  727. /// <summary>
  728. /// This class is a callback invoked when a client sends asset data to
  729. /// an agent inventory notecard update url
  730. /// </summary>
  731. public class ItemUpdater
  732. {
  733. public event UpdateItem OnUpLoad;
  734. private UpdateItem handlerUpdateItem = null;
  735. private string uploaderPath = String.Empty;
  736. private LLUUID inventoryItemID;
  737. private BaseHttpServer httpListener;
  738. private bool m_dumpAssetToFile;
  739. public ItemUpdater(LLUUID inventoryItem, string path, BaseHttpServer httpServer, bool dumpAssetToFile)
  740. {
  741. m_dumpAssetToFile = dumpAssetToFile;
  742. inventoryItemID = inventoryItem;
  743. uploaderPath = path;
  744. httpListener = httpServer;
  745. }
  746. /// <summary>
  747. ///
  748. /// </summary>
  749. /// <param name="data"></param>
  750. /// <param name="path"></param>
  751. /// <param name="param"></param>
  752. /// <returns></returns>
  753. public string uploaderCaps(byte[] data, string path, string param)
  754. {
  755. LLUUID inv = inventoryItemID;
  756. string res = String.Empty;
  757. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  758. LLUUID assetID = LLUUID.Zero;
  759. handlerUpdateItem = OnUpLoad;
  760. if (handlerUpdateItem != null)
  761. {
  762. assetID = handlerUpdateItem(inv, data);
  763. }
  764. uploadComplete.new_asset = assetID.ToString();
  765. uploadComplete.new_inventory_item = inv;
  766. uploadComplete.state = "complete";
  767. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  768. httpListener.RemoveStreamHandler("POST", uploaderPath);
  769. if (m_dumpAssetToFile)
  770. {
  771. SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  772. }
  773. return res;
  774. }
  775. ///Left this in and commented in case there are unforseen issues
  776. //private void SaveAssetToFile(string filename, byte[] data)
  777. //{
  778. // FileStream fs = File.Create(filename);
  779. // BinaryWriter bw = new BinaryWriter(fs);
  780. // bw.Write(data);
  781. // bw.Close();
  782. // fs.Close();
  783. //}
  784. private static void SaveAssetToFile(string filename, byte[] data)
  785. {
  786. string assetPath = "UserAssets";
  787. if (!Directory.Exists(assetPath))
  788. {
  789. Directory.CreateDirectory(assetPath);
  790. }
  791. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  792. BinaryWriter bw = new BinaryWriter(fs);
  793. bw.Write(data);
  794. bw.Close();
  795. fs.Close();
  796. }
  797. }
  798. /// <summary>
  799. /// This class is a callback invoked when a client sends asset data to
  800. /// a task inventory script update url
  801. /// </summary>
  802. public class TaskInventoryScriptUpdater
  803. {
  804. public event UpdateTaskScript OnUpLoad;
  805. private UpdateTaskScript handlerUpdateTaskScript = null;
  806. private string uploaderPath = String.Empty;
  807. private LLUUID inventoryItemID;
  808. private LLUUID primID;
  809. private bool isScriptRunning;
  810. private BaseHttpServer httpListener;
  811. private bool m_dumpAssetToFile;
  812. public TaskInventoryScriptUpdater(LLUUID inventoryItemID, LLUUID primID, int isScriptRunning,
  813. string path, BaseHttpServer httpServer, bool dumpAssetToFile)
  814. {
  815. m_dumpAssetToFile = dumpAssetToFile;
  816. this.inventoryItemID = inventoryItemID;
  817. this.primID = primID;
  818. // This comes in over the packet as an integer, but actually appears to be treated as a bool
  819. this.isScriptRunning = (0 == isScriptRunning ? false : true);
  820. uploaderPath = path;
  821. httpListener = httpServer;
  822. }
  823. /// <summary>
  824. ///
  825. /// </summary>
  826. /// <param name="data"></param>
  827. /// <param name="path"></param>
  828. /// <param name="param"></param>
  829. /// <returns></returns>
  830. public string uploaderCaps(byte[] data, string path, string param)
  831. {
  832. try
  833. {
  834. // m_log.InfoFormat("[CAPS]: " +
  835. // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
  836. // data, path, param));
  837. string res = String.Empty;
  838. LLSDTaskInventoryUploadComplete uploadComplete = new LLSDTaskInventoryUploadComplete();
  839. handlerUpdateTaskScript = OnUpLoad;
  840. if (handlerUpdateTaskScript != null)
  841. {
  842. handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data);
  843. }
  844. uploadComplete.item_id = inventoryItemID;
  845. uploadComplete.task_id = primID;
  846. uploadComplete.state = "complete";
  847. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  848. httpListener.RemoveStreamHandler("POST", uploaderPath);
  849. if (m_dumpAssetToFile)
  850. {
  851. SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  852. }
  853. // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
  854. return res;
  855. }
  856. catch (Exception e)
  857. {
  858. m_log.Error("[CAPS]: " + e.ToString());
  859. }
  860. // XXX Maybe this should be some meaningful error packet
  861. return null;
  862. }
  863. ///Left this in and commented in case there are unforseen issues
  864. //private void SaveAssetToFile(string filename, byte[] data)
  865. //{
  866. // FileStream fs = File.Create(filename);
  867. // BinaryWriter bw = new BinaryWriter(fs);
  868. // bw.Write(data);
  869. // bw.Close();
  870. // fs.Close();
  871. //}
  872. private static void SaveAssetToFile(string filename, byte[] data)
  873. {
  874. string assetPath = "UserAssets";
  875. if (!Directory.Exists(assetPath))
  876. {
  877. Directory.CreateDirectory(assetPath);
  878. }
  879. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  880. BinaryWriter bw = new BinaryWriter(fs);
  881. bw.Write(data);
  882. bw.Close();
  883. fs.Close();
  884. }
  885. }
  886. }
  887. }