ArchiveWriteRequestPreparation.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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.Reflection;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Serialization;
  39. using OpenSim.Region.CoreModules.World.Terrain;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using Ionic.Zlib;
  43. using GZipStream = Ionic.Zlib.GZipStream;
  44. using CompressionMode = Ionic.Zlib.CompressionMode;
  45. namespace OpenSim.Region.CoreModules.World.Archiver
  46. {
  47. /// <summary>
  48. /// Prepare to write out an archive.
  49. /// </summary>
  50. public class ArchiveWriteRequestPreparation
  51. {
  52. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. /// <summary>
  54. /// The minimum major version of OAR that we can write.
  55. /// </summary>
  56. public static int MIN_MAJOR_VERSION = 0;
  57. /// <summary>
  58. /// The maximum major version of OAR that we can write.
  59. /// </summary>
  60. public static int MAX_MAJOR_VERSION = 0;
  61. /// <summary>
  62. /// Determine whether this archive will save assets. Default is true.
  63. /// </summary>
  64. public bool SaveAssets { get; set; }
  65. protected Scene m_scene;
  66. protected Stream m_saveStream;
  67. protected Guid m_requestId;
  68. /// <summary>
  69. /// Constructor
  70. /// </summary>
  71. /// <param name="scene"></param>
  72. /// <param name="savePath">The path to which to save data.</param>
  73. /// <param name="requestId">The id associated with this request</param>
  74. /// <exception cref="System.IO.IOException">
  75. /// If there was a problem opening a stream for the file specified by the savePath
  76. /// </exception>
  77. public ArchiveWriteRequestPreparation(Scene scene, string savePath, Guid requestId) : this(scene, requestId)
  78. {
  79. try
  80. {
  81. m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression);
  82. }
  83. catch (EntryPointNotFoundException e)
  84. {
  85. m_log.ErrorFormat(
  86. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  87. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  88. m_log.ErrorFormat("{0} {1}", e.Message, e.StackTrace);
  89. }
  90. }
  91. /// <summary>
  92. /// Constructor.
  93. /// </summary>
  94. /// <param name="scene"></param>
  95. /// <param name="saveStream">The stream to which to save data.</param>
  96. /// <param name="requestId">The id associated with this request</param>
  97. public ArchiveWriteRequestPreparation(Scene scene, Stream saveStream, Guid requestId) : this(scene, requestId)
  98. {
  99. m_saveStream = saveStream;
  100. }
  101. protected ArchiveWriteRequestPreparation(Scene scene, Guid requestId)
  102. {
  103. m_scene = scene;
  104. m_requestId = requestId;
  105. SaveAssets = true;
  106. }
  107. /// <summary>
  108. /// Archive the region requested.
  109. /// </summary>
  110. /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
  111. public void ArchiveRegion(Dictionary<string, object> options)
  112. {
  113. if (options.ContainsKey("noassets") && (bool)options["noassets"])
  114. SaveAssets = false;
  115. try
  116. {
  117. Dictionary<UUID, AssetType> assetUuids = new Dictionary<UUID, AssetType>();
  118. EntityBase[] entities = m_scene.GetEntities();
  119. List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
  120. string checkPermissions = null;
  121. int numObjectsSkippedPermissions = 0;
  122. Object temp;
  123. if (options.TryGetValue("checkPermissions", out temp))
  124. checkPermissions = (string)temp;
  125. // Filter entities so that we only have scene objects.
  126. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
  127. // end up having to do this
  128. foreach (EntityBase entity in entities)
  129. {
  130. if (entity is SceneObjectGroup)
  131. {
  132. SceneObjectGroup sceneObject = (SceneObjectGroup)entity;
  133. if (!sceneObject.IsDeleted && !sceneObject.IsAttachment)
  134. {
  135. if (!CanUserArchiveObject(m_scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, checkPermissions))
  136. {
  137. // The user isn't allowed to copy/transfer this object, so it will not be included in the OAR.
  138. ++numObjectsSkippedPermissions;
  139. }
  140. else
  141. {
  142. sceneObjects.Add(sceneObject);
  143. }
  144. }
  145. }
  146. }
  147. if (SaveAssets)
  148. {
  149. UuidGatherer assetGatherer = new UuidGatherer(m_scene.AssetService);
  150. foreach (SceneObjectGroup sceneObject in sceneObjects)
  151. {
  152. assetGatherer.GatherAssetUuids(sceneObject, assetUuids);
  153. }
  154. m_log.DebugFormat(
  155. "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets",
  156. sceneObjects.Count, assetUuids.Count);
  157. }
  158. else
  159. {
  160. m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
  161. }
  162. if (numObjectsSkippedPermissions > 0)
  163. {
  164. m_log.DebugFormat(
  165. "[ARCHIVER]: {0} scene objects skipped due to lack of permissions",
  166. numObjectsSkippedPermissions);
  167. }
  168. // Make sure that we also request terrain texture assets
  169. RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings;
  170. if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
  171. assetUuids[regionSettings.TerrainTexture1] = AssetType.Texture;
  172. if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
  173. assetUuids[regionSettings.TerrainTexture2] = AssetType.Texture;
  174. if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
  175. assetUuids[regionSettings.TerrainTexture3] = AssetType.Texture;
  176. if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
  177. assetUuids[regionSettings.TerrainTexture4] = AssetType.Texture;
  178. TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream);
  179. // Asynchronously request all the assets required to perform this archive operation
  180. ArchiveWriteRequestExecution awre
  181. = new ArchiveWriteRequestExecution(
  182. sceneObjects,
  183. m_scene.RequestModuleInterface<ITerrainModule>(),
  184. m_scene.RequestModuleInterface<IRegionSerialiserModule>(),
  185. m_scene,
  186. archiveWriter,
  187. m_requestId,
  188. options);
  189. m_log.InfoFormat("[ARCHIVER]: Creating archive file. This may take some time.");
  190. // Write out control file. This has to be done first so that subsequent loaders will see this file first
  191. // XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this
  192. archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options));
  193. m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
  194. if (SaveAssets)
  195. {
  196. AssetsRequest ar
  197. = new AssetsRequest(
  198. new AssetsArchiver(archiveWriter), assetUuids,
  199. m_scene.AssetService, m_scene.UserAccountService,
  200. m_scene.RegionInfo.ScopeID, options, awre.ReceivedAllAssets);
  201. Util.FireAndForget(o => ar.Execute());
  202. }
  203. else
  204. {
  205. awre.ReceivedAllAssets(new List<UUID>(), new List<UUID>());
  206. }
  207. }
  208. catch (Exception)
  209. {
  210. m_saveStream.Close();
  211. throw;
  212. }
  213. }
  214. /// <summary>
  215. /// Checks whether the user has permission to export an object group to an OAR.
  216. /// </summary>
  217. /// <param name="user">The user</param>
  218. /// <param name="objGroup">The object group</param>
  219. /// <param name="checkPermissions">Which permissions to check: "C" = Copy, "T" = Transfer</param>
  220. /// <returns>Whether the user is allowed to export the object to an OAR</returns>
  221. private bool CanUserArchiveObject(UUID user, SceneObjectGroup objGroup, string checkPermissions)
  222. {
  223. if (checkPermissions == null)
  224. return true;
  225. IPermissionsModule module = m_scene.RequestModuleInterface<IPermissionsModule>();
  226. if (module == null)
  227. return true; // this shouldn't happen
  228. // Check whether the user is permitted to export all of the parts in the SOG. If any
  229. // part can't be exported then the entire SOG can't be exported.
  230. bool permitted = true;
  231. //int primNumber = 1;
  232. foreach (SceneObjectPart obj in objGroup.Parts)
  233. {
  234. uint perm;
  235. PermissionClass permissionClass = module.GetPermissionClass(user, obj);
  236. switch (permissionClass)
  237. {
  238. case PermissionClass.Owner:
  239. perm = obj.BaseMask;
  240. break;
  241. case PermissionClass.Group:
  242. perm = obj.GroupMask | obj.EveryoneMask;
  243. break;
  244. case PermissionClass.Everyone:
  245. default:
  246. perm = obj.EveryoneMask;
  247. break;
  248. }
  249. bool canCopy = (perm & (uint)PermissionMask.Copy) != 0;
  250. bool canTransfer = (perm & (uint)PermissionMask.Transfer) != 0;
  251. // Special case: if Everyone can copy the object then this implies it can also be
  252. // Transferred.
  253. // However, if the user is the Owner then we don't check EveryoneMask, because it seems that the mask
  254. // always (incorrectly) includes the Copy bit set in this case. But that's a mistake: the viewer
  255. // does NOT show that the object has Everyone-Copy permissions, and doesn't allow it to be copied.
  256. if (permissionClass != PermissionClass.Owner)
  257. canTransfer |= (obj.EveryoneMask & (uint)PermissionMask.Copy) != 0;
  258. bool partPermitted = true;
  259. if (checkPermissions.Contains("C") && !canCopy)
  260. partPermitted = false;
  261. if (checkPermissions.Contains("T") && !canTransfer)
  262. partPermitted = false;
  263. // If the user is the Creator of the object then it can always be included in the OAR
  264. bool creator = (obj.CreatorID.Guid == user.Guid);
  265. if (creator)
  266. partPermitted = true;
  267. //string name = (objGroup.PrimCount == 1) ? objGroup.Name : string.Format("{0} ({1}/{2})", obj.Name, primNumber, objGroup.PrimCount);
  268. //m_log.DebugFormat("[ARCHIVER]: Object permissions: {0}: Base={1:X4}, Owner={2:X4}, Everyone={3:X4}, permissionClass={4}, checkPermissions={5}, canCopy={6}, canTransfer={7}, creator={8}, permitted={9}",
  269. // name, obj.BaseMask, obj.OwnerMask, obj.EveryoneMask,
  270. // permissionClass, checkPermissions, canCopy, canTransfer, creator, partPermitted);
  271. if (!partPermitted)
  272. {
  273. permitted = false;
  274. break;
  275. }
  276. //++primNumber;
  277. }
  278. return permitted;
  279. }
  280. /// <summary>
  281. /// Create the control file for the most up to date archive
  282. /// </summary>
  283. /// <returns></returns>
  284. public string CreateControlFile(Dictionary<string, object> options)
  285. {
  286. int majorVersion = MAX_MAJOR_VERSION, minorVersion = 7;
  287. //
  288. // if (options.ContainsKey("version"))
  289. // {
  290. // string[] parts = options["version"].ToString().Split('.');
  291. // if (parts.Length >= 1)
  292. // {
  293. // majorVersion = Int32.Parse(parts[0]);
  294. //
  295. // if (parts.Length >= 2)
  296. // minorVersion = Int32.Parse(parts[1]);
  297. // }
  298. // }
  299. //
  300. // if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION)
  301. // {
  302. // throw new Exception(
  303. // string.Format(
  304. // "OAR version number for save must be between {0} and {1}",
  305. // MIN_MAJOR_VERSION, MAX_MAJOR_VERSION));
  306. // }
  307. // else if (majorVersion == MAX_MAJOR_VERSION)
  308. // {
  309. // // Force 1.0
  310. // minorVersion = 0;
  311. // }
  312. // else if (majorVersion == MIN_MAJOR_VERSION)
  313. // {
  314. // // Force 0.4
  315. // minorVersion = 4;
  316. // }
  317. m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion);
  318. //if (majorVersion == 1)
  319. //{
  320. // m_log.WarnFormat("[ARCHIVER]: Please be aware that version 1.0 OARs are not compatible with OpenSim 0.7.0.2 and earlier. Please use the --version=0 option if you want to produce a compatible OAR");
  321. //}
  322. StringWriter sw = new StringWriter();
  323. XmlTextWriter xtw = new XmlTextWriter(sw);
  324. xtw.Formatting = Formatting.Indented;
  325. xtw.WriteStartDocument();
  326. xtw.WriteStartElement("archive");
  327. xtw.WriteAttributeString("major_version", majorVersion.ToString());
  328. xtw.WriteAttributeString("minor_version", minorVersion.ToString());
  329. xtw.WriteStartElement("creation_info");
  330. DateTime now = DateTime.UtcNow;
  331. TimeSpan t = now - new DateTime(1970, 1, 1);
  332. xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString());
  333. xtw.WriteElementString("id", UUID.Random().ToString());
  334. xtw.WriteEndElement();
  335. xtw.WriteElementString("assets_included", SaveAssets.ToString());
  336. xtw.WriteEndElement();
  337. xtw.Flush();
  338. xtw.Close();
  339. String s = sw.ToString();
  340. sw.Close();
  341. return s;
  342. }
  343. }
  344. }