ArchiveReadRequest.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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.Region.CoreModules.World.Terrain;
  41. using OpenSim.Region.Framework.Interfaces;
  42. using OpenSim.Region.Framework.Scenes;
  43. using OpenSim.Region.Framework.Scenes.Serialization;
  44. using OpenSim.Services.Interfaces;
  45. using System.Threading;
  46. namespace OpenSim.Region.CoreModules.World.Archiver
  47. {
  48. /// <summary>
  49. /// Handles an individual archive read request
  50. /// </summary>
  51. public class ArchiveReadRequest
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. /// <summary>
  55. /// Contains data used while dearchiving a single scene.
  56. /// </summary>
  57. private class DearchiveContext
  58. {
  59. public Scene Scene { get; set; }
  60. public List<string> SerialisedSceneObjects { get; set; }
  61. public List<string> SerialisedParcels { get; set; }
  62. public List<SceneObjectGroup> SceneObjects { get; set; }
  63. public DearchiveContext(Scene scene)
  64. {
  65. Scene = scene;
  66. SerialisedSceneObjects = new List<string>();
  67. SerialisedParcels = new List<string>();
  68. SceneObjects = new List<SceneObjectGroup>();
  69. }
  70. }
  71. /// <summary>
  72. /// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version
  73. /// bumps here should be compatible.
  74. /// </summary>
  75. public static int MAX_MAJOR_VERSION = 1;
  76. /// <summary>
  77. /// Has the control file been loaded for this archive?
  78. /// </summary>
  79. public bool ControlFileLoaded { get; private set; }
  80. protected string m_loadPath;
  81. protected Scene m_rootScene;
  82. protected Stream m_loadStream;
  83. protected Guid m_requestId;
  84. protected string m_errorMessage;
  85. /// <value>
  86. /// Should the archive being loaded be merged with what is already on the region?
  87. /// Merging usually suppresses terrain and parcel loading
  88. /// </value>
  89. protected bool m_merge;
  90. /// <value>
  91. /// If true, force the loading of terrain from the oar file
  92. /// </value>
  93. protected bool m_forceTerrain;
  94. /// <value>
  95. /// If true, force the loading of parcels from the oar file
  96. /// </value>
  97. protected bool m_forceParcels;
  98. /// <value>
  99. /// Should we ignore any assets when reloading the archive?
  100. /// </value>
  101. protected bool m_skipAssets;
  102. /// <value>
  103. /// Displacement added to each object as it is added to the world
  104. /// </value>
  105. protected Vector3 m_displacement = Vector3.Zero;
  106. /// <value>
  107. /// Rotation (in radians) to apply to the objects as they are loaded.
  108. /// </value>
  109. protected float m_rotation = 0f;
  110. /// <value>
  111. /// Center around which to apply the rotation relative to the origional oar position
  112. /// </value>
  113. protected Vector3 m_rotationCenter = new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 2f, 0f);
  114. /// <summary>
  115. /// Used to cache lookups for valid uuids.
  116. /// </summary>
  117. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  118. private IUserManagement m_UserMan;
  119. private IUserManagement UserManager
  120. {
  121. get
  122. {
  123. if (m_UserMan == null)
  124. {
  125. m_UserMan = m_rootScene.RequestModuleInterface<IUserManagement>();
  126. }
  127. return m_UserMan;
  128. }
  129. }
  130. /// <summary>
  131. /// Used to cache lookups for valid groups.
  132. /// </summary>
  133. private IDictionary<UUID, bool> m_validGroupUuids = new Dictionary<UUID, bool>();
  134. private IGroupsModule m_groupsModule;
  135. private IAssetService m_assetService = null;
  136. public ArchiveReadRequest(Scene scene, string loadPath, Guid requestId, Dictionary<string,object>options)
  137. {
  138. m_rootScene = scene;
  139. m_loadPath = loadPath;
  140. try
  141. {
  142. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
  143. }
  144. catch (EntryPointNotFoundException e)
  145. {
  146. m_log.ErrorFormat(
  147. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  148. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  149. m_log.Error(e);
  150. }
  151. m_errorMessage = String.Empty;
  152. m_merge = options.ContainsKey("merge");
  153. m_forceTerrain = options.ContainsKey("force-terrain");
  154. m_forceParcels = options.ContainsKey("force-parcels");
  155. m_skipAssets = options.ContainsKey("skipAssets");
  156. m_requestId = requestId;
  157. m_displacement = options.ContainsKey("displacement") ? (Vector3)options["displacement"] : Vector3.Zero;
  158. m_rotation = options.ContainsKey("rotation") ? (float)options["rotation"] : 0f;
  159. m_rotationCenter = options.ContainsKey("rotation-center") ? (Vector3)options["rotation-center"]
  160. : new Vector3(scene.RegionInfo.RegionSizeX / 2f, scene.RegionInfo.RegionSizeY / 2f, 0f);
  161. // Zero can never be a valid user id
  162. m_validUserUuids[UUID.Zero] = false;
  163. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  164. m_assetService = m_rootScene.AssetService;
  165. }
  166. public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object>options)
  167. {
  168. m_rootScene = scene;
  169. m_loadPath = null;
  170. m_loadStream = loadStream;
  171. m_skipAssets = options.ContainsKey("skipAssets");
  172. m_merge = options.ContainsKey("merge");
  173. m_requestId = requestId;
  174. // Zero can never be a valid user id
  175. m_validUserUuids[UUID.Zero] = false;
  176. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  177. m_assetService = m_rootScene.AssetService;
  178. }
  179. /// <summary>
  180. /// Dearchive the region embodied in this request.
  181. /// </summary>
  182. public void DearchiveRegion()
  183. {
  184. int successfulAssetRestores = 0;
  185. int failedAssetRestores = 0;
  186. DearchiveScenesInfo dearchivedScenes;
  187. // We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
  188. // Therefore, we have to keep track of the dearchive context of all the scenes.
  189. Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();
  190. string fullPath = "NONE";
  191. TarArchiveReader archive = null;
  192. byte[] data;
  193. TarArchiveReader.TarEntryType entryType;
  194. try
  195. {
  196. FindAndLoadControlFile(out archive, out dearchivedScenes);
  197. while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
  198. {
  199. //m_log.DebugFormat(
  200. // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
  201. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  202. continue;
  203. // Find the scene that this file belongs to
  204. Scene scene;
  205. string filePath;
  206. if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
  207. continue; // this file belongs to a region that we're not loading
  208. DearchiveContext sceneContext = null;
  209. if (scene != null)
  210. {
  211. if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
  212. {
  213. sceneContext = new DearchiveContext(scene);
  214. sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
  215. }
  216. }
  217. // Process the file
  218. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
  219. {
  220. sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
  221. }
  222. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
  223. {
  224. if (LoadAsset(filePath, data))
  225. successfulAssetRestores++;
  226. else
  227. failedAssetRestores++;
  228. if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
  229. m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
  230. }
  231. else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_forceTerrain))
  232. {
  233. LoadTerrain(scene, filePath, data);
  234. }
  235. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  236. {
  237. LoadRegionSettings(scene, filePath, data, dearchivedScenes);
  238. }
  239. else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_forceParcels))
  240. {
  241. sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
  242. }
  243. else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  244. {
  245. // Ignore, because we already read the control file
  246. }
  247. }
  248. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  249. }
  250. catch (Exception e)
  251. {
  252. m_log.Error(
  253. String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
  254. m_errorMessage += e.ToString();
  255. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  256. return;
  257. }
  258. finally
  259. {
  260. if (archive != null)
  261. archive.Close();
  262. }
  263. if (!m_skipAssets)
  264. {
  265. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  266. if (failedAssetRestores > 0)
  267. {
  268. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  269. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  270. }
  271. }
  272. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  273. {
  274. m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);
  275. if (!m_merge)
  276. {
  277. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  278. sceneContext.Scene.DeleteAllSceneObjects();
  279. }
  280. try
  281. {
  282. LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
  283. LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
  284. // Inform any interested parties that the region has changed. We waited until now so that all
  285. // of the region's objects will be loaded when we send this notification.
  286. IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
  287. if (estateModule != null)
  288. estateModule.TriggerRegionInfoChange();
  289. }
  290. catch (Exception e)
  291. {
  292. m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
  293. m_errorMessage += e.ToString();
  294. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  295. return;
  296. }
  297. }
  298. // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
  299. // that users can enter the scene. If we allow the scripts to start in the loop above
  300. // then they significantly increase the time until the OAR finishes loading.
  301. Util.FireAndForget(delegate(object o)
  302. {
  303. Thread.Sleep(15000);
  304. m_log.Info("[ARCHIVER]: Starting scripts in scene objects");
  305. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  306. {
  307. foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
  308. {
  309. sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
  310. sceneObject.ResumeScripts();
  311. }
  312. sceneContext.SceneObjects.Clear();
  313. }
  314. });
  315. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  316. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage);
  317. }
  318. /// <summary>
  319. /// Searches through the files in the archive for the control file, and reads it.
  320. /// We must read the control file first, in order to know which regions are available.
  321. /// </summary>
  322. /// <remarks>
  323. /// In most cases the control file *is* first, since that's how we create archives. However,
  324. /// it's possible that someone rewrote the archive externally so we can't rely on this fact.
  325. /// </remarks>
  326. /// <param name="archive"></param>
  327. /// <param name="dearchivedScenes"></param>
  328. private void FindAndLoadControlFile(out TarArchiveReader archive, out DearchiveScenesInfo dearchivedScenes)
  329. {
  330. archive = new TarArchiveReader(m_loadStream);
  331. dearchivedScenes = new DearchiveScenesInfo();
  332. string filePath;
  333. byte[] data;
  334. TarArchiveReader.TarEntryType entryType;
  335. bool firstFile = true;
  336. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  337. {
  338. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  339. continue;
  340. if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  341. {
  342. LoadControlFile(filePath, data, dearchivedScenes);
  343. // Find which scenes are available in the simulator
  344. ArchiveScenesGroup simulatorScenes = new ArchiveScenesGroup();
  345. SceneManager.Instance.ForEachScene(delegate(Scene scene2)
  346. {
  347. simulatorScenes.AddScene(scene2);
  348. });
  349. simulatorScenes.CalcSceneLocations();
  350. dearchivedScenes.SetSimulatorScenes(m_rootScene, simulatorScenes);
  351. // If the control file wasn't the first file then reset the read pointer
  352. if (!firstFile)
  353. {
  354. m_log.Warn("Control file wasn't the first file in the archive");
  355. if (m_loadStream.CanSeek)
  356. {
  357. m_loadStream.Seek(0, SeekOrigin.Begin);
  358. }
  359. else if (m_loadPath != null)
  360. {
  361. archive.Close();
  362. archive = null;
  363. m_loadStream.Close();
  364. m_loadStream = null;
  365. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(m_loadPath), CompressionMode.Decompress);
  366. archive = new TarArchiveReader(m_loadStream);
  367. }
  368. else
  369. {
  370. // There isn't currently a scenario where this happens, but it's best to add a check just in case
  371. throw new Exception("Error reading archive: control file wasn't the first file, and the input stream doesn't allow seeking");
  372. }
  373. }
  374. return;
  375. }
  376. firstFile = false;
  377. }
  378. throw new Exception("Control file not found");
  379. }
  380. /// <summary>
  381. /// Load serialized scene objects.
  382. /// </summary>
  383. protected void LoadObjects(Scene scene, List<string> serialisedSceneObjects, List<SceneObjectGroup> sceneObjects)
  384. {
  385. // Reload serialized prims
  386. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  387. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, m_rotation);
  388. UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject;
  389. IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
  390. int sceneObjectsLoadedCount = 0;
  391. foreach (string serialisedSceneObject in serialisedSceneObjects)
  392. {
  393. /*
  394. m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
  395. // Really large xml files (multi megabyte) appear to cause
  396. // memory problems
  397. // when loading the xml. But don't enable this check yet
  398. if (serialisedSceneObject.Length > 5000000)
  399. {
  400. m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
  401. continue;
  402. }
  403. */
  404. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  405. // Happily this does not do much to the object since it hasn't been added to the scene yet
  406. if (sceneObject.AttachmentPoint == 0)
  407. {
  408. if (m_displacement != Vector3.Zero || m_rotation != 0f)
  409. {
  410. Vector3 pos = sceneObject.AbsolutePosition;
  411. if (m_rotation != 0f)
  412. {
  413. // Rotate the object
  414. sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation;
  415. // Get object position relative to rotation axis
  416. Vector3 offset = pos - m_rotationCenter;
  417. // Rotate the object position
  418. offset *= rot;
  419. // Restore the object position back to relative to the region
  420. pos = m_rotationCenter + offset;
  421. }
  422. if (m_displacement != Vector3.Zero)
  423. {
  424. pos += m_displacement;
  425. }
  426. sceneObject.AbsolutePosition = pos;
  427. }
  428. }
  429. bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
  430. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  431. // on the same region server and multiple examples a single object archive to be imported
  432. // to the same scene (when this is possible).
  433. sceneObject.ResetIDs();
  434. if (isTelehub)
  435. {
  436. // Change the Telehub Object to the new UUID
  437. scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
  438. scene.RegionInfo.RegionSettings.Save();
  439. oldTelehubUUID = UUID.Zero;
  440. }
  441. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  442. // or creator data is present. Otherwise, use the estate owner instead.
  443. foreach (SceneObjectPart part in sceneObject.Parts)
  444. {
  445. if (string.IsNullOrEmpty(part.CreatorData))
  446. {
  447. if (!ResolveUserUuid(scene, part.CreatorID))
  448. part.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner;
  449. }
  450. if (UserManager != null)
  451. UserManager.AddUser(part.CreatorID, part.CreatorData);
  452. if (!ResolveUserUuid(scene, part.OwnerID))
  453. part.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  454. if (!ResolveUserUuid(scene, part.LastOwnerID))
  455. part.LastOwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  456. if (!ResolveGroupUuid(part.GroupID))
  457. part.GroupID = UUID.Zero;
  458. // And zap any troublesome sit target information
  459. // part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  460. // part.SitTargetPosition = new Vector3(0, 0, 0);
  461. // Fix ownership/creator of inventory items
  462. // Not doing so results in inventory items
  463. // being no copy/no mod for everyone
  464. lock (part.TaskInventory)
  465. {
  466. TaskInventoryDictionary inv = part.TaskInventory;
  467. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  468. {
  469. if (!ResolveUserUuid(scene, kvp.Value.OwnerID))
  470. {
  471. kvp.Value.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  472. }
  473. if (string.IsNullOrEmpty(kvp.Value.CreatorData))
  474. {
  475. if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
  476. kvp.Value.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner;
  477. }
  478. if (UserManager != null)
  479. UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
  480. if (!ResolveGroupUuid(kvp.Value.GroupID))
  481. kvp.Value.GroupID = UUID.Zero;
  482. }
  483. }
  484. }
  485. if (scene.AddRestoredSceneObject(sceneObject, true, false))
  486. {
  487. sceneObjectsLoadedCount++;
  488. sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
  489. sceneObject.ResumeScripts();
  490. }
  491. }
  492. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
  493. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
  494. if (ignoredObjects > 0)
  495. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  496. if (oldTelehubUUID != UUID.Zero)
  497. {
  498. m_log.WarnFormat("Telehub object not found: {0}", oldTelehubUUID);
  499. scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
  500. scene.RegionInfo.RegionSettings.ClearSpawnPoints();
  501. }
  502. }
  503. /// <summary>
  504. /// Load serialized parcels.
  505. /// </summary>
  506. /// <param name="scene"></param>
  507. /// <param name="serialisedParcels"></param>
  508. protected void LoadParcels(Scene scene, List<string> serialisedParcels)
  509. {
  510. // Reload serialized parcels
  511. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  512. List<LandData> landData = new List<LandData>();
  513. foreach (string serialisedParcel in serialisedParcels)
  514. {
  515. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  516. if (m_displacement != Vector3.Zero)
  517. {
  518. Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
  519. parcel.AABBMin += parcelDisp;
  520. parcel.AABBMax += parcelDisp;
  521. }
  522. // Validate User and Group UUID's
  523. if (parcel.IsGroupOwned)
  524. {
  525. if (!ResolveGroupUuid(parcel.GroupID))
  526. {
  527. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  528. parcel.GroupID = UUID.Zero;
  529. parcel.IsGroupOwned = false;
  530. }
  531. }
  532. else
  533. {
  534. if (!ResolveUserUuid(scene, parcel.OwnerID))
  535. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  536. if (!ResolveGroupUuid(parcel.GroupID))
  537. parcel.GroupID = UUID.Zero;
  538. }
  539. List<LandAccessEntry> accessList = new List<LandAccessEntry>();
  540. foreach (LandAccessEntry entry in parcel.ParcelAccessList)
  541. {
  542. if (ResolveUserUuid(scene, entry.AgentID))
  543. accessList.Add(entry);
  544. // else, drop this access rule
  545. }
  546. parcel.ParcelAccessList = accessList;
  547. // m_log.DebugFormat(
  548. // "[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
  549. // parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
  550. landData.Add(parcel);
  551. }
  552. if (!m_merge)
  553. {
  554. bool setupDefaultParcel = (landData.Count == 0);
  555. scene.LandChannel.Clear(setupDefaultParcel);
  556. }
  557. scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  558. m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
  559. }
  560. /// <summary>
  561. /// Look up the given user id to check whether it's one that is valid for this grid.
  562. /// </summary>
  563. /// <param name="scene"></param>
  564. /// <param name="uuid"></param>
  565. /// <returns></returns>
  566. private bool ResolveUserUuid(Scene scene, UUID uuid)
  567. {
  568. lock (m_validUserUuids)
  569. {
  570. if (!m_validUserUuids.ContainsKey(uuid))
  571. {
  572. // Note: we call GetUserAccount() inside the lock because this UserID is likely
  573. // to occur many times, and we only want to query the users service once.
  574. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
  575. m_validUserUuids.Add(uuid, account != null);
  576. }
  577. return m_validUserUuids[uuid];
  578. }
  579. }
  580. /// <summary>
  581. /// Look up the given group id to check whether it's one that is valid for this grid.
  582. /// </summary>
  583. /// <param name="uuid"></param>
  584. /// <returns></returns>
  585. private bool ResolveGroupUuid(UUID uuid)
  586. {
  587. if (uuid == UUID.Zero)
  588. return true; // this means the object has no group
  589. lock (m_validGroupUuids)
  590. {
  591. if (!m_validGroupUuids.ContainsKey(uuid))
  592. {
  593. bool exists;
  594. if (m_groupsModule == null)
  595. {
  596. exists = false;
  597. }
  598. else
  599. {
  600. // Note: we call GetGroupRecord() inside the lock because this GroupID is likely
  601. // to occur many times, and we only want to query the groups service once.
  602. exists = (m_groupsModule.GetGroupRecord(uuid) != null);
  603. }
  604. m_validGroupUuids.Add(uuid, exists);
  605. }
  606. return m_validGroupUuids[uuid];
  607. }
  608. }
  609. /// Load an asset
  610. /// </summary>
  611. /// <param name="assetFilename"></param>
  612. /// <param name="data"></param>
  613. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  614. private bool LoadAsset(string assetPath, byte[] data)
  615. {
  616. // Right now we're nastily obtaining the UUID from the filename
  617. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  618. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  619. if (i == -1)
  620. {
  621. m_log.ErrorFormat(
  622. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  623. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  624. return false;
  625. }
  626. string extension = filename.Substring(i);
  627. string uuid = filename.Remove(filename.Length - extension.Length);
  628. if (m_assetService.GetMetadata(uuid) != null)
  629. {
  630. // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
  631. return true;
  632. }
  633. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  634. {
  635. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  636. if (assetType == (sbyte)AssetType.Unknown)
  637. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  638. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  639. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  640. asset.Data = data;
  641. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  642. // exists.
  643. m_assetService.Store(asset);
  644. /**
  645. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  646. * it might be best done when dearchive takes place on a separate thread
  647. if (asset.Type=AssetType.Texture)
  648. {
  649. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  650. if (cacheLayerDecode != null)
  651. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  652. }
  653. */
  654. return true;
  655. }
  656. else
  657. {
  658. m_log.ErrorFormat(
  659. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  660. assetPath, extension);
  661. return false;
  662. }
  663. }
  664. /// <summary>
  665. /// Load region settings data
  666. /// </summary>
  667. /// <param name="scene"></param>
  668. /// <param name="settingsPath"></param>
  669. /// <param name="data"></param>
  670. /// <param name="dearchivedScenes"></param>
  671. /// <returns>
  672. /// true if settings were loaded successfully, false otherwise
  673. /// </returns>
  674. private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
  675. {
  676. RegionSettings loadedRegionSettings;
  677. try
  678. {
  679. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  680. }
  681. catch (Exception e)
  682. {
  683. m_log.ErrorFormat(
  684. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  685. settingsPath, e);
  686. return false;
  687. }
  688. RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
  689. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  690. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  691. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  692. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  693. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  694. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  695. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  696. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  697. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  698. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  699. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  700. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  701. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  702. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  703. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  704. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  705. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  706. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  707. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  708. currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
  709. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  710. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  711. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  712. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  713. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  714. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  715. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  716. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  717. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  718. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  719. currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
  720. currentRegionSettings.ClearSpawnPoints();
  721. foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
  722. currentRegionSettings.AddSpawnPoint(sp);
  723. currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
  724. currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
  725. currentRegionSettings.Save();
  726. scene.TriggerEstateSunUpdate();
  727. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  728. if (estateModule != null)
  729. estateModule.sendRegionHandshakeToAll();
  730. return true;
  731. }
  732. /// <summary>
  733. /// Load terrain data
  734. /// </summary>
  735. /// <param name="scene"></param>
  736. /// <param name="terrainPath"></param>
  737. /// <param name="data"></param>
  738. /// <returns>
  739. /// true if terrain was resolved successfully, false otherwise.
  740. /// </returns>
  741. private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
  742. {
  743. ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
  744. MemoryStream ms = new MemoryStream(data);
  745. if (m_displacement != Vector3.Zero || m_rotation != 0f)
  746. {
  747. Vector2 rotationCenter = new Vector2(m_rotationCenter.X, m_rotationCenter.Y);
  748. terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, rotationCenter, ms);
  749. }
  750. else
  751. {
  752. terrainModule.LoadFromStream(terrainPath, ms);
  753. }
  754. ms.Close();
  755. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  756. return true;
  757. }
  758. /// <summary>
  759. /// Load oar control file
  760. /// </summary>
  761. /// <param name="path"></param>
  762. /// <param name="data"></param>
  763. /// <param name="dearchivedScenes"></param>
  764. public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
  765. {
  766. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
  767. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  768. XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  769. // Loaded metadata will be empty if no information exists in the archive
  770. dearchivedScenes.LoadedCreationDateTime = 0;
  771. dearchivedScenes.DefaultOriginalID = "";
  772. bool multiRegion = false;
  773. while (xtr.Read())
  774. {
  775. if (xtr.NodeType == XmlNodeType.Element)
  776. {
  777. if (xtr.Name.ToString() == "archive")
  778. {
  779. int majorVersion = int.Parse(xtr["major_version"]);
  780. int minorVersion = int.Parse(xtr["minor_version"]);
  781. string version = string.Format("{0}.{1}", majorVersion, minorVersion);
  782. if (majorVersion > MAX_MAJOR_VERSION)
  783. {
  784. throw new Exception(
  785. string.Format(
  786. "The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below",
  787. majorVersion, MAX_MAJOR_VERSION));
  788. }
  789. m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
  790. }
  791. if (xtr.Name.ToString() == "datetime")
  792. {
  793. int value;
  794. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  795. dearchivedScenes.LoadedCreationDateTime = value;
  796. }
  797. else if (xtr.Name.ToString() == "row")
  798. {
  799. multiRegion = true;
  800. dearchivedScenes.StartRow();
  801. }
  802. else if (xtr.Name.ToString() == "region")
  803. {
  804. dearchivedScenes.StartRegion();
  805. }
  806. else if (xtr.Name.ToString() == "id")
  807. {
  808. string id = xtr.ReadElementContentAsString();
  809. dearchivedScenes.DefaultOriginalID = id;
  810. if (multiRegion)
  811. dearchivedScenes.SetRegionOriginalID(id);
  812. }
  813. else if (xtr.Name.ToString() == "dir")
  814. {
  815. dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
  816. }
  817. }
  818. }
  819. dearchivedScenes.MultiRegionFormat = multiRegion;
  820. if (!multiRegion)
  821. {
  822. // Add the single scene
  823. dearchivedScenes.StartRow();
  824. dearchivedScenes.StartRegion();
  825. dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
  826. dearchivedScenes.SetRegionDirectory("");
  827. }
  828. ControlFileLoaded = true;
  829. return dearchivedScenes;
  830. }
  831. }
  832. }