ArchiveReadRequest.cs 39 KB

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