ArchiveReadRequest.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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.Generic;
  29. using System.IO;
  30. using System.IO.Compression;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Text;
  34. using log4net;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Communications.Cache;
  38. using OpenSim.Region.CoreModules.World.Terrain;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. namespace OpenSim.Region.CoreModules.World.Archiver
  42. {
  43. /// <summary>
  44. /// Handles an individual archive read request
  45. /// </summary>
  46. public class ArchiveReadRequest
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding();
  50. private Scene m_scene;
  51. private Stream m_loadStream;
  52. private string m_errorMessage;
  53. /// <value>
  54. /// Should the archive being loaded be merged with what is already on the region?
  55. /// </value>
  56. private bool m_merge;
  57. /// <summary>
  58. /// Used to cache lookups for valid uuids.
  59. /// </summary>
  60. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  61. public ArchiveReadRequest(Scene scene, string loadPath, bool merge)
  62. {
  63. m_scene = scene;
  64. m_loadStream = new GZipStream(GetStream(loadPath), CompressionMode.Decompress);
  65. m_errorMessage = String.Empty;
  66. m_merge = merge;
  67. }
  68. public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge)
  69. {
  70. m_scene = scene;
  71. m_loadStream = loadStream;
  72. m_merge = merge;
  73. }
  74. /// <summary>
  75. /// Dearchive the region embodied in this request.
  76. /// </summary>
  77. public void DearchiveRegion()
  78. {
  79. // The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions
  80. DearchiveRegion0DotStar();
  81. }
  82. private void DearchiveRegion0DotStar()
  83. {
  84. int successfulAssetRestores = 0;
  85. int failedAssetRestores = 0;
  86. List<string> serialisedSceneObjects = new List<string>();
  87. try
  88. {
  89. TarArchiveReader archive = new TarArchiveReader(m_loadStream);
  90. string filePath = "ERROR";
  91. byte[] data;
  92. TarArchiveReader.TarEntryType entryType;
  93. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  94. {
  95. //m_log.DebugFormat(
  96. // "[ARCHIVER]: Successfully read {0} ({1} bytes)}", filePath, data.Length);
  97. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  98. {
  99. m_log.WarnFormat(
  100. "[ARCHIVER]: Ignoring directory entry {0}", filePath);
  101. }
  102. else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
  103. {
  104. serialisedSceneObjects.Add(m_asciiEncoding.GetString(data));
  105. }
  106. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
  107. {
  108. if (LoadAsset(filePath, data))
  109. successfulAssetRestores++;
  110. else
  111. failedAssetRestores++;
  112. }
  113. else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
  114. {
  115. LoadTerrain(filePath, data);
  116. }
  117. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  118. {
  119. LoadRegionSettings(filePath, data);
  120. }
  121. }
  122. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  123. archive.Close();
  124. }
  125. catch (Exception e)
  126. {
  127. m_log.ErrorFormat(
  128. "[ARCHIVER]: Error loading oar file. Exception was: {0}", e);
  129. m_errorMessage += e.ToString();
  130. m_scene.EventManager.TriggerOarFileLoaded(m_errorMessage);
  131. return;
  132. }
  133. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  134. if (failedAssetRestores > 0)
  135. {
  136. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  137. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  138. }
  139. if (!m_merge)
  140. {
  141. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  142. m_scene.DeleteAllSceneObjects();
  143. }
  144. // Reload serialized prims
  145. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  146. IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>();
  147. ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
  148. foreach (string serialisedSceneObject in serialisedSceneObjects)
  149. {
  150. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  151. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  152. // on the same region server and multiple examples a single object archive to be imported
  153. // to the same scene (when this is possible).
  154. sceneObject.ResetIDs();
  155. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  156. // otherwise, use the master avatar uuid instead
  157. UUID masterAvatarId = m_scene.RegionInfo.MasterAvatarAssignedUUID;
  158. if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
  159. masterAvatarId = m_scene.RegionInfo.EstateSettings.EstateOwner;
  160. foreach (SceneObjectPart part in sceneObject.Children.Values)
  161. {
  162. if (!ResolveUserUuid(part.CreatorID))
  163. part.CreatorID = masterAvatarId;
  164. if (!ResolveUserUuid(part.OwnerID))
  165. part.OwnerID = masterAvatarId;
  166. if (!ResolveUserUuid(part.LastOwnerID))
  167. part.LastOwnerID = masterAvatarId;
  168. // And zap any troublesome sit target information
  169. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  170. part.SitTargetPosition = new Vector3(0, 0, 0);
  171. // Fix ownership/creator of inventory items
  172. // Not doing so results in inventory items
  173. // being no copy/no mod for everyone
  174. lock (part.TaskInventory)
  175. {
  176. TaskInventoryDictionary inv = part.TaskInventory;
  177. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  178. {
  179. if (!ResolveUserUuid(kvp.Value.OwnerID))
  180. {
  181. kvp.Value.OwnerID = masterAvatarId;
  182. }
  183. if (!ResolveUserUuid(kvp.Value.CreatorID))
  184. {
  185. kvp.Value.CreatorID = masterAvatarId;
  186. }
  187. }
  188. }
  189. }
  190. if (m_scene.AddRestoredSceneObject(sceneObject, true, false))
  191. {
  192. sceneObjects.Add(sceneObject);
  193. }
  194. }
  195. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjects.Count);
  196. int ignoredObjects = serialisedSceneObjects.Count - sceneObjects.Count;
  197. if (ignoredObjects > 0)
  198. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  199. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  200. m_log.Debug("[ARCHIVER]: Starting scripts");
  201. foreach (SceneObjectGroup sceneObject in sceneObjects)
  202. {
  203. sceneObject.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 0);
  204. }
  205. m_scene.EventManager.TriggerOarFileLoaded(m_errorMessage);
  206. }
  207. /// <summary>
  208. /// Look up the given user id to check whether it's one that is valid for this grid.
  209. /// </summary>
  210. /// <param name="uuid"></param>
  211. /// <returns></returns>
  212. private bool ResolveUserUuid(UUID uuid)
  213. {
  214. if (!m_validUserUuids.ContainsKey(uuid))
  215. {
  216. CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(uuid);
  217. if (profile != null && profile.UserProfile != null)
  218. m_validUserUuids.Add(uuid, true);
  219. else
  220. m_validUserUuids.Add(uuid, false);
  221. }
  222. if (m_validUserUuids[uuid])
  223. return true;
  224. else
  225. return false;
  226. }
  227. /// <summary>
  228. /// Load an asset
  229. /// </summary>
  230. /// <param name="assetFilename"></param>
  231. /// <param name="data"></param>
  232. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  233. private bool LoadAsset(string assetPath, byte[] data)
  234. {
  235. // Right now we're nastily obtaining the UUID from the filename
  236. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  237. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  238. if (i == -1)
  239. {
  240. m_log.ErrorFormat(
  241. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  242. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  243. return false;
  244. }
  245. string extension = filename.Substring(i);
  246. string uuid = filename.Remove(filename.Length - extension.Length);
  247. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  248. {
  249. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  250. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  251. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty);
  252. asset.Type = assetType;
  253. asset.Data = data;
  254. m_scene.CommsManager.AssetCache.AddAsset(asset);
  255. /**
  256. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  257. * it might be best done when dearchive takes place on a separate thread
  258. if (asset.Type=AssetType.Texture)
  259. {
  260. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  261. if (cacheLayerDecode != null)
  262. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  263. }
  264. */
  265. return true;
  266. }
  267. else
  268. {
  269. m_log.ErrorFormat(
  270. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  271. assetPath, extension);
  272. return false;
  273. }
  274. }
  275. /// <summary>
  276. /// Load region settings data
  277. /// </summary>
  278. /// <param name="settingsPath"></param>
  279. /// <param name="data"></param>
  280. /// <returns>
  281. /// true if settings were loaded successfully, false otherwise
  282. /// </returns>
  283. private bool LoadRegionSettings(string settingsPath, byte[] data)
  284. {
  285. RegionSettings loadedRegionSettings;
  286. try
  287. {
  288. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  289. }
  290. catch (Exception e)
  291. {
  292. m_log.ErrorFormat(
  293. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  294. settingsPath, e);
  295. return false;
  296. }
  297. RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
  298. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  299. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  300. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  301. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  302. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  303. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  304. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  305. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  306. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  307. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  308. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  309. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  310. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  311. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  312. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  313. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  314. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  315. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  316. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  317. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  318. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  319. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  320. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  321. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  322. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  323. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  324. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  325. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  326. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  327. IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
  328. estateModule.sendRegionHandshakeToAll();
  329. return true;
  330. }
  331. /// <summary>
  332. /// Load terrain data
  333. /// </summary>
  334. /// <param name="terrainPath"></param>
  335. /// <param name="data"></param>
  336. /// <returns>
  337. /// true if terrain was resolved successfully, false otherwise.
  338. /// </returns>
  339. private bool LoadTerrain(string terrainPath, byte[] data)
  340. {
  341. ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
  342. MemoryStream ms = new MemoryStream(data);
  343. terrainModule.LoadFromStream(terrainPath, ms);
  344. ms.Close();
  345. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  346. return true;
  347. }
  348. /// <summary>
  349. /// Resolve path to a working FileStream
  350. /// </summary>
  351. private Stream GetStream(string path)
  352. {
  353. try
  354. {
  355. if (File.Exists(path))
  356. {
  357. return new FileStream(path, FileMode.Open);
  358. }
  359. else
  360. {
  361. Uri uri = new Uri(path); // throw exception if not valid URI
  362. if (uri.Scheme == "file")
  363. {
  364. return new FileStream(uri.AbsolutePath, FileMode.Open);
  365. }
  366. else
  367. {
  368. if (uri.Scheme != "http")
  369. throw new Exception(String.Format("Unsupported URI scheme ({0})", path));
  370. // OK, now we know we have an HTTP URI to work with
  371. return URIFetch(uri);
  372. }
  373. }
  374. }
  375. catch (Exception e)
  376. {
  377. throw new Exception(String.Format("Unable to create file input stream for {0}: {1}", path, e));
  378. }
  379. }
  380. private static Stream URIFetch(Uri uri)
  381. {
  382. HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
  383. // request.Credentials = credentials;
  384. request.ContentLength = 0;
  385. WebResponse response = request.GetResponse();
  386. Stream file = response.GetResponseStream();
  387. if (response.ContentType != "application/x-oar")
  388. throw new Exception(String.Format("{0} does not identify an OAR file", uri.ToString()));
  389. if (response.ContentLength == 0)
  390. throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
  391. // return new BufferedStream(file, (int) response.ContentLength);
  392. return new BufferedStream(file, 1000000);
  393. }
  394. }
  395. }