Caps.cs 41 KB

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