From e41e52e09727842d990a31e2a5f7f3e9c88fe8b3 Mon Sep 17 00:00:00 2001 From: Oren Hurvitz Date: Sun, 1 Jun 2014 17:39:11 +0300 Subject: [PATCH] Close streams immediately when we finish using them --- .../Remote/OfflineIMServiceRobustConnector.cs | 13 +-- OpenSim/Capabilities/LLSD.cs | 29 +++--- .../Framework/Communications/RestClient.cs | 29 +++++- .../Servers/HttpServer/BaseHttpServer.cs | 96 ++++++++++++------- .../Servers/HttpServer/RestObjectPoster.cs | 30 +++--- .../HttpServer/RestObjectPosterResponse.cs | 31 +++--- .../Servers/HttpServer/RestSessionService.cs | 65 +++++++------ OpenSim/Framework/Util.cs | 53 +++------- OpenSim/Framework/WebUtil.cs | 7 +- .../Agent/TextureSender/J2KDecoderModule.cs | 6 +- .../Avatar/Friends/FriendsRequestHandler.cs | 15 +-- .../World/Archiver/ArchiveReadRequest.cs | 19 ++-- .../World/Archiver/ArchiveWriteRequest.cs | 9 +- .../World/Estate/EstateManagementModule.cs | 5 +- .../World/Estate/XEstateRequestHandler.cs | 12 +-- .../World/Serialiser/SerialiseObjects.cs | 30 +++--- .../World/WorldMap/WorldMapModule.cs | 7 +- .../DataSnapshot/DataSnapshotManager.cs | 35 +++---- .../Scenes/Animation/BinBVHAnimation.cs | 49 +++++----- .../Region/Framework/Scenes/KeyframeMotion.cs | 46 +++++---- .../Region/Framework/Scenes/UuidGatherer.cs | 55 +++++------ OpenSim/Server/Base/ServerUtils.cs | 20 ++-- .../AuthenticationServerPostHandler.cs | 17 +--- .../Avatar/AvatarServerPostHandler.cs | 15 +-- .../Friends/FriendsServerPostHandler.cs | 15 +-- .../Handlers/Grid/GridServerPostHandler.cs | 15 +-- .../GridUser/GridUserServerPostHandler.cs | 16 +--- .../Hypergrid/HGFriendsServerPostHandler.cs | 20 +--- .../Inventory/XInventoryInConnector.cs | 13 +-- .../Handlers/Map/MapAddServerConnector.cs | 15 +-- .../Presence/PresenceServerPostHandler.cs | 15 +-- .../Handlers/Simulation/AgentHandlers.cs | 56 ++++++++--- .../UserAccountServerPostHandler.cs | 15 +-- .../Asset/AssetServicesConnector.cs | 38 ++++---- 34 files changed, 426 insertions(+), 485 deletions(-) diff --git a/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRobustConnector.cs b/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRobustConnector.cs index c44b6ccb68..b3673dab18 100644 --- a/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRobustConnector.cs +++ b/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRobustConnector.cs @@ -215,18 +215,7 @@ namespace OpenSim.OfflineIM rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } #endregion diff --git a/OpenSim/Capabilities/LLSD.cs b/OpenSim/Capabilities/LLSD.cs index eec9e615a9..c59cede3f4 100644 --- a/OpenSim/Capabilities/LLSD.cs +++ b/OpenSim/Capabilities/LLSD.cs @@ -68,7 +68,10 @@ namespace OpenSim.Framework.Capabilities /// public static object LLSDDeserialize(byte[] b) { - return LLSDDeserialize(new MemoryStream(b, false)); + using (MemoryStream ms = new MemoryStream(b, false)) + { + return LLSDDeserialize(ms); + } } /// @@ -78,21 +81,23 @@ namespace OpenSim.Framework.Capabilities /// public static object LLSDDeserialize(Stream st) { - XmlTextReader reader = new XmlTextReader(st); - reader.Read(); - SkipWS(reader); + using (XmlTextReader reader = new XmlTextReader(st)) + { + reader.Read(); + SkipWS(reader); - if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd") - throw new LLSDParseException("Expected "); + if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd") + throw new LLSDParseException("Expected "); - reader.Read(); - object ret = LLSDParseOne(reader); - SkipWS(reader); + reader.Read(); + object ret = LLSDParseOne(reader); + SkipWS(reader); - if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd") - throw new LLSDParseException("Expected "); + if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd") + throw new LLSDParseException("Expected "); - return ret; + return ret; + } } /// diff --git a/OpenSim/Framework/Communications/RestClient.cs b/OpenSim/Framework/Communications/RestClient.cs index e55618122f..fb79c59963 100644 --- a/OpenSim/Framework/Communications/RestClient.cs +++ b/OpenSim/Framework/Communications/RestClient.cs @@ -56,7 +56,7 @@ namespace OpenSim.Framework.Communications /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be /// invoked by the caller in either synchronous mode or asynchronous modes. /// - public class RestClient + public class RestClient : IDisposable { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); @@ -148,6 +148,33 @@ namespace OpenSim.Framework.Communications #endregion constructors + + #region Dispose + + private bool disposed = false; + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + _resource.Dispose(); + } + + disposed = true; + } + + #endregion Dispose + + /// /// Add a path element to the query, e.g. assets /// diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs index b92c25b1f9..093855ca65 100644 --- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs +++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs @@ -832,28 +832,40 @@ namespace OpenSim.Framework.Servers.HttpServer return; // never log these; they're just binary data Stream inputStream = Util.Copy(request.InputStream); - - if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip")) - inputStream = new GZipStream(inputStream, System.IO.Compression.CompressionMode.Decompress); - - using (StreamReader reader = new StreamReader(inputStream, Encoding.UTF8)) + Stream innerStream = null; + try { - string output; - - if (DebugLevel == 5) + if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip")) { - char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed - int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1); - output = new string(chars, 0, Math.Min(len, WebUtil.MaxRequestDiagLength)); - if (len > WebUtil.MaxRequestDiagLength) - output += "..."; - } - else - { - output = reader.ReadToEnd(); + innerStream = inputStream; + inputStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress); } - m_log.DebugFormat("[LOGHTTP] {0}", Util.BinaryToASCII(output)); + using (StreamReader reader = new StreamReader(inputStream, Encoding.UTF8)) + { + string output; + + if (DebugLevel == 5) + { + char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed + int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1); + output = new string(chars, 0, Math.Min(len, WebUtil.MaxRequestDiagLength)); + if (len > WebUtil.MaxRequestDiagLength) + output += "..."; + } + else + { + output = reader.ReadToEnd(); + } + + m_log.DebugFormat("[LOGHTTP] {0}", Util.BinaryToASCII(output)); + } + } + finally + { + if (innerStream != null) + innerStream.Dispose(); + inputStream.Dispose(); } } @@ -981,19 +993,33 @@ namespace OpenSim.Framework.Servers.HttpServer /// private byte[] HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response) { + String requestBody; + Stream requestStream = request.InputStream; + Stream innerStream = null; + try + { + if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip")) + { + innerStream = requestStream; + requestStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress); + } - if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip")) - requestStream = new GZipStream(requestStream, System.IO.Compression.CompressionMode.Decompress); + using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8)) + { + requestBody = reader.ReadToEnd(); + } + } + finally + { + if (innerStream != null) + innerStream.Dispose(); + requestStream.Dispose(); + } - Encoding encoding = Encoding.UTF8; - StreamReader reader = new StreamReader(requestStream, encoding); - - string requestBody = reader.ReadToEnd(); - reader.Close(); - requestStream.Close(); //m_log.Debug(requestBody); requestBody = requestBody.Replace("", ""); + string responseString = String.Empty; XmlRpcRequest xmlRprcRequest = null; @@ -1089,18 +1115,16 @@ namespace OpenSim.Framework.Servers.HttpServer response.ContentType = "text/xml"; using (MemoryStream outs = new MemoryStream()) + using (XmlTextWriter writer = new XmlTextWriter(outs, Encoding.UTF8)) { - using (XmlTextWriter writer = new XmlTextWriter(outs, Encoding.UTF8)) + writer.Formatting = Formatting.None; + XmlRpcResponseSerializer.Singleton.Serialize(writer, xmlRpcResponse); + writer.Flush(); + outs.Flush(); + outs.Position = 0; + using (StreamReader sr = new StreamReader(outs)) { - writer.Formatting = Formatting.None; - XmlRpcResponseSerializer.Singleton.Serialize(writer, xmlRpcResponse); - writer.Flush(); - outs.Flush(); - outs.Position = 0; - using (StreamReader sr = new StreamReader(outs)) - { - responseString = sr.ReadToEnd(); - } + responseString = sr.ReadToEnd(); } } } diff --git a/OpenSim/Framework/Servers/HttpServer/RestObjectPoster.cs b/OpenSim/Framework/Servers/HttpServer/RestObjectPoster.cs index 48ced19c11..afe052fc0a 100644 --- a/OpenSim/Framework/Servers/HttpServer/RestObjectPoster.cs +++ b/OpenSim/Framework/Servers/HttpServer/RestObjectPoster.cs @@ -52,23 +52,25 @@ namespace OpenSim.Framework.Servers.HttpServer request.Method = verb; request.ContentType = "text/xml"; - MemoryStream buffer = new MemoryStream(); - - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - - using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + using (MemoryStream buffer = new MemoryStream()) { - XmlSerializer serializer = new XmlSerializer(type); - serializer.Serialize(writer, obj); - writer.Flush(); + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Encoding = Encoding.UTF8; + + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + XmlSerializer serializer = new XmlSerializer(type); + serializer.Serialize(writer, obj); + writer.Flush(); + } + + int length = (int)buffer.Length; + request.ContentLength = length; + + using (Stream requestStream = request.GetRequestStream()) + requestStream.Write(buffer.ToArray(), 0, length); } - int length = (int) buffer.Length; - request.ContentLength = length; - - Stream requestStream = request.GetRequestStream(); - requestStream.Write(buffer.ToArray(), 0, length); // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request); request.BeginGetResponse(AsyncCallback, request); } diff --git a/OpenSim/Framework/Servers/HttpServer/RestObjectPosterResponse.cs b/OpenSim/Framework/Servers/HttpServer/RestObjectPosterResponse.cs index 451745c7f2..a911b9fa75 100644 --- a/OpenSim/Framework/Servers/HttpServer/RestObjectPosterResponse.cs +++ b/OpenSim/Framework/Servers/HttpServer/RestObjectPosterResponse.cs @@ -60,24 +60,25 @@ namespace OpenSim.Framework.Servers.HttpServer request.ContentType = "text/xml"; request.Timeout = 10000; - MemoryStream buffer = new MemoryStream(); - - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - - using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + using (MemoryStream buffer = new MemoryStream()) { - XmlSerializer serializer = new XmlSerializer(type); - serializer.Serialize(writer, obj); - writer.Flush(); + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Encoding = Encoding.UTF8; + + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + XmlSerializer serializer = new XmlSerializer(type); + serializer.Serialize(writer, obj); + writer.Flush(); + } + + int length = (int)buffer.Length; + request.ContentLength = length; + + using (Stream requestStream = request.GetRequestStream()) + requestStream.Write(buffer.ToArray(), 0, length); } - int length = (int) buffer.Length; - request.ContentLength = length; - - Stream requestStream = request.GetRequestStream(); - requestStream.Write(buffer.ToArray(), 0, length); - requestStream.Close(); // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request); request.BeginGetResponse(AsyncCallback, request); } diff --git a/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs b/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs index 83c9848e0d..ad69cd22cb 100644 --- a/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs +++ b/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs @@ -77,26 +77,25 @@ namespace OpenSim.Framework.Servers.HttpServer request.ContentType = "text/xml"; request.Timeout = 20000; - MemoryStream buffer = new MemoryStream(); - - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - - using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + using (MemoryStream buffer = new MemoryStream()) { - XmlSerializer serializer = new XmlSerializer(type); - serializer.Serialize(writer, sobj); - writer.Flush(); + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Encoding = Encoding.UTF8; + + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + XmlSerializer serializer = new XmlSerializer(type); + serializer.Serialize(writer, sobj); + writer.Flush(); + } + + int length = (int)buffer.Length; + request.ContentLength = length; + + using (Stream requestStream = request.GetRequestStream()) + requestStream.Write(buffer.ToArray(), 0, length); } - int length = (int)buffer.Length; - request.ContentLength = length; - - Stream requestStream = request.GetRequestStream(); - requestStream.Write(buffer.ToArray(), 0, length); - buffer.Close(); - requestStream.Close(); - TResponse deserial = default(TResponse); using (WebResponse resp = request.GetResponse()) { @@ -133,25 +132,25 @@ namespace OpenSim.Framework.Servers.HttpServer request.ContentType = "text/xml"; request.Timeout = 10000; - MemoryStream buffer = new MemoryStream(); - - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - - using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + using (MemoryStream buffer = new MemoryStream()) { - XmlSerializer serializer = new XmlSerializer(type); - serializer.Serialize(writer, sobj); - writer.Flush(); + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Encoding = Encoding.UTF8; + + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + XmlSerializer serializer = new XmlSerializer(type); + serializer.Serialize(writer, sobj); + writer.Flush(); + } + + int length = (int)buffer.Length; + request.ContentLength = length; + + using (Stream requestStream = request.GetRequestStream()) + requestStream.Write(buffer.ToArray(), 0, length); } - buffer.Close(); - int length = (int)buffer.Length; - request.ContentLength = length; - - Stream requestStream = request.GetRequestStream(); - requestStream.Write(buffer.ToArray(), 0, length); - requestStream.Close(); // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request); request.BeginGetResponse(AsyncCallback, request); } diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs index 9d7de970a4..5c429ee483 100644 --- a/OpenSim/Framework/Util.cs +++ b/OpenSim/Framework/Util.cs @@ -509,6 +509,19 @@ namespace OpenSim.Framework return sb.ToString(); } + public static byte[] DocToBytes(XmlDocument doc) + { + using (MemoryStream ms = new MemoryStream()) + using (XmlTextWriter xw = new XmlTextWriter(ms, null)) + { + xw.Formatting = Formatting.Indented; + doc.WriteTo(xw); + xw.Flush(); + + return ms.ToArray(); + } + } + /// /// Is the platform Windows? /// @@ -1307,46 +1320,6 @@ namespace OpenSim.Framework return ret; } - public static string Compress(string text) - { - byte[] buffer = Util.UTF8.GetBytes(text); - MemoryStream memory = new MemoryStream(); - using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true)) - { - compressor.Write(buffer, 0, buffer.Length); - } - - memory.Position = 0; - - byte[] compressed = new byte[memory.Length]; - memory.Read(compressed, 0, compressed.Length); - - byte[] compressedBuffer = new byte[compressed.Length + 4]; - Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length); - Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4); - return Convert.ToBase64String(compressedBuffer); - } - - public static string Decompress(string compressedText) - { - byte[] compressedBuffer = Convert.FromBase64String(compressedText); - using (MemoryStream memory = new MemoryStream()) - { - int msgLength = BitConverter.ToInt32(compressedBuffer, 0); - memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4); - - byte[] buffer = new byte[msgLength]; - - memory.Position = 0; - using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress)) - { - decompressor.Read(buffer, 0, buffer.Length); - } - - return Util.UTF8.GetString(buffer); - } - } - /// /// Copy data from one stream to another, leaving the read position of both streams at the beginning. /// diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs index e614fd5f63..d6831524b2 100644 --- a/OpenSim/Framework/WebUtil.cs +++ b/OpenSim/Framework/WebUtil.cs @@ -176,7 +176,8 @@ namespace OpenSim.Framework public static void LogOutgoingDetail(string context, Stream outputStream) { - using (StreamReader reader = new StreamReader(Util.Copy(outputStream), Encoding.UTF8)) + using (Stream stream = Util.Copy(outputStream)) + using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string output; @@ -262,12 +263,12 @@ namespace OpenSim.Framework using (MemoryStream ms = new MemoryStream()) { - using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress)) + using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true)) { comp.Write(buffer, 0, buffer.Length); // We need to close the gzip stream before we write it anywhere // because apparently something important related to gzip compression - // gets written on the strteam upon Dispose() + // gets written on the stream upon Dispose() } byte[] buf = ms.ToArray(); request.ContentLength = buf.Length; //Count bytes to send diff --git a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs index 732781ab80..5cdcab9f35 100644 --- a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs +++ b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs @@ -231,7 +231,11 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender { try { - List layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData)); + List layerStarts; + using (MemoryStream ms = new MemoryStream(j2kData)) + { + layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms); + } if (layerStarts != null && layerStarts.Count > 0) { diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs index ff87eceae0..13512a20be 100644 --- a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs +++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -289,18 +289,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } #endregion diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs index e9c6fb63cd..c8056d425d 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs @@ -918,17 +918,18 @@ namespace OpenSim.Region.CoreModules.World.Archiver { ITerrainModule terrainModule = scene.RequestModuleInterface(); - MemoryStream ms = new MemoryStream(data); - if (m_displacement != Vector3.Zero || m_rotation != 0f) + using (MemoryStream ms = new MemoryStream(data)) { - Vector2 rotationCenter = new Vector2(m_rotationCenter.X, m_rotationCenter.Y); - terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, rotationCenter, ms); + if (m_displacement != Vector3.Zero || m_rotation != 0f) + { + Vector2 rotationCenter = new Vector2(m_rotationCenter.X, m_rotationCenter.Y); + terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, rotationCenter, ms); + } + else + { + terrainModule.LoadFromStream(terrainPath, ms); + } } - else - { - terrainModule.LoadFromStream(terrainPath, ms); - } - ms.Close(); m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath); diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs index 136a16e6c8..448147ac7b 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs @@ -569,10 +569,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver string terrainPath = String.Format("{0}{1}{2}.r32", regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName); - MemoryStream ms = new MemoryStream(); - scene.RequestModuleInterface().SaveToStream(terrainPath, ms); - m_archiveWriter.WriteFile(terrainPath, ms.ToArray()); - ms.Close(); + using (MemoryStream ms = new MemoryStream()) + { + scene.RequestModuleInterface().SaveToStream(terrainPath, ms); + m_archiveWriter.WriteFile(terrainPath, ms.ToArray()); + } m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive."); diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs index eecc4783cf..b417198efc 100644 --- a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs @@ -1116,9 +1116,8 @@ namespace OpenSim.Region.CoreModules.World.Estate { try { - MemoryStream terrainStream = new MemoryStream(terrainData); - terr.LoadFromStream(filename, terrainStream); - terrainStream.Close(); + using (MemoryStream terrainStream = new MemoryStream(terrainData)) + terr.LoadFromStream(filename, terrainStream); FileInfo x = new FileInfo(filename); remoteClient.SendAlertMessage("Your terrain was loaded as a " + x.Extension + " file. It may take a few moments to appear."); diff --git a/OpenSim/Region/CoreModules/World/Estate/XEstateRequestHandler.cs b/OpenSim/Region/CoreModules/World/Estate/XEstateRequestHandler.cs index 236676777c..ec5af2b538 100644 --- a/OpenSim/Region/CoreModules/World/Estate/XEstateRequestHandler.cs +++ b/OpenSim/Region/CoreModules/World/Estate/XEstateRequestHandler.cs @@ -281,18 +281,8 @@ namespace OpenSim.Region.CoreModules.World.Estate rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); - } } } diff --git a/OpenSim/Region/CoreModules/World/Serialiser/SerialiseObjects.cs b/OpenSim/Region/CoreModules/World/Serialiser/SerialiseObjects.cs index 328fbf0275..65f464afea 100644 --- a/OpenSim/Region/CoreModules/World/Serialiser/SerialiseObjects.cs +++ b/OpenSim/Region/CoreModules/World/Serialiser/SerialiseObjects.cs @@ -54,13 +54,14 @@ namespace OpenSim.Region.CoreModules.World.Serialiser { string xmlstream = GetObjectXml(scene); - MemoryStream stream = ReformatXmlString(xmlstream); + using (MemoryStream stream = ReformatXmlString(xmlstream)) + { + stream.Seek(0, SeekOrigin.Begin); + CreateXmlFile(stream, fileName); - stream.Seek(0, SeekOrigin.Begin); - CreateXmlFile(stream, fileName); - - stream.Seek(0, SeekOrigin.Begin); - CreateCompressedXmlFile(stream, fileName); + stream.Seek(0, SeekOrigin.Begin); + CreateCompressedXmlFile(stream, fileName); + } } private static MemoryStream ReformatXmlString(string xmlstream) @@ -112,13 +113,16 @@ namespace OpenSim.Region.CoreModules.World.Serialiser { #region GZip Compressed Version - FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create); - MemoryStream gzipMSStream = new MemoryStream(); - GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress); - xmlStream.WriteTo(gzipStream); - gzipMSStream.WriteTo(objectsFileCompressed); - objectsFileCompressed.Flush(); - objectsFileCompressed.Close(); + using (FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create)) + using (MemoryStream gzipMSStream = new MemoryStream()) + { + using (GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress, true)) + { + xmlStream.WriteTo(gzipStream); + } + + gzipMSStream.WriteTo(objectsFileCompressed); + } #endregion } diff --git a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs index 2d28d6e5ef..995e2972bd 100644 --- a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs +++ b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs @@ -1145,7 +1145,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap if (myMapImageJPEG.Length == 0) { - MemoryStream imgstream = new MemoryStream(); + MemoryStream imgstream = null; Bitmap mapTexture = new Bitmap(1,1); ManagedImage managedImage; Image image = (Image)mapTexture; @@ -1192,10 +1192,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap image.Dispose(); if (imgstream != null) - { - imgstream.Close(); imgstream.Dispose(); - } } } else @@ -1639,4 +1636,4 @@ namespace OpenSim.Region.CoreModules.World.WorldMap public uint itemtype; public ulong regionhandle; } -} \ No newline at end of file +} diff --git a/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs b/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs index 4a06f6e90f..33899aa7b4 100644 --- a/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs +++ b/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs @@ -373,24 +373,27 @@ namespace OpenSim.Region.DataSnapshot for (int i = 0; i < services.Length; i++) { string url = services[i].Trim(); - RestClient cli = new RestClient(url); - cli.AddQueryParameter("service", serviceName); - cli.AddQueryParameter("host", m_hostname); - cli.AddQueryParameter("port", m_listener_port); - cli.AddQueryParameter("secret", m_Secret.ToString()); - cli.RequestMethod = "GET"; - try + using (RestClient cli = new RestClient(url)) { - reply = cli.Request(null); - } - catch (WebException) - { - m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url); - } - catch (Exception e) - { - m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString()); + cli.AddQueryParameter("service", serviceName); + cli.AddQueryParameter("host", m_hostname); + cli.AddQueryParameter("port", m_listener_port); + cli.AddQueryParameter("secret", m_Secret.ToString()); + cli.RequestMethod = "GET"; + try + { + reply = cli.Request(null); + } + catch (WebException) + { + m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url); + } + catch (Exception e) + { + m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString()); + } } + byte[] response = new byte[1024]; // int n = 0; try diff --git a/OpenSim/Region/Framework/Scenes/Animation/BinBVHAnimation.cs b/OpenSim/Region/Framework/Scenes/Animation/BinBVHAnimation.cs index 3afc87f4d4..b3b38b27f8 100644 --- a/OpenSim/Region/Framework/Scenes/Animation/BinBVHAnimation.cs +++ b/OpenSim/Region/Framework/Scenes/Animation/BinBVHAnimation.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -113,31 +113,34 @@ namespace OpenSim.Region.Framework.Scenes.Animation public byte[] ToBytes() { - byte[] outputbytes = new byte[0]; + byte[] outputbytes; - BinaryWriter iostream = new BinaryWriter(new MemoryStream()); - iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown0))); - iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown1))); - iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority))); - iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(Length))); - iostream.Write(BinBVHUtil.WriteNullTerminatedString(ExpressionName)); - iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(InPoint))); - iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(OutPoint))); - iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Loop ? 1 : 0))); - iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseInTime))); - iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseOutTime))); - iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes(HandPose))); - iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes((uint)(Joints.Length)))); - - for (int i = 0; i < Joints.Length; i++) + using (MemoryStream ms = new MemoryStream()) + using (BinaryWriter iostream = new BinaryWriter(ms)) { - Joints[i].WriteBytesToStream(iostream, InPoint, OutPoint); + iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown0))); + iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown1))); + iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority))); + iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(Length))); + iostream.Write(BinBVHUtil.WriteNullTerminatedString(ExpressionName)); + iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(InPoint))); + iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(OutPoint))); + iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Loop ? 1 : 0))); + iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseInTime))); + iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseOutTime))); + iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes(HandPose))); + iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes((uint)(Joints.Length)))); + + for (int i = 0; i < Joints.Length; i++) + { + Joints[i].WriteBytesToStream(iostream, InPoint, OutPoint); + } + iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(0))); + + using (MemoryStream ms2 = (MemoryStream)iostream.BaseStream) + outputbytes = ms2.ToArray(); } - iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(0))); - MemoryStream ms = (MemoryStream)iostream.BaseStream; - outputbytes = ms.ToArray(); - ms.Close(); - iostream.Close(); + return outputbytes; } diff --git a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs index 2d489ea663..b4a171f5ab 100644 --- a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs +++ b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs @@ -280,7 +280,7 @@ namespace OpenSim.Region.Framework.Scenes if (!m_selected) { StopTimer(); - m_serializedPosition = m_group.AbsolutePosition; + m_serializedPosition = m_group.AbsolutePosition; } } } @@ -308,10 +308,11 @@ namespace OpenSim.Region.Framework.Scenes try { - MemoryStream ms = new MemoryStream(data); - BinaryFormatter fmt = new BinaryFormatter(); - - newMotion = (KeyframeMotion)fmt.Deserialize(ms); + using (MemoryStream ms = new MemoryStream(data)) + { + BinaryFormatter fmt = new BinaryFormatter(); + newMotion = (KeyframeMotion)fmt.Deserialize(ms); + } newMotion.m_group = grp; @@ -345,26 +346,26 @@ namespace OpenSim.Region.Framework.Scenes return; m_group = grp; - m_scene = grp.Scene; + m_scene = grp.Scene; Vector3 grppos = grp.AbsolutePosition; - Vector3 offset = grppos - m_serializedPosition; + Vector3 offset = grppos - m_serializedPosition; // avoid doing it more than once // current this will happen dragging a prim to other region m_serializedPosition = grppos; m_basePosition += offset; m_nextPosition += offset; - + m_currentFrame.StartPosition += offset; - m_currentFrame.Position += offset; + m_currentFrame.Position += offset; for (int i = 0; i < m_frames.Count; i++) { Keyframe k = m_frames[i]; k.StartPosition += offset; k.Position += offset; - m_frames[i]=k; + m_frames[i]=k; } if (m_running) @@ -527,7 +528,7 @@ namespace OpenSim.Region.Framework.Scenes { k.Position = pos; // k.Velocity = Vector3.Zero; - } + } k.StartRotation = rot; if (k.Rotation.HasValue) @@ -764,19 +765,22 @@ namespace OpenSim.Region.Framework.Scenes public Byte[] Serialize() { StopTimer(); - MemoryStream ms = new MemoryStream(); - BinaryFormatter fmt = new BinaryFormatter(); SceneObjectGroup tmp = m_group; - m_group = null; - if (!m_selected && tmp != null) - m_serializedPosition = tmp.AbsolutePosition; - fmt.Serialize(ms, this); - m_group = tmp; - if (m_running && !m_waitingCrossing) - StartTimer(); + m_group = null; + if (!m_selected && tmp != null) + m_serializedPosition = tmp.AbsolutePosition; - return ms.ToArray(); + using (MemoryStream ms = new MemoryStream()) + { + BinaryFormatter fmt = new BinaryFormatter(); + fmt.Serialize(ms, this); + m_group = tmp; + if (m_running && !m_waitingCrossing) + StartTimer(); + + return ms.ToArray(); + } } public void StartCrossingCheck() diff --git a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs index a7015e12b2..d07cc6a4fb 100644 --- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs +++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs @@ -458,35 +458,36 @@ namespace OpenSim.Region.Framework.Scenes if (null == assetBase) return; - MemoryStream ms = new MemoryStream(assetBase.Data); - StreamReader sr = new StreamReader(ms); - - sr.ReadLine(); // Unknown (Version?) - sr.ReadLine(); // Unknown - sr.ReadLine(); // Unknown - sr.ReadLine(); // Name - sr.ReadLine(); // Comment ? - int count = Convert.ToInt32(sr.ReadLine()); // Item count - - for (int i = 0 ; i < count ; i++) + using (MemoryStream ms = new MemoryStream(assetBase.Data)) + using (StreamReader sr = new StreamReader(ms)) { - string type = sr.ReadLine(); - if (type == null) - break; - string name = sr.ReadLine(); - if (name == null) - break; - string id = sr.ReadLine(); - if (id == null) - break; - string unknown = sr.ReadLine(); - if (unknown == null) - break; + sr.ReadLine(); // Unknown (Version?) + sr.ReadLine(); // Unknown + sr.ReadLine(); // Unknown + sr.ReadLine(); // Name + sr.ReadLine(); // Comment ? + int count = Convert.ToInt32(sr.ReadLine()); // Item count - // If it can be parsed as a UUID, it is an asset ID - UUID uuid; - if (UUID.TryParse(id, out uuid)) - assetUuids[uuid] = (sbyte)AssetType.Animation; + for (int i = 0 ; i < count ; i++) + { + string type = sr.ReadLine(); + if (type == null) + break; + string name = sr.ReadLine(); + if (name == null) + break; + string id = sr.ReadLine(); + if (id == null) + break; + string unknown = sr.ReadLine(); + if (unknown == null) + break; + + // If it can be parsed as a UUID, it is an asset ID + UUID uuid; + if (UUID.TryParse(id, out uuid)) + assetUuids[uuid] = (sbyte)AssetType.Animation; // the asset is either an Animation or a Sound, but this distinction isn't important + } } } diff --git a/OpenSim/Server/Base/ServerUtils.cs b/OpenSim/Server/Base/ServerUtils.cs index c92e23ca1b..8f1d56b9a4 100644 --- a/OpenSim/Server/Base/ServerUtils.cs +++ b/OpenSim/Server/Base/ServerUtils.cs @@ -196,17 +196,19 @@ namespace OpenSim.Server.Base public static byte[] SerializeResult(XmlSerializer xs, object data) { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8); - xw.Formatting = Formatting.Indented; - xs.Serialize(xw, data); - xw.Flush(); + using (MemoryStream ms = new MemoryStream()) + using (XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8)) + { + xw.Formatting = Formatting.Indented; + xs.Serialize(xw, data); + xw.Flush(); - ms.Seek(0, SeekOrigin.Begin); - byte[] ret = ms.GetBuffer(); - Array.Resize(ref ret, (int)ms.Length); + ms.Seek(0, SeekOrigin.Begin); + byte[] ret = ms.GetBuffer(); + Array.Resize(ref ret, (int)ms.Length); - return ret; + return ret; + } } /// diff --git a/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs b/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs index 5d65f67b08..6ee98b34b2 100644 --- a/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs @@ -209,7 +209,7 @@ namespace OpenSim.Server.Handlers.Authentication rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } byte[] GetAuthInfo(UUID principalID) @@ -279,7 +279,7 @@ namespace OpenSim.Server.Handlers.Authentication rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] SuccessResult(string token) @@ -306,18 +306,7 @@ namespace OpenSim.Server.Handlers.Authentication rootElement.AppendChild(t); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.GetBuffer(); + return Util.DocToBytes(doc); } private byte[] ResultToBytes(Dictionary result) diff --git a/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs b/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs index 59dbed459b..ff8699fbc6 100644 --- a/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs @@ -247,7 +247,7 @@ namespace OpenSim.Server.Handlers.Avatar rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -269,18 +269,7 @@ namespace OpenSim.Server.Handlers.Avatar rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } } diff --git a/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs b/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs index d442443f85..3aab30b3c3 100644 --- a/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs @@ -229,7 +229,7 @@ namespace OpenSim.Server.Handlers.Friends rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -261,18 +261,7 @@ namespace OpenSim.Server.Handlers.Friends rootElement.AppendChild(message); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } void FromKeyValuePairs(Dictionary kvp, out string principalID, out string friend, out int flags) diff --git a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs index dda47565db..d5a9d67d1e 100644 --- a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs @@ -602,7 +602,7 @@ namespace OpenSim.Server.Handlers.Grid rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -634,18 +634,7 @@ namespace OpenSim.Server.Handlers.Grid rootElement.AppendChild(message); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } #endregion diff --git a/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs b/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs index 006f6ab232..9237c6334e 100644 --- a/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs +++ b/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs @@ -279,7 +279,7 @@ namespace OpenSim.Server.Handlers.GridUser rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -301,20 +301,8 @@ namespace OpenSim.Server.Handlers.GridUser rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); - } - - } } diff --git a/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs b/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs index a2bdadb1aa..37b47edcd5 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs @@ -335,7 +335,7 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] SuccessResult(string value) @@ -362,7 +362,7 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(message); - return DocToBytes(doc); + return Util.DocToBytes(doc); } @@ -395,7 +395,7 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(message); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] BoolResult(bool value) @@ -417,21 +417,9 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); - } - - #endregion } } diff --git a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs index 7283237898..0288fa6bf3 100644 --- a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs +++ b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs @@ -191,18 +191,7 @@ namespace OpenSim.Server.Handlers.Asset rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } byte[] HandleCreateUserInventory(Dictionary request) diff --git a/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs b/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs index a896fdb5ff..649a27e7b9 100644 --- a/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs +++ b/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs @@ -188,7 +188,7 @@ namespace OpenSim.Server.Handlers.MapImage rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult(string msg) @@ -215,18 +215,7 @@ namespace OpenSim.Server.Handlers.MapImage rootElement.AppendChild(message); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } private System.Net.IPAddress GetCallerIP(IOSHttpRequest request) diff --git a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs index 0b3b961471..49dbcb509f 100644 --- a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs @@ -265,7 +265,7 @@ namespace OpenSim.Server.Handlers.Presence rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -287,18 +287,7 @@ namespace OpenSim.Server.Handlers.Presence rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } } diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs index 6d3a3a7507..da2bfebd8d 100644 --- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs +++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs @@ -250,14 +250,30 @@ namespace OpenSim.Server.Handlers.Simulation return encoding.GetBytes("false"); } + string requestBody; + Stream inputStream = request; - if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) - inputStream = new GZipStream(inputStream, CompressionMode.Decompress); + Stream innerStream = null; + try + { + if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) + { + innerStream = inputStream; + inputStream = new GZipStream(innerStream, CompressionMode.Decompress); + } - StreamReader reader = new StreamReader(inputStream, encoding); + using (StreamReader reader = new StreamReader(inputStream, encoding)) + { + requestBody = reader.ReadToEnd(); + } + } + finally + { + if (innerStream != null) + innerStream.Dispose(); + inputStream.Dispose(); + } - string requestBody = reader.ReadToEnd(); - reader.Close(); keysvals.Add("body", requestBody); Hashtable responsedata = new Hashtable(); @@ -461,15 +477,31 @@ namespace OpenSim.Server.Handlers.Simulation keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); - Stream inputStream = request; - if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) - inputStream = new GZipStream(inputStream, CompressionMode.Decompress); - + String requestBody; Encoding encoding = Encoding.UTF8; - StreamReader reader = new StreamReader(inputStream, encoding); - string requestBody = reader.ReadToEnd(); - reader.Close(); + Stream inputStream = request; + Stream innerStream = null; + try + { + if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) + { + innerStream = inputStream; + inputStream = new GZipStream(innerStream, CompressionMode.Decompress); + } + + using (StreamReader reader = new StreamReader(inputStream, encoding)) + { + requestBody = reader.ReadToEnd(); + } + } + finally + { + if (innerStream != null) + innerStream.Dispose(); + inputStream.Dispose(); + } + keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; diff --git a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs index c87e0224c5..a77d78e310 100644 --- a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs +++ b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs @@ -315,7 +315,7 @@ namespace OpenSim.Server.Handlers.UserAccounts rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -337,18 +337,7 @@ namespace OpenSim.Server.Handlers.UserAccounts rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } private byte[] ResultToBytes(Dictionary result) diff --git a/OpenSim/Services/Connectors/Asset/AssetServicesConnector.cs b/OpenSim/Services/Connectors/Asset/AssetServicesConnector.cs index 0996acbdb7..badacb7b8c 100644 --- a/OpenSim/Services/Connectors/Asset/AssetServicesConnector.cs +++ b/OpenSim/Services/Connectors/Asset/AssetServicesConnector.cs @@ -171,27 +171,29 @@ namespace OpenSim.Services.Connectors return fullAsset.Data; } - RestClient rc = new RestClient(m_ServerURI); - rc.AddResourcePath("assets"); - rc.AddResourcePath(id); - rc.AddResourcePath("data"); - - rc.RequestMethod = "GET"; - - Stream s = rc.Request(m_Auth); - - if (s == null) - return null; - - if (s.Length > 0) + using (RestClient rc = new RestClient(m_ServerURI)) { - byte[] ret = new byte[s.Length]; - s.Read(ret, 0, (int)s.Length); + rc.AddResourcePath("assets"); + rc.AddResourcePath(id); + rc.AddResourcePath("data"); - return ret; + rc.RequestMethod = "GET"; + + Stream s = rc.Request(m_Auth); + + if (s == null) + return null; + + if (s.Length > 0) + { + byte[] ret = new byte[s.Length]; + s.Read(ret, 0, (int)s.Length); + + return ret; + } + + return null; } - - return null; } public bool Get(string id, Object sender, AssetRetrieved handler)