InventoryArchiveReadRequest.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 OpenSimulator 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.Generic;
  29. using System.IO;
  30. using System.IO.Compression;
  31. using System.Reflection;
  32. using System.Threading;
  33. using System.Text;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Communications;
  39. using OpenSim.Framework.Communications.Cache;
  40. using OpenSim.Framework.Communications.Osp;
  41. using OpenSim.Framework.Serialization;
  42. using OpenSim.Framework.Serialization.External;
  43. using OpenSim.Region.CoreModules.World.Archiver;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Services.Interfaces;
  46. namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
  47. {
  48. public class InventoryArchiveReadRequest
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. protected TarArchiveReader archive;
  52. private CachedUserInfo m_userInfo;
  53. private string m_invPath;
  54. /// <value>
  55. /// We only use this to request modules
  56. /// </value>
  57. protected Scene m_scene;
  58. /// <value>
  59. /// The stream from which the inventory archive will be loaded.
  60. /// </value>
  61. private Stream m_loadStream;
  62. public InventoryArchiveReadRequest(
  63. Scene scene, CachedUserInfo userInfo, string invPath, string loadPath)
  64. : this(
  65. scene,
  66. userInfo,
  67. invPath,
  68. new GZipStream(new FileStream(loadPath, FileMode.Open), CompressionMode.Decompress))
  69. {
  70. }
  71. public InventoryArchiveReadRequest(
  72. Scene scene, CachedUserInfo userInfo, string invPath, Stream loadStream)
  73. {
  74. m_scene = scene;
  75. m_userInfo = userInfo;
  76. m_invPath = invPath;
  77. m_loadStream = loadStream;
  78. }
  79. /// <summary>
  80. /// Execute the request
  81. /// </summary>
  82. /// <returns>
  83. /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are
  84. /// returned
  85. /// </returns>
  86. public List<InventoryNodeBase> Execute()
  87. {
  88. string filePath = "ERROR";
  89. int successfulAssetRestores = 0;
  90. int failedAssetRestores = 0;
  91. int successfulItemRestores = 0;
  92. List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
  93. //InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath);
  94. InventoryFolderBase rootDestinationFolder
  95. = InventoryArchiveUtils.FindFolderByPath(
  96. m_scene.InventoryService, m_userInfo.UserProfile.ID, m_invPath);
  97. if (null == rootDestinationFolder)
  98. {
  99. // Possibly provide an option later on to automatically create this folder if it does not exist
  100. m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath);
  101. return nodesLoaded;
  102. }
  103. archive = new TarArchiveReader(m_loadStream);
  104. // In order to load identically named folders, we need to keep track of the folders that we have already
  105. // created
  106. Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>();
  107. byte[] data;
  108. TarArchiveReader.TarEntryType entryType;
  109. try
  110. {
  111. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  112. {
  113. if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
  114. {
  115. if (LoadAsset(filePath, data))
  116. successfulAssetRestores++;
  117. else
  118. failedAssetRestores++;
  119. if ((successfulAssetRestores) % 50 == 0)
  120. m_log.DebugFormat(
  121. "[INVENTORY ARCHIVER]: Loaded {0} assets...",
  122. successfulAssetRestores);
  123. }
  124. else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH))
  125. {
  126. InventoryFolderBase foundFolder
  127. = ReplicateArchivePathToUserInventory(
  128. filePath, TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType,
  129. rootDestinationFolder, foldersCreated, nodesLoaded);
  130. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
  131. {
  132. InventoryItemBase item = LoadItem(data, foundFolder);
  133. if (item != null)
  134. {
  135. successfulItemRestores++;
  136. // If we're loading an item directly into the given destination folder then we need to record
  137. // it separately from any loaded root folders
  138. if (rootDestinationFolder == foundFolder)
  139. nodesLoaded.Add(item);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. finally
  146. {
  147. archive.Close();
  148. }
  149. m_log.DebugFormat(
  150. "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures",
  151. successfulAssetRestores, failedAssetRestores);
  152. m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores);
  153. return nodesLoaded;
  154. }
  155. public void Close()
  156. {
  157. if (m_loadStream != null)
  158. m_loadStream.Close();
  159. }
  160. /// <summary>
  161. /// Replicate the inventory paths in the archive to the user's inventory as necessary.
  162. /// </summary>
  163. /// <param name="archivePath">The item archive path to replicate</param>
  164. /// <param name="isDir">Is the path we're dealing with a directory?</param>
  165. /// <param name="rootDestinationFolder">The root folder for the inventory load</param>
  166. /// <param name="foldersCreated">
  167. /// The folders created so far. This method will add more folders if necessary
  168. /// </param>
  169. /// <param name="nodesLoaded">
  170. /// Track the inventory nodes created. This is distinct from the folders created since for a particular folder
  171. /// chain, only the root node needs to be recorded
  172. /// </param>
  173. /// <returns>The last user inventory folder created or found for the archive path</returns>
  174. public InventoryFolderBase ReplicateArchivePathToUserInventory(
  175. string archivePath,
  176. bool isDir,
  177. InventoryFolderBase rootDestFolder,
  178. Dictionary <string, InventoryFolderBase> foldersCreated,
  179. List<InventoryNodeBase> nodesLoaded)
  180. {
  181. archivePath = archivePath.Substring(ArchiveConstants.INVENTORY_PATH.Length);
  182. // Remove the file portion if we aren't already dealing with a directory path
  183. if (!isDir)
  184. archivePath = archivePath.Remove(archivePath.LastIndexOf("/") + 1);
  185. string originalArchivePath = archivePath;
  186. // m_log.DebugFormat(
  187. // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID);
  188. InventoryFolderBase destFolder = null;
  189. // XXX: Nasty way of dealing with a path that has no directory component
  190. if (archivePath.Length > 0)
  191. {
  192. while (null == destFolder && archivePath.Length > 0)
  193. {
  194. if (foldersCreated.ContainsKey(archivePath))
  195. {
  196. // m_log.DebugFormat(
  197. // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath);
  198. destFolder = foldersCreated[archivePath];
  199. }
  200. else
  201. {
  202. // Don't include the last slash
  203. int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2);
  204. if (penultimateSlashIndex >= 0)
  205. {
  206. archivePath = archivePath.Remove(penultimateSlashIndex + 1);
  207. }
  208. else
  209. {
  210. m_log.DebugFormat(
  211. "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}",
  212. originalArchivePath);
  213. archivePath = string.Empty;
  214. destFolder = rootDestFolder;
  215. }
  216. }
  217. }
  218. }
  219. else
  220. {
  221. destFolder = rootDestFolder;
  222. }
  223. string archivePathSectionToCreate = originalArchivePath.Substring(archivePath.Length);
  224. string[] rawDirsToCreate
  225. = archivePathSectionToCreate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  226. int i = 0;
  227. while (i < rawDirsToCreate.Length)
  228. {
  229. m_log.DebugFormat("[INVENTORY ARCHIVER]: Loading archived folder {0}", rawDirsToCreate[i]);
  230. int identicalNameIdentifierIndex
  231. = rawDirsToCreate[i].LastIndexOf(
  232. ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR);
  233. if (identicalNameIdentifierIndex < 0)
  234. {
  235. i++;
  236. continue;
  237. }
  238. string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex);
  239. newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName);
  240. UUID newFolderId = UUID.Random();
  241. // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be
  242. // deleted once the client has relogged.
  243. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client)
  244. // even though there is a AssetType.RootCategory
  245. destFolder
  246. = new InventoryFolderBase(
  247. newFolderId, newFolderName, m_userInfo.UserProfile.ID,
  248. (short)AssetType.Unknown, destFolder.ID, 1);
  249. m_scene.InventoryService.AddFolder(destFolder);
  250. // UUID newFolderId = UUID.Random();
  251. // m_scene.InventoryService.AddFolder(
  252. // m_userInfo.CreateFolder(
  253. // folderName, newFolderId, (ushort)AssetType.Folder, foundFolder.ID);
  254. // m_log.DebugFormat("[INVENTORY ARCHIVER]: Retrieving newly created folder {0}", folderName);
  255. // foundFolder = foundFolder.GetChildFolder(newFolderId);
  256. // m_log.DebugFormat(
  257. // "[INVENTORY ARCHIVER]: Retrieved newly created folder {0} with ID {1}",
  258. // foundFolder.Name, foundFolder.ID);
  259. // Record that we have now created this folder
  260. archivePath += rawDirsToCreate[i] + "/";
  261. m_log.DebugFormat("[INVENTORY ARCHIVER]: Loaded archive path {0}", archivePath);
  262. foldersCreated[archivePath] = destFolder;
  263. if (0 == i)
  264. nodesLoaded.Add(destFolder);
  265. i++;
  266. }
  267. return destFolder;
  268. /*
  269. string[] rawFolders = filePath.Split(new char[] { '/' });
  270. // Find the folders that do exist along the path given
  271. int i = 0;
  272. bool noFolder = false;
  273. InventoryFolderImpl foundFolder = rootDestinationFolder;
  274. while (!noFolder && i < rawFolders.Length)
  275. {
  276. InventoryFolderImpl folder = foundFolder.FindFolderByPath(rawFolders[i]);
  277. if (null != folder)
  278. {
  279. m_log.DebugFormat("[INVENTORY ARCHIVER]: Found folder {0}", folder.Name);
  280. foundFolder = folder;
  281. i++;
  282. }
  283. else
  284. {
  285. noFolder = true;
  286. }
  287. }
  288. // Create any folders that did not previously exist
  289. while (i < rawFolders.Length)
  290. {
  291. m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0}", rawFolders[i]);
  292. UUID newFolderId = UUID.Random();
  293. m_userInfo.CreateFolder(
  294. rawFolders[i++], newFolderId, (ushort)AssetType.Folder, foundFolder.ID);
  295. foundFolder = foundFolder.GetChildFolder(newFolderId);
  296. }
  297. */
  298. }
  299. /// <summary>
  300. /// Load an item from the archive
  301. /// </summary>
  302. /// <param name="filePath">The archive path for the item</param>
  303. /// <param name="data">The raw item data</param>
  304. /// <param name="rootDestinationFolder">The root destination folder for loaded items</param>
  305. /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param>
  306. protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder)
  307. {
  308. InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data);
  309. // Don't use the item ID that's in the file
  310. item.ID = UUID.Random();
  311. UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.CommsManager);
  312. if (UUID.Zero != ospResolvedId)
  313. {
  314. item.CreatorIdAsUuid = ospResolvedId;
  315. // XXX: For now, don't preserve the OSPA in the creator id (which actually gets persisted to the
  316. // database). Instead, replace with the UUID that we found.
  317. item.CreatorId = ospResolvedId.ToString();
  318. }
  319. else
  320. {
  321. item.CreatorIdAsUuid = m_userInfo.UserProfile.ID;
  322. }
  323. item.Owner = m_userInfo.UserProfile.ID;
  324. // Reset folder ID to the one in which we want to load it
  325. item.Folder = loadFolder.ID;
  326. //m_userInfo.AddItem(item);
  327. m_scene.InventoryService.AddItem(item);
  328. return item;
  329. }
  330. /// <summary>
  331. /// Load an asset
  332. /// </summary>
  333. /// <param name="assetFilename"></param>
  334. /// <param name="data"></param>
  335. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  336. private bool LoadAsset(string assetPath, byte[] data)
  337. {
  338. //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>();
  339. // Right now we're nastily obtaining the UUID from the filename
  340. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  341. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  342. if (i == -1)
  343. {
  344. m_log.ErrorFormat(
  345. "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  346. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  347. return false;
  348. }
  349. string extension = filename.Substring(i);
  350. string uuid = filename.Remove(filename.Length - extension.Length);
  351. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  352. {
  353. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  354. if (assetType == (sbyte)AssetType.Unknown)
  355. m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  356. //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  357. AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType);
  358. asset.Data = data;
  359. m_scene.AssetService.Store(asset);
  360. return true;
  361. }
  362. else
  363. {
  364. m_log.ErrorFormat(
  365. "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  366. assetPath, extension);
  367. return false;
  368. }
  369. }
  370. }
  371. }