From 523f7cc1dce8e9be9652771e9c4145c733e53a58 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Wed, 19 Oct 2022 02:23:15 +0100 Subject: [PATCH] more code stype changes --- .../RemoteController/RemoteAdminPlugin.cs | 4 +- OpenSim/Framework/WebUtil.cs | 603 ++++++++---------- .../Avatar/Friends/HGFriendsModule.cs | 2 +- 3 files changed, 271 insertions(+), 338 deletions(-) diff --git a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs index feb247398f..9deea592f5 100644 --- a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs +++ b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs @@ -115,7 +115,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController m_accessIP = new HashSet(); if (accessIP != String.Empty) { - string[] ips = accessIP.Split(new char[] { ',' }); + string[] ips = accessIP.Split(Util.SplitCommaArray); foreach (string ip in ips) { string current = ip.Trim(); @@ -305,7 +305,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController if (requestData.ContainsKey("alerts")) { - string[] alertTimes = requestData["alerts"].ToString().Split( new char[] {','}); + string[] alertTimes = requestData["alerts"].ToString().Split(Util.SplitCommaArray); if (alertTimes.Length == 1 && Convert.ToInt32(alertTimes[0]) == -1) { m_log.Info("[RADMIN]: Request to cancel restart."); diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs index 2d48c2acb1..c5bf5870af 100644 --- a/OpenSim/Framework/WebUtil.cs +++ b/OpenSim/Framework/WebUtil.cs @@ -27,7 +27,6 @@ using System; using System.Collections; -using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; @@ -44,7 +43,6 @@ using System.Xml.Linq; using log4net; using Nwc.XmlRpc; using OpenMetaverse.StructuredData; -using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Framework @@ -58,7 +56,7 @@ namespace OpenSim.Framework { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public static ExpiringKey GlobalExpiringBadURLs = new ExpiringKey(30000); + public static ExpiringKey GlobalExpiringBadURLs = new(30000); /// /// Control the printing of certain debug messages. /// @@ -102,9 +100,7 @@ namespace OpenSim.Framework { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors; sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch; - if (sslPolicyErrors == SslPolicyErrors.None) - return true; - return false; + return sslPolicyErrors == SslPolicyErrors.None; } #region JSONRequest @@ -144,29 +140,27 @@ namespace OpenSim.Framework public static void LogOutgoingDetail(string context, Stream outputStream) { - using (Stream stream = Util.Copy(outputStream)) - using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) + using Stream stream = Util.Copy(outputStream); + using StreamReader reader = new(stream, Encoding.UTF8); + string output; + + if (DebugLevel == 5) { - 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, len); - } - else - { - output = reader.ReadToEnd(); - } - - LogOutgoingDetail(context, output); + char[] chars = new char[MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed + int len = reader.Read(chars, 0, MaxRequestDiagLength + 1); + output = new string(chars, 0, len); } + else + { + output = reader.ReadToEnd(); + } + + LogOutgoingDetail(context, output); } public static void LogOutgoingDetail(string type, int reqnum, string output) { - LogOutgoingDetail(string.Format("{0} {1}: ", type, reqnum), output); + LogOutgoingDetail($"{type} {reqnum}: ", output); } public static void LogOutgoingDetail(string context, string output) @@ -174,20 +168,20 @@ namespace OpenSim.Framework if (DebugLevel == 5) { if (output.Length > MaxRequestDiagLength) - output = output.Substring(0, MaxRequestDiagLength) + "..."; + output = output[..MaxRequestDiagLength] + "..."; } - m_log.DebugFormat("[LOGHTTP]: {0}{1}", context, Util.BinaryToASCII(output)); + m_log.DebugFormat($"[LOGHTTP]: {context}{Util.BinaryToASCII(output)}"); } public static void LogResponseDetail(int reqnum, Stream inputStream) { - LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), inputStream); + LogOutgoingDetail($"RESPONSE {reqnum}: ", inputStream); } public static void LogResponseDetail(int reqnum, string input) { - LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input); + LogOutgoingDetail($"RESPONSE {reqnum}: ", input); } public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc, bool keepalive = false) @@ -195,14 +189,13 @@ namespace OpenSim.Framework int reqnum = RequestNumber++; if (DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} JSON-RPC {1} to {2}", - reqnum, method, url); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} JSON-RPC {method} to {url}"); string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int sendlen = 0; int rcvlen = 0; - HttpWebRequest request = null; + HttpWebRequest request; try { request = (HttpWebRequest)WebRequest.Create(url); @@ -216,15 +209,14 @@ namespace OpenSim.Framework } catch (Exception ex) { - errorMessage = ex.Message; - m_log.Debug("[WEB UTIL]: SvcOSD error creating request " + ex.Message); - return ErrorResponseMap(errorMessage); + m_log.Debug($"[WEB UTIL]: SvcOSD error creating request {ex.Message}"); + return ErrorResponseMap(ex.Message); } try { // If there is some input, write it into the request - if (data != null) + if (data is not null) { byte[] buffer; if (DebugLevel >= 5) @@ -242,14 +234,12 @@ namespace OpenSim.Framework { request.Headers["X-Content-Encoding"] = "gzip"; // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding - using (MemoryStream ms = new MemoryStream()) + using MemoryStream ms = new(); + using (GZipStream comp = new(ms, CompressionMode.Compress, true)) { - using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true)) - { - comp.Write(buffer, 0, buffer.Length); - } - buffer = ms.ToArray(); + comp.Write(buffer, 0, buffer.Length); } + buffer = ms.ToArray(); } sendlen = buffer.Length; @@ -259,49 +249,42 @@ namespace OpenSim.Framework buffer = null; } - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - using (StreamReader reader = new StreamReader(response.GetResponseStream())) - { - string responseStr = reader.ReadToEnd(); - if (WebUtil.DebugLevel >= 5) - WebUtil.LogResponseDetail(reqnum, responseStr); - rcvlen = responseStr.Length; - return CanonicalizeResults(responseStr); - } - } + using HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + using StreamReader reader = new(response.GetResponseStream()); + string responseStr = reader.ReadToEnd(); + if (WebUtil.DebugLevel >= 5) + WebUtil.LogResponseDetail(reqnum, responseStr); + rcvlen = responseStr.Length; + return CanonicalizeResults(responseStr); } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { - using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) - errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription); + using HttpWebResponse webResponse = (HttpWebResponse)we.Response; + errorMessage = $"[{webResponse.StatusCode}] {webResponse.StatusDescription}"; } } catch (Exception ex) { errorMessage = ex.Message; - m_log.Debug("[WEB UTIL]: Exception making request: " + ex.ToString()); + m_log.Debug($"[WEB UTIL]: Exception making request: {errorMessage}"); } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { - m_log.InfoFormat( - "[WEB UTIL]: SvcOSD {0} {1} {2} took {3}ms, {4}/{5}bytes", - reqnum, method, url, tickdiff, sendlen, rcvlen ); + m_log.Info($"[WEB UTIL]: SvcOSD {reqnum} {method} {url} took {tickdiff}ms, {sendlen}/{rcvlen}bytes"); } else if (DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", - reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); } } - m_log.DebugFormat("[LOGHTTP]: JSON request {0} {1} to {2} FAILED: {3}", reqnum, method, url, errorMessage); + m_log.Debug($"[LOGHTTP]: JSON request {reqnum} {method} to {url} FAILED: {errorMessage}"); return ErrorResponseMap(errorMessage); } @@ -316,13 +299,14 @@ namespace OpenSim.Framework /// private static OSDMap CanonicalizeResults(string response) { - OSDMap result = new OSDMap(); - - // Default values - result["Success"] = OSD.FromBoolean(true); - result["success"] = OSD.FromBoolean(true); - result["_RawResult"] = OSD.FromString(response); - result["_Result"] = new OSDMap(); + OSDMap result = new() + { + // Default values + ["Success"] = OSD.FromBoolean(true), + ["success"] = OSD.FromBoolean(true), + ["_RawResult"] = OSD.FromString(response), + ["_Result"] = new OSDMap() + }; if (response.Equals("true", StringComparison.OrdinalIgnoreCase)) return result; @@ -346,7 +330,7 @@ namespace OpenSim.Framework catch { // don't need to treat this as an error... we're just guessing anyway -// m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message); + //m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message); } return result; @@ -368,18 +352,17 @@ namespace OpenSim.Framework public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout) { int reqnum = RequestNumber++; - string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown"; + string method = (data is not null && data["RequestMethod"] is not null) ? data["RequestMethod"] : "unknown"; if (DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} ServiceForm '{1}' to {2}", - reqnum, method, url); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} ServiceForm '{method}' to {url}"); string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int sendlen = 0; int rcvlen = 0; - HttpWebRequest request = null; + HttpWebRequest request; try { request = (HttpWebRequest)WebRequest.Create(url); @@ -416,28 +399,24 @@ namespace OpenSim.Framework buffer = null; } - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - using (StreamReader reader = new StreamReader(response.GetResponseStream())) - { - string responseStr = reader.ReadToEnd(); - rcvlen = responseStr.Length; - if (DebugLevel >= 5) - LogResponseDetail(reqnum, responseStr); - OSD responseOSD = OSDParser.Deserialize(responseStr); + using HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + using StreamReader reader = new(response.GetResponseStream()); + string responseStr = reader.ReadToEnd(); + rcvlen = responseStr.Length; + if (DebugLevel >= 5) + LogResponseDetail(reqnum, responseStr); + OSD responseOSD = OSDParser.Deserialize(responseStr); - if (responseOSD.Type == OSDType.Map) - return (OSDMap)responseOSD; - } - } + if (responseOSD.Type == OSDType.Map) + return (OSDMap)responseOSD; } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { - using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) - errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription); + using HttpWebResponse webResponse = (HttpWebResponse)we.Response; + errorMessage = $"[{webResponse.StatusCode}] {webResponse.StatusDescription}"; } } catch (Exception ex) @@ -449,18 +428,16 @@ namespace OpenSim.Framework int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { - m_log.InfoFormat( - "[LOGHTTP]: Slow ServiceForm request {0} '{1}' to {2} took {3}ms, {4}/{5}bytes", - reqnum, method, url, tickdiff, sendlen, rcvlen); + m_log.Info( + $"[LOGHTTP]: Slow ServiceForm request {reqnum} '{method}' to {url} took {tickdiff}ms, {sendlen}/{rcvlen}bytes"); } else if (DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", - reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); } } - m_log.WarnFormat("[LOGHTTP]: ServiceForm request {0} '{1}' to {2} failed: {3}", reqnum, method, url, errorMessage); + m_log.Warn($"[LOGHTTP]: ServiceForm request {reqnum} '{method}' to {url} failed: {errorMessage}"); return ErrorResponseMap(errorMessage); } @@ -471,9 +448,11 @@ namespace OpenSim.Framework /// private static OSDMap ErrorResponseMap(string msg) { - OSDMap result = new OSDMap(); - result["Success"] = "False"; - result["Message"] = OSD.FromString("Service request failed: " + msg); + OSDMap result = new() + { + ["Success"] = "False", + ["Message"] = OSD.FromString("Service request failed: " + msg) + }; return result; } @@ -497,10 +476,10 @@ namespace OpenSim.Framework string fragment1 = uri.Fragment; string fragment2 = fragment; - if (!fragment1.EndsWith("/")) - fragment1 = fragment1 + '/'; - if (fragment2.StartsWith("/")) - fragment2 = fragment2.Substring(1); + if (!fragment1.EndsWith('/')) + fragment1 += '/'; + if (fragment2.StartsWith('/')) + fragment2 = fragment2[1..]; return new Uri(uri, fragment1 + fragment2); } @@ -522,10 +501,10 @@ namespace OpenSim.Framework string fragment1 = uri.Fragment; string fragment2 = fragment.ToString(); - if (!fragment1.EndsWith("/")) - fragment1 = fragment1 + '/'; - if (fragment2.StartsWith("/")) - fragment2 = fragment2.Substring(1); + if (!fragment1.EndsWith('/')) + fragment1 += '/'; + if (fragment2.StartsWith('/')) + fragment2 = fragment2[1..]; return new Uri(uri, fragment1 + fragment2); } @@ -541,18 +520,18 @@ namespace OpenSim.Framework /// appended public static string AppendQuery(this Uri uri, string query) { - if (String.IsNullOrEmpty(query)) + if (string.IsNullOrEmpty(query)) return uri.ToString(); if (query[0] == '?' || query[0] == '&') - query = query.Substring(1); + query = query[1..]; string uriStr = uri.ToString(); - if (uriStr.Contains("?")) - return uriStr + '&' + query; + if (uriStr.Contains('?')) + return $"{uriStr}&{query}"; else - return uriStr + '?' + query; + return $"{uriStr}?{query}"; } #endregion Uri @@ -570,19 +549,19 @@ namespace OpenSim.Framework if (parameters.Count == 0) return string.Empty; - StringBuilder sb = new StringBuilder(4096); + StringBuilder sb = new(4096); foreach (string key in parameters.Keys) { string[] values = parameters.GetValues(key); - if (values != null) + if (values is not null) { foreach (string value in values) { sb.Append(key); - sb.Append("="); + sb.Append('='); if(!string.IsNullOrWhiteSpace(value)) sb.Append(HttpUtility.UrlEncode(value)); - sb.Append("&"); + sb.Append('&'); } } } @@ -602,7 +581,7 @@ namespace OpenSim.Framework public static string GetOne(this NameValueCollection collection, string key) { string[] values = collection.GetValues(key); - if (values != null && values.Length > 0) + if (values is not null && values.Length > 0) return values[0]; return null; @@ -659,14 +638,13 @@ namespace OpenSim.Framework return qy.CompareTo(qx); // descending order } - private float GetQ(Object o) + private static float GetQ(Object o) { // Example: image/png;q=0.9 - float qvalue = 1F; - if (o is String) + float qvalue = 1f; + if (o is String mime) { - string mime = (string)o; string[] parts = mime.Split(';'); if (parts.Length > 1) { @@ -692,22 +670,29 @@ namespace OpenSim.Framework public static string[] GetPreferredImageTypes(string accept) { if (string.IsNullOrEmpty(accept)) - return new string[0]; + return Array.Empty(); - string[] types = accept.Split(new char[] { ',' }); + string[] types = accept.Split(Util.SplitCommaArray); if (types.Length > 0) { - List list = new List(types); - list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); }); - ArrayList tlist = new ArrayList(list); + ArrayList tlist = new(); + foreach(string s in types.AsSpan()) + { + if(s.StartsWith("image", StringComparison.InvariantCultureIgnoreCase)) + tlist.Add(s); + } + if(tlist.Count == 0) + return Array.Empty(); + tlist.Sort(new QBasedComparer()); string[] result = new string[tlist.Count]; + for (int i = 0; i < tlist.Count; i++) { string mime = (string)tlist[i]; - string[] parts = mime.Split(new char[] { ';' }); - string[] pair = parts[0].Split(new char[] { '/' }); + string[] parts = mime.Split(Util.SplitSemicolonArray); + string[] pair = parts[0].Split(Util.SplitSlashArray); if (pair.Length == 2) result[i] = pair[1].ToLower(); else // oops, we don't know what this is... @@ -717,7 +702,7 @@ namespace OpenSim.Framework return result; } - return new string[0]; + return Array.Empty(); } } @@ -772,8 +757,7 @@ namespace OpenSim.Framework int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} AsynchronousRequestObject {1} to {2}", - reqnum, verb, requestUrl); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} AsynchronousRequestObject {verb} to {requestUrl}"); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; @@ -791,7 +775,7 @@ namespace OpenSim.Framework if (maxConnections > 0 && request.ServicePoint.ConnectionLimit < maxConnections) request.ServicePoint.ConnectionLimit = maxConnections; - TResponse deserial = default(TResponse); + TResponse deserial = default; request.Method = verb; @@ -802,12 +786,14 @@ namespace OpenSim.Framework { request.ContentType = "text/xml"; - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - using (MemoryStream buffer = new MemoryStream()) + XmlWriterSettings settings = new() + { + Encoding = Encoding.UTF8 + }; + using (MemoryStream buffer = new()) using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { - XmlSerializer serializer = new XmlSerializer(type); + XmlSerializer serializer = new(type); serializer.Serialize(writer, obj); writer.Flush(); data = buffer.ToArray(); @@ -833,11 +819,9 @@ namespace OpenSim.Framework { try { - using (Stream respStream = response.GetResponseStream()) - { - deserial = XMLResponseHelper.LogAndDeserialize( - reqnum, respStream, response.ContentLength); - } + using Stream respStream = response.GetResponseStream(); + deserial = XMLResponseHelper.LogAndDeserialize( + reqnum, respStream, response.ContentLength); } catch (System.InvalidOperationException) { @@ -857,15 +841,20 @@ namespace OpenSim.Framework { // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't // documented in MSDN - using (WebResponse response = request.EndGetResponse(res2)) + using WebResponse response = request.EndGetResponse(res2); + try + { + using Stream respStream = response.GetResponseStream(); + deserial = XMLResponseHelper.LogAndDeserialize( + reqnum, respStream, response.ContentLength); + } + catch (System.InvalidOperationException) { try { - using (Stream respStream = response.GetResponseStream()) - { - deserial = XMLResponseHelper.LogAndDeserialize( - reqnum, respStream, response.ContentLength); - } + using Stream respStream = response.GetResponseStream(); + deserial = XMLResponseHelper.LogAndDeserialize( + reqnum, respStream, response.ContentLength); } catch (System.InvalidOperationException) { @@ -876,36 +865,30 @@ namespace OpenSim.Framework { if (e.Status == WebExceptionStatus.ProtocolError) { - if (e.Response is HttpWebResponse) + if (e.Response is HttpWebResponse httpResponse) { - using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response) + if (httpResponse.StatusCode != HttpStatusCode.NotFound) { - if (httpResponse.StatusCode != HttpStatusCode.NotFound) - { - // We don't appear to be handling any other status codes, so log these feailures to that - // people don't spend unnecessary hours hunting phantom bugs. - m_log.DebugFormat( - "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", - verb, requestUrl, httpResponse.StatusCode); - } + // We don't appear to be handling any other status codes, so log these feailures to that + // people don't spend unnecessary hours hunting phantom bugs. + m_log.Debug( + $"[ASYNC REQUEST]: Request {verb} {requestUrl} failed with unexpected status code {httpResponse.StatusCode}"); } + httpResponse.Dispose(); } } else { - m_log.ErrorFormat( - "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", - verb, requestUrl, e.Status, e.Message); + m_log.Error( + $"[ASYNC REQUEST]: Request {verb} {requestUrl} failed with status {e.Status} and message {e.Message}"); } } catch (Exception e) { - m_log.ErrorFormat( - "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}", - verb, requestUrl, e.Message, e.StackTrace); + m_log.Error($"[ASYNC REQUEST]: Request {verb} {requestUrl} failed with exception {e.Message}"); } - // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); + //m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); try { @@ -913,9 +896,7 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.ErrorFormat( - "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}", - verb, requestUrl, e.Message, e.StackTrace); + m_log.ErrorFormat($"[ASYNC REQUEST]: Request {verb} {requestUrl} callback failed with exception {e.Message}"); } }, null); @@ -940,9 +921,7 @@ namespace OpenSim.Framework } else if (WebUtil.DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", - - reqnum, tickdiff, tickdata); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms, {tickdata}ms writing"); } } catch { } @@ -970,12 +949,11 @@ namespace OpenSim.Framework int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms {1} to {2}", - reqnum, verb, requestUrl); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SynchronousRestForms {verb} to {requestUrl}"); int tickstart = Util.EnvironmentTickCount(); - HttpWebRequest request = null; + HttpWebRequest request; try { request = (HttpWebRequest)WebRequest.Create(requestUrl); @@ -992,7 +970,7 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.InfoFormat("[FORMS]: Error creating {0} request to : {1}. Request: {2}", verb, requestUrl, e.Message); + m_log.Info($"[FORMS]: Error creating {verb} request to : {requestUrl}. Request: {e.Message}"); throw; } @@ -1014,7 +992,7 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.InfoFormat("[FORMS]: Error sending {0} request to: {1}. {2}", verb,requestUrl, e.Message); + m_log.Info($"[FORMS]: Error sending {verb} request to: {requestUrl}. {e.Message}"); throw; } } @@ -1023,32 +1001,28 @@ namespace OpenSim.Framework string respstring = String.Empty; try { - using (WebResponse resp = request.GetResponse()) + using WebResponse resp = request.GetResponse(); + if (resp.ContentLength != 0) { - if (resp.ContentLength != 0) - { - using (StreamReader reader = new StreamReader(resp.GetResponseStream())) - respstring = reader.ReadToEnd(); - rcvlen = respstring.Length; - } + using (StreamReader reader = new(resp.GetResponseStream())) + respstring = reader.ReadToEnd(); + rcvlen = respstring.Length; } } catch (Exception e) { - m_log.InfoFormat("[FORMS]: Error receiving response from {0}: {1}.", requestUrl, e.Message); + m_log.Info($"[FORMS]: Error receiving response from {requestUrl}: {e.Message}"); throw; } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { - m_log.InfoFormat("[FORMS]: request {0} {1} {2} took {3}ms, {4}/{5}bytes", - reqnum, verb, requestUrl, tickdiff, sendlen, rcvlen); + m_log.Info($"[FORMS]: request {reqnum} {verb} {requestUrl} took {tickdiff}ms, {sendlen}/{rcvlen}bytes"); } else if (WebUtil.DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", - reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, respstring); } @@ -1056,7 +1030,6 @@ namespace OpenSim.Framework return respstring; } - public static string MakeRequest(string verb, string requestUrl, string obj, IServiceAuth auth) { return MakeRequest(verb, requestUrl, obj, -1, auth); @@ -1068,12 +1041,11 @@ namespace OpenSim.Framework int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms POST to {1}", - reqnum, requestUrl); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SynchronousRestForms POST to {requestUrl}"); int tickstart = Util.EnvironmentTickCount(); - HttpWebRequest request = null; + HttpWebRequest request; try { request = (HttpWebRequest)WebRequest.Create(requestUrl); @@ -1090,7 +1062,7 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.InfoFormat("[FORMS]: Error creating POST request to {0}: {1}", requestUrl, e.Message); + m_log.Info($"[FORMS]: Error creating POST request to {requestUrl}: {e.Message}"); throw; } @@ -1109,39 +1081,35 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.InfoFormat("[FORMS]: Error sending POST request to {0}: {1}", requestUrl, e.Message); + m_log.Info($"[FORMS]: Error sending POST request to {requestUrl}: {e.Message}"); throw; } - string respstring = String.Empty; + string respstring = string.Empty; int rcvlen = 0; try { - using (WebResponse resp = request.GetResponse()) + using WebResponse resp = request.GetResponse(); + if (resp.ContentLength != 0) { - if (resp.ContentLength != 0) - { - using (StreamReader reader = new StreamReader(resp.GetResponseStream())) - respstring = reader.ReadToEnd(); - } + using StreamReader reader = new(resp.GetResponseStream()); + respstring = reader.ReadToEnd(); } } catch (Exception e) { - m_log.InfoFormat("[FORMS]: Error receiving response from {0}: {1}", requestUrl, e.Message); + m_log.Info($"[FORMS]: Error receiving response from {requestUrl}: {e.Message}"); throw; } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { - m_log.InfoFormat("[FORMS]: request {0} POST {1} took {2}ms {3}/{4}bytes", - reqnum, requestUrl, tickdiff, sendlen, rcvlen); + m_log.Info($"[FORMS]: request {reqnum} POST {requestUrl} took {tickdiff}ms {sendlen}/{rcvlen}bytes"); } else if (WebUtil.DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", - reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, respstring); } @@ -1208,14 +1176,13 @@ namespace OpenSim.Framework int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SRestObjReq {1} {2}", - reqnum, verb, requestUrl); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SRestObjReq {verb} {requestUrl}"); int tickstart = Util.EnvironmentTickCount(); - TResponse deserial = default(TResponse); + TResponse deserial = default; - HttpWebRequest request = null; + HttpWebRequest request; try { request = (HttpWebRequest)WebRequest.Create(requestUrl); @@ -1230,8 +1197,7 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.DebugFormat("[SRestObjReq]: Exception in creating request {0} {1}: {2}{3}", - verb, requestUrl, e.Message, e.StackTrace); + m_log.Debug($"[SRestObjReq]: Exception in creating request {verb} {requestUrl}: {e.Message}"); return deserial; } @@ -1242,11 +1208,11 @@ namespace OpenSim.Framework request.ContentType = "text/xml"; byte[] data; - XmlWriterSettings settings = new XmlWriterSettings() { Encoding = Util.UTF8 }; - using (MemoryStream ms = new MemoryStream()) + XmlWriterSettings settings = new() { Encoding = Util.UTF8 }; + using (MemoryStream ms = new()) using (XmlWriter writer = XmlWriter.Create(ms, settings)) { - XmlSerializer serializer = new XmlSerializer(typeof(TRequest)); + XmlSerializer serializer = new(typeof(TRequest)); serializer.Serialize(writer, obj); writer.Flush(); data = ms.ToArray(); @@ -1265,78 +1231,63 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.DebugFormat( - "[SRestObjReq]: Exception in making request {0} {1}: {2}{3}", - verb, requestUrl, e.Message, e.StackTrace); - + m_log.Debug( $"[SRestObjReq]: Exception in making request {verb} {requestUrl}: {e.Message}"); return deserial; } int rcvlen = 0; try { - using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) + using HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); + if (resp.ContentLength != 0) { - if (resp.ContentLength != 0) - { - rcvlen = (int)resp.ContentLength; - using (Stream respStream = resp.GetResponseStream()) - { - deserial = XMLResponseHelper.LogAndDeserialize( - reqnum, respStream, resp.ContentLength); - } - } - else - { - m_log.DebugFormat("[SRestObjReq]: Oops! no content found in response stream from {0} {1}", - verb, requestUrl); - } + rcvlen = (int)resp.ContentLength; + using Stream respStream = resp.GetResponseStream(); + deserial = XMLResponseHelper.LogAndDeserialize( + reqnum, respStream, resp.ContentLength); + } + else + { + m_log.Debug($"[SRestObjReq]: Oops! no content found in response stream from {verb} {requestUrl}"); } } catch (WebException e) { - using (HttpWebResponse hwr = (HttpWebResponse)e.Response) + using HttpWebResponse hwr = (HttpWebResponse)e.Response; + if (hwr != null) { - if (hwr != null) + if (hwr.StatusCode == HttpStatusCode.Unauthorized) { - if (hwr.StatusCode == HttpStatusCode.Unauthorized) - { - m_log.ErrorFormat("[SRestObjReq]: {0} requires authentication", - requestUrl); - } - else if (hwr.StatusCode != HttpStatusCode.NotFound) - { - m_log.WarnFormat("[SRestObjReq]: {0} returned error: {1}", - requestUrl, hwr.StatusCode); - } + m_log.Error($"[SRestObjReq]: {requestUrl} requires authentication"); + } + else if (hwr.StatusCode != HttpStatusCode.NotFound) + { + m_log.Warn($"[SRestObjReq]: {requestUrl} returned error: {hwr.StatusCode}"); } - else - m_log.ErrorFormat( - "[SRestObjReq]: WebException for {0} {1} {2} {3}", - verb, requestUrl, typeof(TResponse).ToString(), e.Message); } + else + m_log.ErrorFormat( + "[SRestObjReq]: WebException for {0} {1} {2} {3}", + verb, requestUrl, typeof(TResponse).ToString(), e.Message); } catch (System.InvalidOperationException) { // This is what happens when there is invalid XML - m_log.DebugFormat("[SRestObjReq]: Invalid XML from {0} {1} {2}", - verb, requestUrl, typeof(TResponse).ToString()); + m_log.Debug($"[SRestObjReq]: Invalid XML from {verb} {requestUrl} {typeof(TResponse)}"); } catch (Exception e) { - m_log.DebugFormat("[SRestObjReq]: Exception on response from {0} {1}: {2}", - verb, requestUrl, e.Message); + m_log.Debug($"[SRestObjReq]: Exception on response from {verb} {requestUrl}: {e.Message}"); } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { - m_log.InfoFormat("[LOGHTTP]: Slow SRestObjReq {0} {1} {2} took {3}ms, {4}bytes", - reqnum, verb, requestUrl, tickdiff, rcvlen); + m_log.Info($"[LOGHTTP]: Slow SRestObjReq {reqnum} {verb} {requestUrl} took {tickdiff}ms, {rcvlen}bytes"); } else if (WebUtil.DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); } return deserial; } @@ -1346,11 +1297,11 @@ namespace OpenSim.Framework int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SRestObjReq GET {1}", reqnum, requestUrl); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SRestObjReq GET {requestUrl}"); int tickstart = Util.EnvironmentTickCount(); - TResponse deserial = default(TResponse); - HttpWebRequest request = null; + TResponse deserial = default; + HttpWebRequest request; try { request = (HttpWebRequest)WebRequest.Create(requestUrl); @@ -1367,77 +1318,61 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.DebugFormat("[SRestObjReq]: Exception in creating GET request {0}: {1}{2}", - requestUrl, e.Message, e.StackTrace); + m_log.Debug($"[SRestObjReq]: Exception in creating GET request {requestUrl}: {e.Message}"); return deserial; } int rcvlen = 0; try { - using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) + using HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); + if (resp.ContentLength != 0) { - if (resp.ContentLength != 0) - { - rcvlen = (int)resp.ContentLength; - using (Stream respStream = resp.GetResponseStream()) - { - deserial = XMLResponseHelper.LogAndDeserialize( - reqnum, respStream, resp.ContentLength); - } - } - else - { - m_log.DebugFormat("[SRestObjReq]: Oops! no content found in response stream from GET {0}", - requestUrl); - } + rcvlen = (int)resp.ContentLength; + using Stream respStream = resp.GetResponseStream(); + deserial = XMLResponseHelper.LogAndDeserialize( + reqnum, respStream, resp.ContentLength); + } + else + { + m_log.Debug($"[SRestObjReq]: Oops! no content found in response stream from GET {requestUrl}"); } } catch (WebException e) { - using (HttpWebResponse hwr = (HttpWebResponse)e.Response) + using HttpWebResponse hwr = (HttpWebResponse)e.Response; + if (hwr != null) { - if (hwr != null) + if (hwr.StatusCode == HttpStatusCode.Unauthorized) { - if (hwr.StatusCode == HttpStatusCode.Unauthorized) - { - m_log.ErrorFormat("[SRestObjReq]: GET {0} requires authentication", - requestUrl); - } - else if (hwr.StatusCode != HttpStatusCode.NotFound) - { - m_log.WarnFormat("[SRestObjReq]: GET {0} returned error: {1}", - requestUrl, hwr.StatusCode); - } + m_log.Error($"[SRestObjReq]: GET {requestUrl} requires authentication"); + } + else if (hwr.StatusCode != HttpStatusCode.NotFound) + { + m_log.Warn($"[SRestObjReq]: GET {requestUrl} returned error: {hwr.StatusCode}"); } - else - m_log.ErrorFormat( - "[SRestObjReq]: WebException for GET {0} {1} {2}", - requestUrl, typeof(TResponse).ToString(), e.Message); } + else + m_log.Error($"[SRestObjReq]: WebException for GET {requestUrl} {typeof(TResponse)} {e.Message}"); } catch (System.InvalidOperationException) { // This is what happens when there is invalid XML - m_log.DebugFormat("[SRestObjReq]: Invalid XML from GET {0} {1}", - requestUrl, typeof(TResponse).ToString()); + m_log.Debug($"[SRestObjReq]: Invalid XML from GET {requestUrl} {typeof(TResponse)}"); } catch (Exception e) { - m_log.DebugFormat("[SRestObjReq]: Exception on response from GET {0}: {1}", - requestUrl, e.Message); + m_log.Debug($"[SRestObjReq]: Exception on response from GET {requestUrl}: {e.Message}"); } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { - m_log.InfoFormat("[LOGHTTP]: Slow SRestObjReq GET {0} {1} took {2}ms, {3}bytes", - reqnum, requestUrl, tickdiff, rcvlen); + m_log.Info($"[LOGHTTP]: Slow SRestObjReq GET {reqnum} {requestUrl} took {tickdiff}ms, {rcvlen}bytes"); } else if (WebUtil.DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", - reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); } return deserial; } @@ -1447,43 +1382,41 @@ namespace OpenSim.Framework { public static TResponse LogAndDeserialize(int reqnum, Stream respStream, long contentLength) { - XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); + XmlSerializer deserializer = new (typeof(TResponse)); if (WebUtil.DebugLevel >= 5) { const int blockLength = 4096; byte[] dataBuffer = new byte[blockLength]; int curcount; - using (MemoryStream ms = new MemoryStream(4 * blockLength)) + using MemoryStream ms = new(4 * blockLength); + if (contentLength == -1) { - if(contentLength == -1) + while (true) { - while (true) - { - curcount = respStream.Read(dataBuffer, 0, blockLength); - if (curcount <= 0) - break; - ms.Write(dataBuffer, 0, curcount); - } + curcount = respStream.Read(dataBuffer, 0, blockLength); + if (curcount <= 0) + break; + ms.Write(dataBuffer, 0, curcount); } - else - { - int remaining = (int)contentLength; - while (remaining > 0) - { - curcount = respStream.Read(dataBuffer, 0, remaining); - if (curcount <= 0) - throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining)); - ms.Write(dataBuffer, 0, curcount); - remaining -= curcount; - } - } - - dataBuffer = ms.ToArray(); - WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(dataBuffer)); - - ms.Position = 0; - return (TResponse)deserializer.Deserialize(ms); } + else + { + int remaining = (int)contentLength; + while (remaining > 0) + { + curcount = respStream.Read(dataBuffer, 0, remaining); + if (curcount <= 0) + throw new EndOfStreamException($"End of stream reached with {remaining} bytes left to read"); + ms.Write(dataBuffer, 0, curcount); + remaining -= curcount; + } + } + + dataBuffer = ms.ToArray(); + WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(dataBuffer)); + + ms.Position = 0; + return (TResponse)deserializer.Deserialize(ms); } else { @@ -1501,18 +1434,19 @@ namespace OpenSim.Framework int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} XML-RPC '{1}' to {2}", - reqnum, method, url); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} XML-RPC '{method}' to {url}"); int tickstart = Util.EnvironmentTickCount(); string responseStr = null; try { - ArrayList SendParams = new ArrayList(); - SendParams.Add(ReqParams); + ArrayList SendParams = new() + { + ReqParams + }; - XmlRpcRequest Req = new XmlRpcRequest(method, SendParams); + XmlRpcRequest Req = new(method, SendParams); if (WebUtil.DebugLevel >= 5) { @@ -1534,14 +1468,13 @@ namespace OpenSim.Framework } catch (Exception e) { - m_log.Error("Error parsing XML-RPC response", e); + m_log.Error($"[LOGHTTP]: Error parsing XML-RPC response: {e.Message}"); } if (Resp.IsFault) { - m_log.DebugFormat( - "[LOGHTTP]: XML-RPC request {0} '{1}' to {2} FAILED: FaultCode={3}, FaultMessage={4}", - reqnum, method, url, Resp.FaultCode, Resp.FaultString); + m_log.Debug( + $"[LOGHTTP]: XML-RPC request {reqnum} '{method}' to {url} FAILED: FaultCode={Resp.FaultCode}, {Resp.FaultString}"); return null; } @@ -1562,7 +1495,7 @@ namespace OpenSim.Framework } else if (WebUtil.DebugLevel >= 4) { - m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff); + m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {tickdiff}ms"); } } } diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs index 202ff7a702..6d58968ce9 100644 --- a/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs @@ -824,7 +824,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends string[] parts = im.fromAgentName.Split(new char[] { '@' }); if (parts.Length == 2) { - string[] fl = parts[0].Trim().Split(new char[] { '.' }); + string[] fl = parts[0].Trim().Split(Util.SplitDotArray); if (fl.Length == 2) m_uMan.AddUser(new UUID(im.fromAgentID), fl[0], fl[1], "http://" + parts[1]); else