ArchiveWriteRequestPreparation.cs 17 KB

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