ArchiveReadRequest.cs 22 KB

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