ArchiveReadRequest.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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 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("forceTerrain");
  154. m_forceParcels = options.ContainsKey("forceParcels");
  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("rotationCenter") ? (Vector3)options["rotationCenter"]
  160. : new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 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. float angle = (float)(m_rotation / 180.0 * Math.PI);
  388. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle);
  389. UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject;
  390. IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
  391. int sceneObjectsLoadedCount = 0;
  392. foreach (string serialisedSceneObject in serialisedSceneObjects)
  393. {
  394. /*
  395. m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
  396. // Really large xml files (multi megabyte) appear to cause
  397. // memory problems
  398. // when loading the xml. But don't enable this check yet
  399. if (serialisedSceneObject.Length > 5000000)
  400. {
  401. m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
  402. continue;
  403. }
  404. */
  405. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  406. // Happily this does not do much to the object since it hasn't been added to the scene yet
  407. if (sceneObject.AttachmentPoint == 0)
  408. {
  409. if (angle != 0f)
  410. {
  411. sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation;
  412. Vector3 offset = sceneObject.AbsolutePosition - m_rotationCenter;
  413. offset *= rot;
  414. sceneObject.AbsolutePosition = m_rotationCenter + offset;
  415. }
  416. if (m_displacement != Vector3.Zero)
  417. {
  418. sceneObject.AbsolutePosition += m_displacement;
  419. }
  420. }
  421. bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
  422. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  423. // on the same region server and multiple examples a single object archive to be imported
  424. // to the same scene (when this is possible).
  425. sceneObject.ResetIDs();
  426. if (isTelehub)
  427. {
  428. // Change the Telehub Object to the new UUID
  429. scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
  430. scene.RegionInfo.RegionSettings.Save();
  431. oldTelehubUUID = UUID.Zero;
  432. }
  433. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  434. // or creator data is present. Otherwise, use the estate owner instead.
  435. foreach (SceneObjectPart part in sceneObject.Parts)
  436. {
  437. if (string.IsNullOrEmpty(part.CreatorData))
  438. {
  439. if (!ResolveUserUuid(scene, part.CreatorID))
  440. part.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner;
  441. }
  442. if (UserManager != null)
  443. UserManager.AddUser(part.CreatorID, part.CreatorData);
  444. if (!ResolveUserUuid(scene, part.OwnerID))
  445. part.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  446. if (!ResolveUserUuid(scene, part.LastOwnerID))
  447. part.LastOwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  448. if (!ResolveGroupUuid(part.GroupID))
  449. part.GroupID = UUID.Zero;
  450. // And zap any troublesome sit target information
  451. // part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  452. // part.SitTargetPosition = new Vector3(0, 0, 0);
  453. // Fix ownership/creator of inventory items
  454. // Not doing so results in inventory items
  455. // being no copy/no mod for everyone
  456. lock (part.TaskInventory)
  457. {
  458. TaskInventoryDictionary inv = part.TaskInventory;
  459. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  460. {
  461. if (!ResolveUserUuid(scene, kvp.Value.OwnerID))
  462. {
  463. kvp.Value.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  464. }
  465. if (string.IsNullOrEmpty(kvp.Value.CreatorData))
  466. {
  467. if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
  468. kvp.Value.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner;
  469. }
  470. if (UserManager != null)
  471. UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
  472. if (!ResolveGroupUuid(kvp.Value.GroupID))
  473. kvp.Value.GroupID = UUID.Zero;
  474. }
  475. }
  476. }
  477. if (scene.AddRestoredSceneObject(sceneObject, true, false))
  478. {
  479. sceneObjectsLoadedCount++;
  480. sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
  481. sceneObject.ResumeScripts();
  482. }
  483. }
  484. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
  485. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
  486. if (ignoredObjects > 0)
  487. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  488. if (oldTelehubUUID != UUID.Zero)
  489. {
  490. m_log.WarnFormat("Telehub object not found: {0}", oldTelehubUUID);
  491. scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
  492. scene.RegionInfo.RegionSettings.ClearSpawnPoints();
  493. }
  494. }
  495. /// <summary>
  496. /// Load serialized parcels.
  497. /// </summary>
  498. /// <param name="scene"></param>
  499. /// <param name="serialisedParcels"></param>
  500. protected void LoadParcels(Scene scene, List<string> serialisedParcels)
  501. {
  502. // Reload serialized parcels
  503. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  504. List<LandData> landData = new List<LandData>();
  505. foreach (string serialisedParcel in serialisedParcels)
  506. {
  507. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  508. if (m_displacement != Vector3.Zero)
  509. {
  510. Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
  511. parcel.AABBMin += parcelDisp;
  512. parcel.AABBMax += parcelDisp;
  513. }
  514. // Validate User and Group UUID's
  515. if (parcel.IsGroupOwned)
  516. {
  517. if (!ResolveGroupUuid(parcel.GroupID))
  518. {
  519. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  520. parcel.GroupID = UUID.Zero;
  521. parcel.IsGroupOwned = false;
  522. }
  523. }
  524. else
  525. {
  526. if (!ResolveUserUuid(scene, parcel.OwnerID))
  527. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  528. if (!ResolveGroupUuid(parcel.GroupID))
  529. parcel.GroupID = UUID.Zero;
  530. }
  531. List<LandAccessEntry> accessList = new List<LandAccessEntry>();
  532. foreach (LandAccessEntry entry in parcel.ParcelAccessList)
  533. {
  534. if (ResolveUserUuid(scene, entry.AgentID))
  535. accessList.Add(entry);
  536. // else, drop this access rule
  537. }
  538. parcel.ParcelAccessList = accessList;
  539. // m_log.DebugFormat(
  540. // "[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
  541. // parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
  542. landData.Add(parcel);
  543. }
  544. if (!m_merge)
  545. {
  546. bool setupDefaultParcel = (landData.Count == 0);
  547. scene.LandChannel.Clear(setupDefaultParcel);
  548. }
  549. scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  550. m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
  551. }
  552. /// <summary>
  553. /// Look up the given user id to check whether it's one that is valid for this grid.
  554. /// </summary>
  555. /// <param name="scene"></param>
  556. /// <param name="uuid"></param>
  557. /// <returns></returns>
  558. private bool ResolveUserUuid(Scene scene, UUID uuid)
  559. {
  560. lock (m_validUserUuids)
  561. {
  562. if (!m_validUserUuids.ContainsKey(uuid))
  563. {
  564. // Note: we call GetUserAccount() inside the lock because this UserID is likely
  565. // to occur many times, and we only want to query the users service once.
  566. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
  567. m_validUserUuids.Add(uuid, account != null);
  568. }
  569. return m_validUserUuids[uuid];
  570. }
  571. }
  572. /// <summary>
  573. /// Look up the given group id to check whether it's one that is valid for this grid.
  574. /// </summary>
  575. /// <param name="uuid"></param>
  576. /// <returns></returns>
  577. private bool ResolveGroupUuid(UUID uuid)
  578. {
  579. if (uuid == UUID.Zero)
  580. return true; // this means the object has no group
  581. lock (m_validGroupUuids)
  582. {
  583. if (!m_validGroupUuids.ContainsKey(uuid))
  584. {
  585. bool exists;
  586. if (m_groupsModule == null)
  587. {
  588. exists = false;
  589. }
  590. else
  591. {
  592. // Note: we call GetGroupRecord() inside the lock because this GroupID is likely
  593. // to occur many times, and we only want to query the groups service once.
  594. exists = (m_groupsModule.GetGroupRecord(uuid) != null);
  595. }
  596. m_validGroupUuids.Add(uuid, exists);
  597. }
  598. return m_validGroupUuids[uuid];
  599. }
  600. }
  601. /// Load an asset
  602. /// </summary>
  603. /// <param name="assetFilename"></param>
  604. /// <param name="data"></param>
  605. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  606. private bool LoadAsset(string assetPath, byte[] data)
  607. {
  608. // Right now we're nastily obtaining the UUID from the filename
  609. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  610. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  611. if (i == -1)
  612. {
  613. m_log.ErrorFormat(
  614. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  615. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  616. return false;
  617. }
  618. string extension = filename.Substring(i);
  619. string uuid = filename.Remove(filename.Length - extension.Length);
  620. if (m_assetService.GetMetadata(uuid) != null)
  621. {
  622. // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
  623. return true;
  624. }
  625. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  626. {
  627. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  628. if (assetType == (sbyte)AssetType.Unknown)
  629. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  630. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  631. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  632. asset.Data = data;
  633. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  634. // exists.
  635. m_assetService.Store(asset);
  636. /**
  637. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  638. * it might be best done when dearchive takes place on a separate thread
  639. if (asset.Type=AssetType.Texture)
  640. {
  641. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  642. if (cacheLayerDecode != null)
  643. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  644. }
  645. */
  646. return true;
  647. }
  648. else
  649. {
  650. m_log.ErrorFormat(
  651. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  652. assetPath, extension);
  653. return false;
  654. }
  655. }
  656. /// <summary>
  657. /// Load region settings data
  658. /// </summary>
  659. /// <param name="scene"></param>
  660. /// <param name="settingsPath"></param>
  661. /// <param name="data"></param>
  662. /// <param name="dearchivedScenes"></param>
  663. /// <returns>
  664. /// true if settings were loaded successfully, false otherwise
  665. /// </returns>
  666. private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
  667. {
  668. RegionSettings loadedRegionSettings;
  669. try
  670. {
  671. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  672. }
  673. catch (Exception e)
  674. {
  675. m_log.ErrorFormat(
  676. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  677. settingsPath, e);
  678. return false;
  679. }
  680. RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
  681. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  682. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  683. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  684. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  685. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  686. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  687. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  688. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  689. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  690. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  691. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  692. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  693. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  694. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  695. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  696. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  697. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  698. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  699. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  700. currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
  701. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  702. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  703. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  704. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  705. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  706. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  707. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  708. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  709. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  710. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  711. currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
  712. currentRegionSettings.ClearSpawnPoints();
  713. foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
  714. currentRegionSettings.AddSpawnPoint(sp);
  715. currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
  716. currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
  717. currentRegionSettings.Save();
  718. scene.TriggerEstateSunUpdate();
  719. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  720. if (estateModule != null)
  721. estateModule.sendRegionHandshakeToAll();
  722. return true;
  723. }
  724. /// <summary>
  725. /// Load terrain data
  726. /// </summary>
  727. /// <param name="scene"></param>
  728. /// <param name="terrainPath"></param>
  729. /// <param name="data"></param>
  730. /// <returns>
  731. /// true if terrain was resolved successfully, false otherwise.
  732. /// </returns>
  733. private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
  734. {
  735. ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
  736. MemoryStream ms = new MemoryStream(data);
  737. if (m_displacement != Vector3.Zero)
  738. {
  739. Vector2 terrainDisplacement = new Vector2(m_displacement.X, m_displacement.Y);
  740. terrainModule.LoadFromStream(terrainPath, terrainDisplacement, ms);
  741. }
  742. else
  743. {
  744. terrainModule.LoadFromStream(terrainPath, ms);
  745. }
  746. ms.Close();
  747. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  748. return true;
  749. }
  750. /// <summary>
  751. /// Load oar control file
  752. /// </summary>
  753. /// <param name="path"></param>
  754. /// <param name="data"></param>
  755. /// <param name="dearchivedScenes"></param>
  756. public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
  757. {
  758. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
  759. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  760. XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  761. // Loaded metadata will be empty if no information exists in the archive
  762. dearchivedScenes.LoadedCreationDateTime = 0;
  763. dearchivedScenes.DefaultOriginalID = "";
  764. bool multiRegion = false;
  765. while (xtr.Read())
  766. {
  767. if (xtr.NodeType == XmlNodeType.Element)
  768. {
  769. if (xtr.Name.ToString() == "archive")
  770. {
  771. int majorVersion = int.Parse(xtr["major_version"]);
  772. int minorVersion = int.Parse(xtr["minor_version"]);
  773. string version = string.Format("{0}.{1}", majorVersion, minorVersion);
  774. if (majorVersion > MAX_MAJOR_VERSION)
  775. {
  776. throw new Exception(
  777. string.Format(
  778. "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",
  779. majorVersion, MAX_MAJOR_VERSION));
  780. }
  781. m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
  782. }
  783. if (xtr.Name.ToString() == "datetime")
  784. {
  785. int value;
  786. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  787. dearchivedScenes.LoadedCreationDateTime = value;
  788. }
  789. else if (xtr.Name.ToString() == "row")
  790. {
  791. multiRegion = true;
  792. dearchivedScenes.StartRow();
  793. }
  794. else if (xtr.Name.ToString() == "region")
  795. {
  796. dearchivedScenes.StartRegion();
  797. }
  798. else if (xtr.Name.ToString() == "id")
  799. {
  800. string id = xtr.ReadElementContentAsString();
  801. dearchivedScenes.DefaultOriginalID = id;
  802. if (multiRegion)
  803. dearchivedScenes.SetRegionOriginalID(id);
  804. }
  805. else if (xtr.Name.ToString() == "dir")
  806. {
  807. dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
  808. }
  809. }
  810. }
  811. dearchivedScenes.MultiRegionFormat = multiRegion;
  812. if (!multiRegion)
  813. {
  814. // Add the single scene
  815. dearchivedScenes.StartRow();
  816. dearchivedScenes.StartRegion();
  817. dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
  818. dearchivedScenes.SetRegionDirectory("");
  819. }
  820. ControlFileLoaded = true;
  821. return dearchivedScenes;
  822. }
  823. }
  824. }