diff --git a/.github/workflows/dotnetci.yml b/.github/workflows/dotnetci.yml
index 2b964b5bc91..b879bcc2705 100644
--- a/.github/workflows/dotnetci.yml
+++ b/.github/workflows/dotnetci.yml
@@ -14,7 +14,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
- dotnet-version: 6.0.*
+ dotnet-version: 8.0.*
- name: Restore dependencies
run: dotnet restore
- name: Build
diff --git a/.nant/local.include b/.nant/local.include
deleted file mode 100644
index be79d1cfce4..00000000000
--- a/.nant/local.include
+++ /dev/null
@@ -1,289 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/BUILDING.md b/BUILDING.md
index 2d91710fad2..4eb287a38a9 100644
--- a/BUILDING.md
+++ b/BUILDING.md
@@ -1,10 +1,26 @@
+# git clone
+
+get or update source from git
+
+ `git clone git://opensimulator.org/git/opensim`
+
+
+
# Building on Windows
## Requirements
For building under Windows, the following is required:
* [Microsoft DotNet 6.0](https://dotnet.microsoft.com/en-us/download), version 6.0 or later.
- dotnet 6.0 is the LTS version and is recommended.
+ dotnet 8.0 is the LTS version and is recommended.
+ To building under Windows, the following is required:
+
+ * [dotnet 8.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)
+
+optionally also
+
+ * [Visual Studio .NET](https://visualstudio.microsoft.com/vs/features/net-development/), version 2022 or later
+
### Building
Prebuild is no longer used. There is a top level Solution (sln) and csproj files for each
@@ -18,7 +34,10 @@ Either command will do a NuGet restore (dotnet restore) to restore any required
kicking off a build using a current version of msbuild. The Csproj and SLN files are all designed to use the new
format for Msbuild which is simplified and really directly replaces what prebuild provided.
-Load the generated OpenSim.sln into Visual Studio .NET and build the solution.
+run
+ `compile.bat`
+
+Or load the generated OpenSim.sln into Visual Studio or Visual Studio Code and build the solution.
Configure, see below
@@ -28,10 +47,14 @@ The resulting build will be generated to ./build/{Debug|Release}/
## Requirements
- * [Mono > 5.0](https://www.mono-project.com/download/stable/#download-lin)
- * On some Linux distributions you may need to install additional packages.
- * [Microsoft DotNet 6.0](https://dotnet.microsoft.com/en-us/download), version 6.0 or later.
- dotnet 6.0 is the LTS version and is recommended.
+ * [dotnet 8.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)
+ * libgdiplus
+
+ if you have mono 6.x complete, you already have libgdiplus, otherwise you need to install it
+ using a package manager for your operating system, like apt, brew, macports, etc
+ for example on debian:
+
+ `apt-get update && apt-get install -y apt-utils libgdiplus libc6-dev`
### Building
Prebuild is no longer used. There is a top level Solution (sln) and csproj files for each
diff --git a/Directory.Build.props b/Directory.Build.props
index bc5ea01bfa8..8675639bab1 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,6 +1,10 @@
false
+ disable
+ disable
+ false
+ true
$(SolutionDir)\obj\$(Configuration)\$(MSBuildProjectName)\
$(SolutionDir)\obj\$(Configuration)\$(MSBuildProjectName)\
$(SolutionDir)\build\$(Configuration)\$(AssemblyName)\
diff --git a/OpenSim.sln b/OpenSim.sln
index 153dbe5b516..1264c9ea0f9 100644
--- a/OpenSim.sln
+++ b/OpenSim.sln
@@ -21,8 +21,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Capabilities", "Ope
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Capabilities.Handlers", "OpenSim\Capabilities\Handlers\OpenSim.Capabilities.Handlers.csproj", "{002BDDF6-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Capabilities.Handlers.Tests", "OpenSim\Capabilities\Handlers\OpenSim.Capabilities.Handlers.Tests.csproj", "{507CDB79-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.ConsoleClient", "OpenSim\ConsoleClient\OpenSim.ConsoleClient.csproj", "{CB348113-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data", "OpenSim\Data\OpenSim.Data.csproj", "{7E218E2D-0000-0000-0000-000000000000}"
@@ -35,8 +33,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data.PGSQL", "OpenS
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data.SQLite", "OpenSim\Data\SQLite\OpenSim.Data.SQLite.csproj", "{675096A5-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data.Tests", "OpenSim\Data\Tests\OpenSim.Data.Tests.csproj", "{37FD59A6-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework", "OpenSim\Framework\OpenSim.Framework.csproj", "{BCCDBB55-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.AssetLoader.Filesystem", "OpenSim\Framework\AssetLoader\Filesystem\OpenSim.Framework.AssetLoader.Filesystem.csproj", "{384A4FAB-0000-0000-0000-000000000000}"
@@ -47,46 +43,26 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Monitorin
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Serialization", "OpenSim\Framework\Serialization\OpenSim.Framework.Serialization.csproj", "{BD63E665-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Serialization.Tests", "OpenSim\Framework\Serialization\Tests\OpenSim.Framework.Serialization.Tests.csproj", "{B3B5B07A-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Servers", "OpenSim\Framework\Servers\OpenSim.Framework.Servers.csproj", "{726D540D-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Servers.HttpServer", "OpenSim\Framework\Servers\HttpServer\OpenSim.Framework.Servers.HttpServer.csproj", "{159EC5C2-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Servers.Tests", "OpenSim\Framework\Servers\Tests\OpenSim.Framework.Servers.Tests.csproj", "{743E90C2-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Framework.Tests", "OpenSim\Framework\Tests\OpenSim.Framework.Tests.csproj", "{FA62D900-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ClientStack.LindenCaps", "OpenSim\Region\ClientStack\Linden\Caps\OpenSim.Region.ClientStack.LindenCaps.csproj", "{574BCA63-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ClientStack.LindenCaps.Tests", "OpenSim\Region\ClientStack\Linden\Caps\OpenSim.Region.ClientStack.LindenCaps.Tests.csproj", "{A461C3AC-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ClientStack.LindenUDP", "OpenSim\Region\ClientStack\Linden\UDP\OpenSim.Region.ClientStack.LindenUDP.csproj", "{E7F1E4AB-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ClientStack.LindenUDP.Tests", "OpenSim\Region\ClientStack\Linden\UDP\Tests\OpenSim.Region.ClientStack.LindenUDP.Tests.csproj", "{6E5280E2-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.CoreModules", "OpenSim\Region\CoreModules\OpenSim.Region.CoreModules.csproj", "{B60B8DCD-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.CoreModules.Tests", "OpenSim\Region\CoreModules\OpenSim.Region.CoreModules.Tests.csproj", "{3B99D6D0-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.Framework", "OpenSim\Region\Framework\OpenSim.Region.Framework.csproj", "{C98F6D97-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.Framework.Tests", "OpenSim\Region\Framework\OpenSim.Region.Framework.Tests.csproj", "{BEF3BCBC-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.OptionalModules", "OpenSim\Region\OptionalModules\OpenSim.Region.OptionalModules.csproj", "{BAF8E8F2-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.BasicPhysics", "OpenSim\Region\PhysicsModules\BasicPhysics\OpenSim.Region.PhysicsModule.BasicPhysics.csproj", "{BAC989A5-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.BulletS", "OpenSim\Region\PhysicsModules\BulletS\OpenSim.Region.PhysicsModule.BulletS.csproj", "{223BC46D-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.BulletS.Tests", "OpenSim\Region\PhysicsModules\BulletS\Tests\OpenSim.Region.PhysicsModule.BulletS.Tests.csproj", "{7364753A-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.Meshing", "OpenSim\Region\PhysicsModules\Meshing\OpenSim.Region.PhysicsModule.Meshing.csproj", "{5ECE503F-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.Ode", "OpenSim\Region\PhysicsModules\Ode\OpenSim.Region.PhysicsModule.Ode.csproj", "{BD76F0CA-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.Ode.Tests", "OpenSim\Region\PhysicsModules\Ode\Tests\OpenSim.Region.PhysicsModule.Ode.Tests.csproj", "{968D2EA9-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.POS", "OpenSim\Region\PhysicsModules\POS\OpenSim.Region.PhysicsModule.POS.csproj", "{2400666E-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.PhysicsModule.ubOde", "OpenSim\Region\PhysicsModules\ubOde\OpenSim.Region.PhysicsModule.ubOde.csproj", "{AC52DE31-0000-0000-0000-000000000000}"
@@ -107,20 +83,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ScriptEngine
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ScriptEngine.Shared.Instance", "OpenSim\Region\ScriptEngine\Shared\Instance\OpenSim.Region.ScriptEngine.Shared.Instance.csproj", "{B185E548-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ScriptEngine.Tests", "OpenSim\Region\ScriptEngine\OpenSim.Region.ScriptEngine.Tests.csproj", "{CBDD2219-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ScriptEngine.XEngine", "OpenSim\Region\ScriptEngine\XEngine\OpenSim.Region.ScriptEngine.XEngine.csproj", "{798F0488-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ScriptEngine.XEngine.Api.Runtime", "OpenSim\Region\ScriptEngine\XEngine\Api\Runtime\OpenSim.Region.ScriptEngine.XEngine.Api.Runtime.csproj", "{4A4B6F6C-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Region.ScriptEngine.YEngine", "OpenSim\Region\ScriptEngine\YEngine\OpenSim.Region.ScriptEngine.YEngine.csproj", "{798B4867-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Server.Base", "OpenSim\Server\Base\OpenSim.Server.Base.csproj", "{2E0569BB-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Server.Handlers", "OpenSim\Server\Handlers\OpenSim.Server.Handlers.csproj", "{ED041501-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Server.Handlers.Tests", "OpenSim\Server\Handlers\OpenSim.Server.Handlers.Tests.csproj", "{AC0DDB9E-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.AssetService", "OpenSim\Services\AssetService\OpenSim.Services.AssetService.csproj", "{7FDD1B76-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.AuthenticationService", "OpenSim\Services\AuthenticationService\OpenSim.Services.AuthenticationService.csproj", "{76495B84-0000-0000-0000-000000000000}"
@@ -149,8 +117,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.Interfaces
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.InventoryService", "OpenSim\Services\InventoryService\OpenSim.Services.InventoryService.csproj", "{0066981A-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.InventoryService.Tests", "OpenSim\Services\InventoryService\Tests\OpenSim.Services.InventoryService.Tests.csproj", "{D4979419-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.LLLoginService", "OpenSim\Services\LLLoginService\OpenSim.Services.LLLoginService.csproj", "{84F83E53-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.MapImageService", "OpenSim\Services\MapImageService\OpenSim.Services.MapImageService.csproj", "{B03715E7-0000-0000-0000-000000000000}"
@@ -165,22 +131,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.UserAccoun
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Services.UserProfilesService", "OpenSim\Services\UserProfilesService\OpenSim.Services.UserProfilesService.csproj", "{B4C57E7D-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tests", "OpenSim\Tests\OpenSim.Tests.csproj", "{CCCB2DA6-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tests.Clients.AssetClient", "OpenSim\Tests\Clients\Assets\OpenSim.Tests.Clients.AssetClient.csproj", "{5BC4E133-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tests.Common", "OpenSim\Tests\Common\OpenSim.Tests.Common.csproj", "{CC43930F-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tests.Performance", "OpenSim\Tests\Performance\OpenSim.Tests.Performance.csproj", "{24A774FE-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tests.Permissions", "OpenSim\Tests\Permissions\OpenSim.Tests.Permissions.csproj", "{E0DDF05C-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tests.Stress", "OpenSim\Tests\Stress\OpenSim.Tests.Stress.csproj", "{660D26BC-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tools.Configger", "OpenSim\Tools\Configger\OpenSim.Tools.Configger.csproj", "{2F0C334A-0000-0000-0000-000000000000}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Tools.lslc", "OpenSim\Tools\Compiler\OpenSim.Tools.lslc.csproj", "{12EC22DE-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSimMutelist.Modules", "addon-modules\OpenSimMutelist\Modules\OpenSimMutelist.Modules.csproj", "{87C4E6E3-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSimSearch.Modules", "addon-modules\OpenSimSearch\Modules\OpenSimSearch.Modules.csproj", "{BE5D1132-0000-0000-0000-000000000000}"
@@ -189,8 +139,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "pCampBot", "OpenSim\Tools\p
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Robust", "OpenSim\Server\Robust.csproj", "{6E64F01D-0000-0000-0000-000000000000}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Robust.Tests", "OpenSim\Tests\Robust\Robust.Tests.csproj", "{D2E26E14-0000-0000-0000-000000000000}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SmartThreadPool", "ThirdParty\SmartThreadPool\SmartThreadPool.csproj", "{8C618053-0000-0000-0000-000000000000}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSim.Data.MySQL.MoneyData", "addon-modules\OpenSim.Data.MySQL.MoneyData\OpenSim.Data.MySQL.MoneyData\OpenSim.Data.MySQL.MoneyData.csproj", "{A9CF27A6-3E23-4A10-82DA-604CA8C577D9}"
@@ -241,10 +189,6 @@ Global
{002BDDF6-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{002BDDF6-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{002BDDF6-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {507CDB79-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {507CDB79-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {507CDB79-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {507CDB79-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{CB348113-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CB348113-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CB348113-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -269,10 +213,6 @@ Global
{675096A5-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{675096A5-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{675096A5-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {37FD59A6-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {37FD59A6-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {37FD59A6-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {37FD59A6-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{BCCDBB55-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BCCDBB55-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BCCDBB55-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -293,10 +233,6 @@ Global
{BD63E665-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD63E665-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD63E665-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {B3B5B07A-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {B3B5B07A-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {B3B5B07A-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {B3B5B07A-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{726D540D-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{726D540D-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{726D540D-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -305,46 +241,22 @@ Global
{159EC5C2-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{159EC5C2-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{159EC5C2-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {743E90C2-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {743E90C2-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {743E90C2-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {743E90C2-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {FA62D900-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {FA62D900-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {FA62D900-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {FA62D900-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{574BCA63-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{574BCA63-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{574BCA63-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{574BCA63-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {A461C3AC-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {A461C3AC-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {A461C3AC-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {A461C3AC-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{E7F1E4AB-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7F1E4AB-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7F1E4AB-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7F1E4AB-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {6E5280E2-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {6E5280E2-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6E5280E2-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {6E5280E2-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{B60B8DCD-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B60B8DCD-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B60B8DCD-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B60B8DCD-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {3B99D6D0-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3B99D6D0-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3B99D6D0-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3B99D6D0-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{C98F6D97-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C98F6D97-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C98F6D97-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C98F6D97-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {BEF3BCBC-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {BEF3BCBC-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {BEF3BCBC-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {BEF3BCBC-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{BAF8E8F2-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAF8E8F2-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAF8E8F2-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -357,22 +269,10 @@ Global
{223BC46D-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{223BC46D-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{223BC46D-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {7364753A-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {7364753A-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7364753A-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {7364753A-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{5ECE503F-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5ECE503F-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5ECE503F-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5ECE503F-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {BD76F0CA-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {BD76F0CA-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {BD76F0CA-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {BD76F0CA-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {968D2EA9-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {968D2EA9-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {968D2EA9-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {968D2EA9-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{2400666E-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2400666E-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2400666E-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -413,18 +313,6 @@ Global
{B185E548-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B185E548-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B185E548-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {CBDD2219-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CBDD2219-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CBDD2219-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CBDD2219-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {798F0488-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {798F0488-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {798F0488-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {798F0488-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {4A4B6F6C-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4A4B6F6C-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4A4B6F6C-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4A4B6F6C-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{798B4867-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{798B4867-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{798B4867-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -437,10 +325,6 @@ Global
{ED041501-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ED041501-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ED041501-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {AC0DDB9E-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {AC0DDB9E-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {AC0DDB9E-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {AC0DDB9E-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{7FDD1B76-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7FDD1B76-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7FDD1B76-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -497,10 +381,6 @@ Global
{0066981A-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0066981A-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0066981A-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {D4979419-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {D4979419-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {D4979419-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {D4979419-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{84F83E53-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84F83E53-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84F83E53-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -529,38 +409,6 @@ Global
{B4C57E7D-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B4C57E7D-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B4C57E7D-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {CCCB2DA6-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CCCB2DA6-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CCCB2DA6-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CCCB2DA6-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {5BC4E133-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {5BC4E133-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {5BC4E133-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5BC4E133-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {CC43930F-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CC43930F-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CC43930F-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CC43930F-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {24A774FE-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {24A774FE-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {24A774FE-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {24A774FE-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {E0DDF05C-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {E0DDF05C-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E0DDF05C-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {E0DDF05C-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {660D26BC-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {660D26BC-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {660D26BC-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {660D26BC-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {2F0C334A-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2F0C334A-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2F0C334A-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2F0C334A-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {12EC22DE-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {12EC22DE-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {12EC22DE-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {12EC22DE-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{87C4E6E3-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{87C4E6E3-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{87C4E6E3-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -577,10 +425,6 @@ Global
{6E64F01D-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E64F01D-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E64F01D-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
- {D2E26E14-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {D2E26E14-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {D2E26E14-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {D2E26E14-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU
{8C618053-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8C618053-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8C618053-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU
diff --git a/OpenSim/Addons/Groups/GroupsMessagingModule.cs b/OpenSim/Addons/Groups/GroupsMessagingModule.cs
index dc52320b32e..e5aa79b8246 100755
--- a/OpenSim/Addons/Groups/GroupsMessagingModule.cs
+++ b/OpenSim/Addons/Groups/GroupsMessagingModule.cs
@@ -325,7 +325,7 @@ public void SendMessageToGroup(
im.RegionID = thisClient.Scene.RegionInfo.RegionID.Guid;
}
- if ((im.binaryBucket == null) || (im.binaryBucket.Length == 0) || ((im.binaryBucket.Length == 1 && im.binaryBucket[0] == 0)))
+ if (im.binaryBucket is null || im.binaryBucket.Length == 0 || (im.binaryBucket.Length == 1 && im.binaryBucket[0] == 0))
{
ExtendedGroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), groupID, null);
if (groupInfo != null)
diff --git a/OpenSim/Addons/Groups/GroupsModule.cs b/OpenSim/Addons/Groups/GroupsModule.cs
index 314a6057953..cfca4e6003e 100755
--- a/OpenSim/Addons/Groups/GroupsModule.cs
+++ b/OpenSim/Addons/Groups/GroupsModule.cs
@@ -1113,7 +1113,7 @@ public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID,
{
m_log.DebugFormat("[Groups]: Group Notice {0} not found, composing empty message.", groupNoticeID);
msg.fromAgentID = UUID.Zero.Guid;
- msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); ;
+ msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentName = string.Empty;
msg.message = string.Empty;
msg.binaryBucket = Array.Empty(); ;
@@ -1275,7 +1275,7 @@ public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
- msg.binaryBucket = Array.Empty(); ;
+ msg.binaryBucket = Array.Empty();
OutgoingInstantMessage(msg, ejecteeID);
}
@@ -1293,7 +1293,7 @@ public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
- msg.binaryBucket = Array.Empty(); ;
+ msg.binaryBucket = Array.Empty();
OutgoingInstantMessage(msg, agentID);
}
@@ -1575,17 +1575,12 @@ public void NotifyChange(UUID groupID)
private string GetRequestingAgentIDStr(IClientAPI client)
{
- return GetRequestingAgentID(client).ToString();
+ return client is null ? UUID.ZeroString : client.AgentId.ToString();
}
private UUID GetRequestingAgentID(IClientAPI client)
{
- UUID requestingAgentID = UUID.Zero;
- if (client != null)
- {
- requestingAgentID = client.AgentId;
- }
- return requestingAgentID;
+ return client is null ? UUID.Zero : client.AgentId;
}
}
diff --git a/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs b/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs
index 5bca6540922..98a9d4627d7 100644
--- a/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs
+++ b/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs
@@ -285,8 +285,7 @@ private Dictionary MakeRequest(string method, Dictionary replyData = ServerUtils.ParseXmlResponse(
- reply);
+ Dictionary replyData = ServerUtils.ParseXmlResponse(reply);
return replyData;
}
diff --git a/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnectorModule.cs b/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnectorModule.cs
index dd06c958262..580221fa639 100644
--- a/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnectorModule.cs
+++ b/OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnectorModule.cs
@@ -164,12 +164,11 @@ private void OnNewClient(IClientAPI client)
void OnCompleteMovementToRegion(IClientAPI client, bool arg2)
{
- object sp = null;
- if (client.Scene.TryGetScenePresence(client.AgentId, out sp))
+ if (client.SceneAgent is ScenePresence sp)
{
- if (sp is ScenePresence && ((ScenePresence)sp).PresenceType != PresenceType.Npc)
+ if (sp.PresenceType != PresenceType.Npc)
{
- AgentCircuitData aCircuit = ((ScenePresence)sp).Scene.AuthenticateHandler.GetAgentCircuitData(client.AgentId);
+ AgentCircuitData aCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(client.AgentId);
if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 &&
m_OfflineIM != null && m_Messaging != null)
{
@@ -460,7 +459,7 @@ public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID
public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
- return m_LocalGroupsConnector.GetAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID); ;
+ return m_LocalGroupsConnector.GetAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID);
}
public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
diff --git a/OpenSim/Addons/Groups/Local/GroupsServiceLocalConnectorModule.cs b/OpenSim/Addons/Groups/Local/GroupsServiceLocalConnectorModule.cs
index cee1c9c8ff5..312d4adf690 100644
--- a/OpenSim/Addons/Groups/Local/GroupsServiceLocalConnectorModule.cs
+++ b/OpenSim/Addons/Groups/Local/GroupsServiceLocalConnectorModule.cs
@@ -240,7 +240,7 @@ public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID
public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
- return m_GroupsService.GetAgentToGroupInvite(RequestingAgentID, inviteID); ;
+ return m_GroupsService.GetAgentToGroupInvite(RequestingAgentID, inviteID);
}
public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
@@ -285,7 +285,7 @@ public void UpdateMembership(string RequestingAgentID, string AgentID, UUID Grou
public ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID)
{
- return m_GroupsService.GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID); ;
+ return m_GroupsService.GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID);
}
public List GetAgentGroupMemberships(string RequestingAgentID, string AgentID)
diff --git a/OpenSim/Addons/Groups/OpenSim.Addons.Groups.csproj b/OpenSim/Addons/Groups/OpenSim.Addons.Groups.csproj
index 520c13a59b1..03f11ae98a2 100644
--- a/OpenSim/Addons/Groups/OpenSim.Addons.Groups.csproj
+++ b/OpenSim/Addons/Groups/OpenSim.Addons.Groups.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Addons.Groups
http://opensimulator.org
OpenSim.Addons.Groups
@@ -12,6 +12,7 @@
+
@@ -30,9 +31,6 @@
..\..\..\bin\OpenMetaverseTypes.dll
False
-
- False
-
diff --git a/OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnectorModule.cs b/OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnectorModule.cs
index a52a91577e8..1fc3afd1efd 100644
--- a/OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnectorModule.cs
+++ b/OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnectorModule.cs
@@ -327,7 +327,7 @@ public List GetAgentGroupRoles(string RequestingAgentID, string
{
return m_CacheWrapper.GetAgentGroupRoles(RequestingAgentID, AgentID, GroupID, delegate
{
- return m_GroupsService.GetAgentGroupRoles(RequestingAgentID, AgentID, GroupID);
+ return m_GroupsService.GetAgentGroupRoles(RequestingAgentID, AgentID, GroupID); ;
});
}
diff --git a/OpenSim/Addons/OfflineIM/OpenSim.Addons.OfflineIM.csproj b/OpenSim/Addons/OfflineIM/OpenSim.Addons.OfflineIM.csproj
index 1bb689306ea..f7a0809781a 100644
--- a/OpenSim/Addons/OfflineIM/OpenSim.Addons.OfflineIM.csproj
+++ b/OpenSim/Addons/OfflineIM/OpenSim.Addons.OfflineIM.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Addons.OfflineIM
http://opensimulator.org
OpenSim.Addons.OfflineIM
@@ -9,6 +9,7 @@
+
@@ -23,9 +24,6 @@
..\..\..\bin\OpenMetaverseTypes.dll
False
-
- False
-
diff --git a/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRemoteConnector.cs b/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRemoteConnector.cs
index e0022754f72..b4de67b4cd1 100644
--- a/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRemoteConnector.cs
+++ b/OpenSim/Addons/OfflineIM/Remote/OfflineIMServiceRemoteConnector.cs
@@ -93,29 +93,37 @@ public List GetMessages(UUID principalID)
if (ret == null)
return ims;
- if (!ret.ContainsKey("RESULT"))
+ if (!ret.TryGetValue("RESULT", out object resultobj))
return ims;
- string result = ret["RESULT"].ToString();
- if (result == "NULL" || result.ToLower() == "false")
+ if(resultobj is string result)
{
- string reason = ret.ContainsKey("REASON") ? ret["REASON"].ToString() : "Unknown error";
- m_log.DebugFormat("[OfflineIM.V2.RemoteConnector]: GetMessages for {0} failed: {1}", principalID, reason);
+ if (result == "NULL" || result.Equals("false", StringComparison.InvariantCultureIgnoreCase))
+ {
+ if (ret.TryGetValue("REASON", out object rso))
+ m_log.Debug($"[OfflineIM.V2.RemoteConnector]: GetMessages for {principalID} failed: {rso}");
+ else
+ m_log.Debug($"[OfflineIM.V2.RemoteConnector]: GetMessages for {principalID} failed: Unknown error");
return ims;
}
-
- foreach (object v in ((Dictionary)ret["RESULT"]).Values)
+ }
+ else if(resultobj is Dictionary resultdic)
{
- GridInstantMessage m = OfflineIMDataUtils.GridInstantMessage((Dictionary)v);
+ foreach (object v in resultdic.Values)
+ {
+ if (v is Dictionary vdic)
+ {
+ GridInstantMessage m = OfflineIMDataUtils.GridInstantMessage(vdic);
ims.Add(m);
}
+ }
+ }
return ims;
}
public bool StoreMessage(GridInstantMessage im, out string reason)
{
- reason = string.Empty;
Dictionary sendData = OfflineIMDataUtils.GridInstantMessage(im);
Dictionary ret = MakeRequest("STORE", sendData);
@@ -126,16 +134,20 @@ public bool StoreMessage(GridInstantMessage im, out string reason)
return false;
}
- if (ret.ContainsKey("RESULT") == true)
+ if (ret.TryGetValue("RESULT", out object o))
{
- string result = ret["RESULT"].ToString();
- if (result == "NULL" || result.ToLower() == "false")
+ string result = o.ToString();
+ if (result == "NULL" || result.Equals("false", StringComparison.InvariantCultureIgnoreCase))
{
- reason = ret.ContainsKey("REASON") ? ret["REASON"].ToString() : "Unknown error";
+ if(ret.TryGetValue("REASON", out object ro))
+ reason = ro.ToString();
+ else
+ reason = "Unknown error";
return false;
}
}
+ reason = string.Empty;
return true;
}
@@ -163,8 +175,7 @@ private Dictionary MakeRequest(string method, Dictionary replyData = ServerUtils.ParseXmlResponse(
- reply);
+ Dictionary replyData = ServerUtils.ParseXmlResponse(reply);
return replyData;
}
diff --git a/OpenSim/Addons/OfflineIM/Service/OfflineIMService.cs b/OpenSim/Addons/OfflineIM/Service/OfflineIMService.cs
index bf578a0b9ed..57c724a171b 100644
--- a/OpenSim/Addons/OfflineIM/Service/OfflineIMService.cs
+++ b/OpenSim/Addons/OfflineIM/Service/OfflineIMService.cs
@@ -28,10 +28,7 @@
using System;
using System.Collections.Generic;
using System.IO;
-using System.Reflection;
-using System.Runtime.Serialization;
using System.Text;
-using System.Timers;
using System.Xml;
using System.Xml.Serialization;
using log4net;
@@ -40,21 +37,59 @@
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
+using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
namespace OpenSim.OfflineIM
{
- public class OfflineIMService : OfflineIMServiceBase, IOfflineIMService
+ public class OfflineIMService : ServiceBase, IOfflineIMService
{
-// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- private const int MAX_IM = 25;
-
+ //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+ private IOfflineIMData m_Database = null;
+ private int m_MaxOfflineIMs = 25;
private XmlSerializer m_serializer;
private static bool m_Initialized = false;
- public OfflineIMService(IConfigSource config)
- : base(config)
+ public OfflineIMService(IConfigSource config) : base(config)
{
+ string dllName = string.Empty;
+ string connString = string.Empty;
+ string realm = "im_offline";
+
+ //
+ // Try reading the [DatabaseService] section, if it exists
+ //
+ IConfig dbConfig = config.Configs["DatabaseService"];
+ if (dbConfig is not null)
+ {
+ if (dllName.Length == 0)
+ dllName = dbConfig.GetString("StorageProvider", string.Empty);
+ if (connString.Length == 0)
+ connString = dbConfig.GetString("ConnectionString", string.Empty);
+ }
+
+ //
+ // [Messaging] section overrides [DatabaseService], if it exists
+ //
+ IConfig imConfig = config.Configs["Messaging"];
+ if (imConfig is not null)
+ {
+ dllName = imConfig.GetString("StorageProvider", dllName);
+ connString = imConfig.GetString("ConnectionString", connString);
+ realm = imConfig.GetString("Realm", realm);
+ m_MaxOfflineIMs = imConfig.GetInt("MaxOfflineIMs", m_MaxOfflineIMs);
+ }
+
+ //
+ // We tried, but this doesn't exist. We can't proceed.
+ //
+ if (string.IsNullOrEmpty(dllName))
+ throw new Exception("No StorageProvider configured");
+
+ m_Database = LoadPlugin(dllName, new Object[] { connString, realm });
+ if (m_Database is null)
+ throw new Exception("Could not find a storage interface in the given module " + dllName);
+
m_serializer = new XmlSerializer(typeof(GridInstantMessage));
if (!m_Initialized)
{
@@ -68,8 +103,7 @@ public List GetMessages(UUID principalID)
List ims = new List();
OfflineIMData[] messages = m_Database.Get("PrincipalID", principalID.ToString());
-
- if (messages == null || (messages != null && messages.Length == 0))
+ if (messages is null || messages.Length == 0)
return ims;
foreach (OfflineIMData m in messages)
@@ -94,7 +128,7 @@ public bool StoreMessage(GridInstantMessage im, out string reason)
// Check limits
UUID principalID = new UUID(im.toAgentID);
long count = m_Database.GetCount("PrincipalID", principalID.ToString());
- if (count >= MAX_IM)
+ if (count >= m_MaxOfflineIMs)
{
reason = "Number of offline IMs has maxed out";
return false;
diff --git a/OpenSim/Addons/OfflineIM/Service/OfflineIMServiceBase.cs b/OpenSim/Addons/OfflineIM/Service/OfflineIMServiceBase.cs
deleted file mode 100644
index d68ae3d7c52..00000000000
--- a/OpenSim/Addons/OfflineIM/Service/OfflineIMServiceBase.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Nini.Config;
-using OpenSim.Framework;
-using OpenSim.Data;
-using OpenSim.Services.Interfaces;
-using OpenSim.Services.Base;
-
-namespace OpenSim.OfflineIM
-{
- public class OfflineIMServiceBase : ServiceBase
- {
- protected IOfflineIMData m_Database = null;
-
- public OfflineIMServiceBase(IConfigSource config)
- : base(config)
- {
- string dllName = String.Empty;
- string connString = String.Empty;
- string realm = "im_offline";
-
- //
- // Try reading the [DatabaseService] section, if it exists
- //
- IConfig dbConfig = config.Configs["DatabaseService"];
- if (dbConfig != null)
- {
- if (dllName.Length == 0)
- dllName = dbConfig.GetString("StorageProvider", String.Empty);
- if (connString.Length == 0)
- connString = dbConfig.GetString("ConnectionString", String.Empty);
- }
-
- //
- // [Messaging] section overrides [DatabaseService], if it exists
- //
- IConfig imConfig = config.Configs["Messaging"];
- if (imConfig != null)
- {
- dllName = imConfig.GetString("StorageProvider", dllName);
- connString = imConfig.GetString("ConnectionString", connString);
- realm = imConfig.GetString("Realm", realm);
- }
-
- //
- // We tried, but this doesn't exist. We can't proceed.
- //
- if (string.IsNullOrEmpty(dllName))
- throw new Exception("No StorageProvider configured");
-
- m_Database = LoadPlugin(dllName, new Object[] { connString, realm });
- if (m_Database == null)
- throw new Exception("Could not find a storage interface in the given module " + dllName);
- }
- }
-}
diff --git a/OpenSim/ApplicationPlugins/LoadRegions/OpenSim.ApplicationPlugins.LoadRegions.csproj b/OpenSim/ApplicationPlugins/LoadRegions/OpenSim.ApplicationPlugins.LoadRegions.csproj
index 2093ded0dcd..91189d3a665 100644
--- a/OpenSim/ApplicationPlugins/LoadRegions/OpenSim.ApplicationPlugins.LoadRegions.csproj
+++ b/OpenSim/ApplicationPlugins/LoadRegions/OpenSim.ApplicationPlugins.LoadRegions.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.ApplicationPlugins.LoadRegions
http://opensimulator.org
OpenSim
diff --git a/OpenSim/ApplicationPlugins/RegionModulesController/OpenSim.ApplicationPlugins.RegionModulesController.csproj b/OpenSim/ApplicationPlugins/RegionModulesController/OpenSim.ApplicationPlugins.RegionModulesController.csproj
index 8533e15a33f..cdfcf1d0866 100644
--- a/OpenSim/ApplicationPlugins/RegionModulesController/OpenSim.ApplicationPlugins.RegionModulesController.csproj
+++ b/OpenSim/ApplicationPlugins/RegionModulesController/OpenSim.ApplicationPlugins.RegionModulesController.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.ApplicationPlugins.RegionModulesController
http://opensimulator.org
OpenSim
@@ -10,6 +10,7 @@
+
{1}\n",i,m_texture.FaceTextures[i].TextureID);
+ sb.AppendLine($"Texture: {i} --> {m_texture.FaceTextures[i].TextureID}");
foreach (AvatarWearable awear in m_wearables)
{
for (int i = 0; i < awear.Count; i++)
- s += String.Format("Wearable: item={0}, asset={1}\n",awear[i].ItemID,awear[i].AssetID);
+ sb.AppendLine($"Wearable: item={awear[i].ItemID}, asset={awear[i].AssetID}");
}
- s += "Visual Params: ";
- // for (uint j = 0; j < AvatarAppearance.VISUALPARAM_COUNT; j++)
+ sb.Append("Visual Params: ");
+ //for (uint j = 0; j < AvatarAppearance.VISUALPARAM_COUNT; j++)
for (uint j = 0; j < m_visualparams.Length; j++)
- s += String.Format("{0},",m_visualparams[j]);
- s += "\n";
+ {
+ sb.Append(m_visualparams[j]);
+ sb.Append(',');
+ }
+ sb.Append('\n');
- return s;
+ return sb.ToString();
}
// DEBUG OFF
@@ -539,16 +542,20 @@ internal void AppendAttachment(AvatarAttachment attach)
lock (m_attachments)
{
- if (!m_attachments.ContainsKey(attach.AttachPoint))
- m_attachments[attach.AttachPoint] = new List();
+ ref List atlst = ref CollectionsMarshal.GetValueRefOrAddDefault(m_attachments, attach.AttachPoint, out bool ex);
+ if(!ex)
+ {
+ atlst = new List() { attach };
+ return;
+ }
- foreach (AvatarAttachment prev in m_attachments[attach.AttachPoint])
+ foreach (AvatarAttachment prev in atlst)
{
if (prev.ItemID.Equals(attach.ItemID))
return;
}
- m_attachments[attach.AttachPoint].Add(attach);
+ atlst.Add(attach);
}
}
@@ -560,8 +567,7 @@ internal void ReplaceAttachment(AvatarAttachment attach)
lock (m_attachments)
{
- m_attachments[attach.AttachPoint] = new List();
- m_attachments[attach.AttachPoint].Add(attach);
+ m_attachments[attach.AttachPoint] = new List() { attach };
}
}
@@ -609,10 +615,7 @@ public bool SetAttachment(int attachpoint, UUID item, UUID asset)
if (!existingAttachment.AssetID.IsZero() && existingAttachment.AttachPoint == (attachpoint & 0x7F))
{
- m_log.DebugFormat(
- "[AVATAR APPEARANCE]: Ignoring attempt to attach an already attached item {0} at point {1}",
- item, attachpoint);
-
+ m_log.Debug($"[AVATAR APPEARANCE]: Ignoring attach of an already attached item {item} at point {attachpoint}");
return false;
}
else
diff --git a/OpenSim/Framework/AvatarWearable.cs b/OpenSim/Framework/AvatarWearable.cs
index 6435307b98c..32de787ed7a 100644
--- a/OpenSim/Framework/AvatarWearable.cs
+++ b/OpenSim/Framework/AvatarWearable.cs
@@ -185,11 +185,8 @@ public void Clear()
public void RemoveItem(UUID itemID)
{
- if (m_items.ContainsKey(itemID))
- {
- m_ids.Remove(itemID);
- m_items.Remove(itemID);
- }
+ m_ids.Remove(itemID);
+ m_items.Remove(itemID);
}
public void RemoveAsset(UUID assetID)
@@ -225,9 +222,7 @@ public WearableItem this [int idx]
public UUID GetAsset(UUID itemID)
{
- if (!m_items.ContainsKey(itemID))
- return UUID.Zero;
- return m_items[itemID];
+ return m_items.TryGetValue(itemID, out UUID id) ? id : UUID.Zero;
}
public static AvatarWearable[] DefaultWearables
diff --git a/OpenSim/Framework/BasicDOSProtector.cs b/OpenSim/Framework/BasicDOSProtector.cs
index f1ff18f5cb0..c80bee56220 100644
--- a/OpenSim/Framework/BasicDOSProtector.cs
+++ b/OpenSim/Framework/BasicDOSProtector.cs
@@ -84,8 +84,7 @@ public BasicDOSProtector(BasicDosProtectorOptions options)
}
foreach (string str in removes)
{
- m_log.InfoFormat("[{0}] client: {1} is no longer blocked.",
- _options.ReportingName, str);
+ m_log.Info($"[{_options.ReportingName}] client: {str} is no longer blocked.");
}
_blockLockSlim.EnterReadLock();
if (_tempBlocked.Count > 0)
@@ -104,7 +103,7 @@ public BasicDOSProtector(BasicDosProtectorOptions options)
public bool IsBlocked(string key)
{
bool ret = false;
- _blockLockSlim.EnterReadLock();
+ _blockLockSlim.EnterReadLock();
ret = _tempBlocked.ContainsKey(key);
_blockLockSlim.ExitReadLock();
return ret;
@@ -141,11 +140,8 @@ public bool Process(string key, string endpoint)
if (_options.MaxConcurrentSessions > 0)
{
- int sessionscount = 0;
-
_sessionLockSlim.EnterReadLock();
- if (_sessions.ContainsKey(key))
- sessionscount = _sessions[key];
+ _sessions.TryGetValue(key, out int sessionscount);
_sessionLockSlim.ExitReadLock();
if (sessionscount > _options.MaxConcurrentSessions)
@@ -160,7 +156,7 @@ public bool Process(string key, string endpoint)
Util.EnvironmentTickCount() +
(int) _options.ForgetTimeSpan.TotalMilliseconds);
_forgetTimer.Enabled = true;
- m_log.WarnFormat("[{0}]: client: {1} is blocked for {2} milliseconds based on concurrency, X-ForwardedForAllowed status is {3}, endpoint:{4}", _options.ReportingName, clientstring, _options.ForgetTimeSpan.TotalMilliseconds, _options.AllowXForwardedFor, endpoint);
+ m_log.Warn($"[{_options.ReportingName}]: client: {clientstring} is blocked for {_options.ForgetTimeSpan.TotalMilliseconds}ms based on concurrency, X-ForwardedForAllowed status is {_options.AllowXForwardedFor}, endpoint:{_options.AllowXForwardedFor}");
}
else
@@ -241,8 +237,7 @@ private bool DeeperInspection(string key, string endpoint)
_tempBlocked[clientstring] = Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds;
_blockLockSlim.ExitWriteLock();
- m_log.WarnFormat("[{0}]: client: {1} is blocked for {2} milliseconds, X-ForwardedForAllowed status is {3}, endpoint:{4}", _options.ReportingName, clientstring, _options.ForgetTimeSpan.TotalMilliseconds, _options.AllowXForwardedFor, endpoint);
-
+ m_log.Warn($"[{_options.ReportingName}]: client: {clientstring} is blocked for {_options.ForgetTimeSpan.TotalMilliseconds}ms, X-ForwardedForAllowed status is {_options.AllowXForwardedFor}, endpoint:{endpoint}");
return false;
}
//else
diff --git a/OpenSim/Framework/Cache.cs b/OpenSim/Framework/Cache.cs
index 3ca85d7d1a0..a5bf3a6aa05 100644
--- a/OpenSim/Framework/Cache.cs
+++ b/OpenSim/Framework/Cache.cs
@@ -344,26 +344,20 @@ public TimeSpan DefaultTTL
//
protected virtual CacheItemBase GetItem(string index)
{
- CacheItemBase item = null;
lock (m_Index)
{
- if (m_Lookup.ContainsKey(index))
- item = m_Lookup[index];
-
- if (item == null)
+ if(m_Lookup.TryGetValue(index, out CacheItemBase item))
{
+ item.hits++;
+ item.lastUsed = DateTime.UtcNow;
Expire(true);
- return null;
+ return item;
}
- item.hits++;
- item.lastUsed = DateTime.UtcNow;
-
Expire(true);
+ return null;
}
-
- return item;
}
// Get an item from cache. Do not try to fetch from source if not
@@ -566,12 +560,9 @@ public void Invalidate(string uuid)
{
lock (m_Index)
{
- if (!m_Lookup.ContainsKey(uuid))
- return;
-
- CacheItemBase item = m_Lookup[uuid];
+ if (m_Lookup.TryGetValue(uuid, out CacheItemBase item))
+ m_Index.Remove(item);
m_Lookup.Remove(uuid);
- m_Index.Remove(item);
}
}
diff --git a/OpenSim/Framework/CapsUtil.cs b/OpenSim/Framework/CapsUtil.cs
index 020f6e26bdc..86e07cd26e7 100644
--- a/OpenSim/Framework/CapsUtil.cs
+++ b/OpenSim/Framework/CapsUtil.cs
@@ -26,6 +26,7 @@
*/
using OpenMetaverse;
+using System.Runtime.CompilerServices;
namespace OpenSim.Framework
{
@@ -39,24 +40,20 @@ public class CapsUtil
///
///
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string GetCapsSeedPath(string capsObjectPath)
{
- return "CAPS/" + capsObjectPath + "0000/";
+ return $"CAPS/{capsObjectPath}0000/";
}
///
/// Get a random CAPS object path component that will be used as the identifying part of all future CAPS requests
///
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string GetRandomCapsObjectPath()
{
- UUID caps = UUID.Random();
- string capsPath = caps.ToString();
- // I'm commenting this, rather than delete, to keep as historical record.
- // The caps seed is now a full UUID string that gets added four more digits
- // for producing certain CAPs URLs in OpenSim
- //capsPath = capsPath.Remove(capsPath.Length - 4, 4);
- return capsPath;
+ return UUID.Random().ToString();
}
}
}
diff --git a/OpenSim/Framework/ChildAgentDataUpdate.cs b/OpenSim/Framework/ChildAgentDataUpdate.cs
index 3d811ce284d..13b52727b4a 100644
--- a/OpenSim/Framework/ChildAgentDataUpdate.cs
+++ b/OpenSim/Framework/ChildAgentDataUpdate.cs
@@ -125,8 +125,8 @@ public OSDMap Pack(EntityTransferContext ctx)
OSDMap g = (OSDMap)GodData;
// Set legacy value
// TODO: remove after 0.9 is superseded
- if (g.ContainsKey("ViewerUiIsGod"))
- args["god_level"] = g["ViewerUiIsGod"].AsBoolean() ? 200 : 0;
+ if (g.TryGetValue("ViewerUiIsGod", out OSD vuiig))
+ args["god_level"] = vuiig.AsBoolean() ? 200 : 0;
}
if ((Throttles != null) && (Throttles.Length > 0))
@@ -150,72 +150,69 @@ public OSDMap Pack(EntityTransferContext ctx)
public void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
{
- if (args.ContainsKey("region_handle"))
- UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle);
+ OSD osdtmp;
+ if (args.TryGetValue("region_handle", out osdtmp) && osdtmp != null)
+ _ = UInt64.TryParse(osdtmp.AsString(), out RegionHandle);
- if (args["circuit_code"] != null)
- UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
+ if (args.TryGetValue("circuit_code", out osdtmp) && osdtmp != null)
+ _ = UInt32.TryParse(osdtmp.AsString(), out CircuitCode);
- if (args["agent_uuid"] != null)
- AgentID = args["agent_uuid"].AsUUID();
+ if (args.TryGetValue("agent_uuid", out osdtmp) && osdtmp != null)
+ AgentID = osdtmp.AsUUID();
- if (args["session_uuid"] != null)
- SessionID = args["session_uuid"].AsUUID();
+ if (args.TryGetValue("session_uuid", out osdtmp) && osdtmp != null)
+ SessionID = osdtmp.AsUUID();
- if (args["position"] != null)
- Vector3.TryParse(args["position"].AsString(), out Position);
+ if (args.TryGetValue("position", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out Position);
- if (args["velocity"] != null)
- Vector3.TryParse(args["velocity"].AsString(), out Velocity);
+ if (args.TryGetValue("velocity", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out Velocity);
- if (args["center"] != null)
- Vector3.TryParse(args["center"].AsString(), out Center);
+ if (args.TryGetValue("center", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out Center);
- if (args["size"] != null)
- Vector3.TryParse(args["size"].AsString(), out Size);
+ if (args.TryGetValue("size", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out Size);
- if (args["at_axis"] != null)
- Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
+ if (args.TryGetValue("at_axis", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out AtAxis);
- if (args["left_axis"] != null)
- Vector3.TryParse(args["left_axis"].AsString(), out LeftAxis);
+ if (args.TryGetValue("left_axis", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out LeftAxis);
- if (args["up_axis"] != null)
- Vector3.TryParse(args["up_axis"].AsString(), out UpAxis);
+ if (args.TryGetValue("up_axis", out osdtmp) && osdtmp != null)
+ _ = Vector3.TryParse(osdtmp.AsString(), out UpAxis);
- if (args["changed_grid"] != null)
- ChangedGrid = args["changed_grid"].AsBoolean();
+ if (args.TryGetValue("changed_grid", out osdtmp) && osdtmp != null)
+ ChangedGrid = osdtmp.AsBoolean();
- //if (args["god_level"] != null)
- // Int32.TryParse(args["god_level"].AsString(), out GodLevel);
- if (args.ContainsKey("god_data") && args["god_data"] != null)
- GodData = args["god_data"];
+ if (args.TryGetValue("god_data", out osdtmp))
+ GodData = osdtmp;
- if (args["far"] != null)
- Far = (float)(args["far"].AsReal());
+ if (args.TryGetValue("far", out osdtmp) && osdtmp != null)
+ Far = (float)(osdtmp.AsReal());
- if (args["throttles"] != null)
- Throttles = args["throttles"].AsBinary();
+ if (args.TryGetValue("throttles", out osdtmp) && osdtmp != null)
+ Throttles = osdtmp.AsBinary();
- if (args.ContainsKey("children_seeds") && (args["children_seeds"] != null) &&
- (args["children_seeds"].Type == OSDType.Array))
+ if (args.TryGetValue("children_seeds", out osdtmp) && osdtmp is OSDArray childrenSeeds)
{
- OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]);
ChildrenCapSeeds = new Dictionary();
foreach (OSD o in childrenSeeds)
{
- if (o.Type == OSDType.Map)
+ if (o is OSDMap pair)
{
- ulong handle = 0;
- string seed = "";
- OSDMap pair = (OSDMap)o;
- if (pair["handle"] != null)
- if (!UInt64.TryParse(pair["handle"].AsString(), out handle))
- continue;
- if (pair["seed"] != null)
- seed = pair["seed"].AsString();
- if (!ChildrenCapSeeds.ContainsKey(handle))
- ChildrenCapSeeds.Add(handle, seed);
+ if (pair.TryGetValue("handle", out osdtmp) && osdtmp != null)
+ {
+ if (UInt64.TryParse(osdtmp.AsString(), out ulong handle))
+ {
+ if (pair.TryGetValue("seed", out osdtmp))
+ ChildrenCapSeeds.TryAdd(handle, osdtmp.AsString());
+ else
+ ChildrenCapSeeds.TryAdd(handle, string.Empty);
+ }
+ }
}
}
}
@@ -274,12 +271,13 @@ public OSDMap PackUpdateMessage()
public void UnpackUpdateMessage(OSDMap args)
{
- if (args["group_id"] != null)
- GroupID = args["group_id"].AsUUID();
- if (args["group_powers"] != null)
- UInt64.TryParse((string)args["group_powers"].AsString(), out GroupPowers);
- if (args["accept_notices"] != null)
- AcceptNotices = args["accept_notices"].AsBoolean();
+ OSD osdtmp;
+ if (args.TryGetValue("group_id", out osdtmp) && osdtmp != null)
+ GroupID = osdtmp.AsUUID();
+ if (args.TryGetValue("group_powers", out osdtmp) && osdtmp != null)
+ UInt64.TryParse(osdtmp.AsString(), out GroupPowers);
+ if (args.TryGetValue("accept_notices", out osdtmp) && osdtmp != null)
+ AcceptNotices = osdtmp.AsBoolean();
}
}
@@ -317,14 +315,15 @@ public OSDMap PackUpdateMessage()
public void UnpackUpdateMessage(OSDMap args)
{
- if (args["object"] != null)
- ObjectID = args["object"].AsUUID();
- if (args["item"] != null)
- ItemID = args["item"].AsUUID();
- if (args["ignore"] != null)
- IgnoreControls = (uint)args["ignore"].AsInteger();
- if (args["event"] != null)
- EventControls = (uint)args["event"].AsInteger();
+ OSD osdtmp;
+ if (args.TryGetValue("object", out osdtmp) && osdtmp != null)
+ ObjectID = osdtmp.AsUUID();
+ if (args.TryGetValue("item", out osdtmp) && osdtmp != null)
+ ItemID = osdtmp.AsUUID();
+ if (args.TryGetValue("ignore", out osdtmp) && osdtmp != null)
+ IgnoreControls = (uint)osdtmp.AsInteger();
+ if (args.TryGetValue("event", out osdtmp) && osdtmp != null)
+ EventControls = (uint)osdtmp.AsInteger();
}
}
@@ -389,16 +388,10 @@ public UUID AgentID
// Appearance
public AvatarAppearance Appearance;
-// DEBUG ON
- private static readonly ILog m_log =
- LogManager.GetLogger(
- MethodBase.GetCurrentMethod().DeclaringType);
-// DEBUG OFF
-
// Scripted
public ControllerData[] Controllers;
- public string CallbackURI; // to remove
+ public string CallbackURI;
public string NewCallbackURI;
// These two must have the same Count
@@ -407,6 +400,10 @@ public UUID AgentID
public Dictionary MovementAnimationOverRides = new Dictionary();
+ public List CachedFriendsOnline;
+
+ private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
public void SetLookAt(Vector3 value)
{
if (value.X == 0 && value.Y == 0)
@@ -424,7 +421,7 @@ public void SetLookAt(Vector3 value)
public virtual OSDMap Pack(EntityTransferContext ctx)
{
-// m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Pack data");
+ //m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Pack data");
OSDMap args = new OSDMap();
args["message_type"] = OSD.FromString("AgentData");
@@ -463,7 +460,7 @@ public virtual OSDMap Pack(EntityTransferContext ctx)
args["god_data"] = GodData;
OSDMap g = (OSDMap)GodData;
if (g.ContainsKey("ViewerUiIsGod"))
- args["god_level"] = g["ViewerUiIsGod"].AsBoolean() ? 200 : 0;;
+ args["god_level"] = g["ViewerUiIsGod"].AsBoolean() ? 200 : 0;
}
args["always_run"] = OSD.FromBoolean(AlwaysRun);
args["prey_agent"] = OSD.FromUUID(PreyAgent);
@@ -575,6 +572,14 @@ public virtual OSDMap Pack(EntityTransferContext ctx)
args["parent_part"] = OSD.FromUUID(ParentPart);
args["sit_offset"] = OSD.FromString(SitOffset.ToString());
+ if(CachedFriendsOnline != null && CachedFriendsOnline.Count > 0)
+ {
+ OSDArray cfonl = new OSDArray(CachedFriendsOnline.Count);
+ foreach(UUID id in CachedFriendsOnline)
+ cfonl.Add(id);
+ args["cfonline"] = cfonl;
+ }
+
return args;
}
@@ -588,7 +593,7 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
//m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Unpack data");
OSD tmp;
if (args.TryGetValue("region_id", out tmp) && tmp != null)
- UUID.TryParse(tmp.AsString(), out RegionID);
+ _ = UUID.TryParse(tmp.AsString(), out RegionID);
if (args.TryGetValue("circuit_code", out tmp) && tmp != null)
UInt32.TryParse(tmp.AsString(), out CircuitCode);
@@ -600,22 +605,22 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
SessionID = tmp.AsUUID();
if (args.TryGetValue("position", out tmp) && tmp != null)
- Vector3.TryParse(tmp.AsString(), out Position);
+ _ = Vector3.TryParse(tmp.AsString(), out Position);
if (args.TryGetValue("velocity", out tmp) && tmp != null)
- Vector3.TryParse(tmp.AsString(), out Velocity);
+ _ = Vector3.TryParse(tmp.AsString(), out Velocity);
if (args.TryGetValue("center", out tmp) && tmp != null)
- Vector3.TryParse(tmp.AsString(), out Center);
+ _ = Vector3.TryParse(tmp.AsString(), out Center);
if (args.TryGetValue("size", out tmp) && tmp != null)
- Vector3.TryParse(tmp.AsString(), out Size);
+ _ = Vector3.TryParse(tmp.AsString(), out Size);
if (args.TryGetValue("at_axis", out tmp) && tmp != null)
- Vector3.TryParse(tmp.AsString(), out AtAxis);
+ _ = Vector3.TryParse(tmp.AsString(), out AtAxis);
if (args.TryGetValue("left_axis", out tmp) && tmp != null)
- Vector3.TryParse(tmp.AsString(), out LeftAxis);
+ _ = Vector3.TryParse(tmp.AsString(), out LeftAxis);
if (args.TryGetValue("up_axis", out tmp) && tmp != null)
Vector3.TryParse(tmp.AsString(), out UpAxis);
@@ -624,7 +629,7 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
SenderWantsToWaitForRoot = tmp.AsBoolean();
if (args.TryGetValue("far", out tmp) && tmp != null)
- Far = (float)(tmp.AsReal());
+ Far = (float)tmp.AsReal();
if (args.TryGetValue("aspect", out tmp) && tmp != null)
Aspect = (float)tmp.AsReal();
@@ -633,19 +638,19 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
Throttles = tmp.AsBinary();
if (args.TryGetValue("locomotion_state", out tmp) && tmp != null)
- UInt32.TryParse(tmp.AsString(), out LocomotionState);
+ _ = UInt32.TryParse(tmp.AsString(), out LocomotionState);
if (args.TryGetValue("head_rotation", out tmp) && tmp != null)
- Quaternion.TryParse(tmp.AsString(), out HeadRotation);
+ _ = Quaternion.TryParse(tmp.AsString(), out HeadRotation);
if (args.TryGetValue("body_rotation", out tmp) && tmp != null)
- Quaternion.TryParse(tmp.AsString(), out BodyRotation);
+ _ = Quaternion.TryParse(tmp.AsString(), out BodyRotation);
if (args.TryGetValue("control_flags", out tmp) && tmp != null)
- UInt32.TryParse(tmp.AsString(), out ControlFlags);
+ _ = UInt32.TryParse(tmp.AsString(), out ControlFlags);
if (args.TryGetValue("energy_level", out tmp) && tmp != null)
- EnergyLevel = (float)(tmp.AsReal());
+ EnergyLevel = (float)tmp.AsReal();
if (args.TryGetValue("god_data", out tmp) && tmp != null)
GodData = tmp;
@@ -657,7 +662,7 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
PreyAgent = tmp.AsUUID();
if (args.TryGetValue("agent_access", out tmp) && tmp != null)
- Byte.TryParse(tmp.AsString(), out AgentAccess);
+ _ = Byte.TryParse(tmp.AsString(), out AgentAccess);
if (args.TryGetValue("agent_cof", out tmp) && tmp != null)
agentCOF = tmp.AsUUID();
@@ -680,43 +685,36 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
if(args.TryGetValue("active_group_title", out tmp) && tmp != null)
ActiveGroupTitle = tmp.AsString();
- if (args.TryGetValue("children_seeds", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("children_seeds", out tmp) && tmp is OSDArray childrenSeeds)
{
- OSDArray childrenSeeds = (OSDArray)tmp;
ChildrenCapSeeds = new Dictionary();
foreach (OSD o in childrenSeeds)
{
- if (o is OSDMap)
+ if (o is OSDMap pair)
{
- ulong handle = 0;
- string seed = "";
- OSDMap pair = (OSDMap)o;
- if (pair.TryGetValue("handle", out tmp))
- if (!UInt64.TryParse(tmp.AsString(), out handle))
- continue;
- if (pair.TryGetValue("seed", out tmp))
- seed = tmp.AsString();
- if (!ChildrenCapSeeds.ContainsKey(handle))
- ChildrenCapSeeds.Add(handle, seed);
+ if (pair.TryGetValue("handle", out tmp) && tmp != null && UInt64.TryParse(tmp.AsString(), out ulong handle))
+ {
+ if (pair.TryGetValue("seed", out tmp))
+ ChildrenCapSeeds.TryAdd(handle, tmp.AsString());
+ else
+ ChildrenCapSeeds.Add(handle, string.Empty);
+ }
}
}
}
- if (args.TryGetValue("animations", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("animations", out tmp) && tmp is OSDArray anims)
{
- OSDArray anims = (OSDArray)tmp;
Anims = new Animation[anims.Count];
int i = 0;
foreach (OSD o in anims)
{
- if (o is OSDMap)
- {
- Anims[i++] = new Animation((OSDMap)o);
- }
+ if (o is OSDMap om)
+ Anims[i++] = new Animation(om);
}
}
- if (args.TryGetValue("default_animation", out tmp) && tmp is OSDMap)
+ if (args.TryGetValue("default_animation", out tmp) && tmp is OSDMap tmpm)
{
try
{
@@ -728,7 +726,7 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
}
}
- if (args.TryGetValue("animation_state", out tmp) && tmp is OSDMap)
+ if (args.TryGetValue("animation_state", out tmp) && tmp is OSDMap tmpms)
{
try
{
@@ -742,19 +740,19 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
MovementAnimationOverRides.Clear();
- if (args.TryGetValue("movementAO", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("movementAO", out tmp) && tmp is OSDArray AOs)
{
- OSDArray AOs = (OSDArray)tmp;
- int count = AOs.Count;
-
- for (int i = 0; i < count; i++)
+ for (int i = 0; i < AOs.Count; i++)
{
- OSDMap ao = (OSDMap)AOs[i];
- if (ao["state"] != null && ao["uuid"] != null)
+ if(AOs[i] is OSDMap ao)
{
- string state = ao["state"].AsString();
- UUID id = ao["uuid"].AsUUID();
- MovementAnimationOverRides[state] = id;
+ if (ao.TryGetValue("state", out OSD st) && st != null &&
+ ao.TryGetValue("uuid", out OSD uid) && uid != null)
+ {
+ string state = st.AsString();
+ UUID id = uid.AsUUID();
+ MovementAnimationOverRides[state] = id;
+ }
}
}
}
@@ -773,10 +771,10 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
// packed_appearence should contain all appearance information
- if (args.TryGetValue("packed_appearance", out tmp) && tmp is OSDMap)
+ if (args.TryGetValue("packed_appearance", out tmp) && tmp is OSDMap pam)
{
//m_log.WarnFormat("[CHILDAGENTDATAUPDATE] got packed appearance");
- Appearance = new AvatarAppearance((OSDMap)tmp);
+ Appearance = new AvatarAppearance(pam);
}
else
{
@@ -798,10 +796,8 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
if (args.TryGetValue("visual_params", out tmp) && tmp != null)
Appearance.SetVisualParams(tmp.AsBinary());
- if (args.TryGetValue("wearables", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("wearables", out tmp) && tmp is OSDArray wears)
{
- OSDArray wears = (OSDArray)tmp;
-
for (int i = 0; i < wears.Count / 2; i++)
{
AvatarWearable awear = new AvatarWearable((OSDArray)wears[i]);
@@ -809,34 +805,32 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
}
}
- if (args.TryGetValue("attachments", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("attachments", out tmp) && tmp is OSDArray attachs)
{
- OSDArray attachs = (OSDArray)tmp;
foreach (OSD o in attachs)
{
- if (o is OSDMap)
+ if (o is OSDMap att)
{
// We know all of these must end up as attachments so we
// append rather than replace to ensure multiple attachments
// per point continues to work
// m_log.DebugFormat("[CHILDAGENTDATAUPDATE]: Appending attachments for {0}", AgentID);
- Appearance.AppendAttachment(new AvatarAttachment((OSDMap)o));
+ Appearance.AppendAttachment(new AvatarAttachment(att));
}
}
}
// end of code to remove
}
- if (args.TryGetValue("controllers", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("controllers", out tmp) && tmp is OSDArray controls)
{
- OSDArray controls = (OSDArray)tmp;
Controllers = new ControllerData[controls.Count];
int i = 0;
foreach (OSD o in controls)
{
- if (o is OSDMap)
+ if (o is OSDMap cntr)
{
- Controllers[i++] = new ControllerData((OSDMap)o);
+ Controllers[i++] = new ControllerData(cntr);
}
}
}
@@ -848,16 +842,14 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
NewCallbackURI = tmp.AsString();
// Attachment objects
- if (args.TryGetValue("attach_objects", out tmp) && tmp is OSDArray)
+ if (args.TryGetValue("attach_objects", out tmp) && tmp is OSDArray attObjs)
{
- OSDArray attObjs = (OSDArray)tmp;
AttachmentObjects = new List();
AttachmentObjectStates = new List();
foreach (OSD o in attObjs)
{
- if (o is OSDMap)
+ if (o is OSDMap info)
{
- OSDMap info = (OSDMap)o;
ISceneObject so = scene.DeserializeObject(info["sog"].AsString());
so.ExtraFromXmlString(info["extra"].AsString());
so.HasGroupChanged = info["modified"].AsBoolean();
@@ -871,6 +863,13 @@ public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
ParentPart = tmp.AsUUID();
if (args.TryGetValue("sit_offset", out tmp) && tmp != null)
Vector3.TryParse(tmp.AsString(), out SitOffset);
+
+ if (args.TryGetValue("cfonline", out tmp) && tmp is OSDArray cfonl)
+ {
+ CachedFriendsOnline = new List(cfonl.Count);
+ foreach(OSD o in cfonl)
+ CachedFriendsOnline.Add(o.AsUUID());
+ }
}
public AgentData()
diff --git a/OpenSim/Framework/ClientManager.cs b/OpenSim/Framework/ClientManager.cs
index c444fcffc54..05829b869d8 100644
--- a/OpenSim/Framework/ClientManager.cs
+++ b/OpenSim/Framework/ClientManager.cs
@@ -40,15 +40,15 @@ public class ClientManager
{
/// A dictionary mapping from
/// to references
- private readonly Dictionary m_dictbyUUID = new Dictionary();
+ private readonly Dictionary m_dictbyUUID = new();
/// A dictionary mapping from
/// to references
- private readonly Dictionary m_dictbyIPe= new Dictionary();
+ private readonly Dictionary m_dictbyIPe= new();
/// snapshot collection of current
/// references
private IClientAPI[] m_array = null;
/// Synchronization object for writing to the collections
- private readonly object m_syncRoot = new object();
+ private readonly object m_syncRoot = new();
/// Number of clients in the collection
public int Count
@@ -96,10 +96,8 @@ public bool Remove(UUID key)
{
lock (m_syncRoot)
{
- IClientAPI value;
- if (m_dictbyUUID.TryGetValue(key, out value))
+ if (m_dictbyUUID.Remove(key, out IClientAPI value))
{
- m_dictbyUUID.Remove(key);
m_dictbyIPe.Remove(value.RemoteEndPoint);
m_array = null;
return true;
@@ -193,7 +191,7 @@ public void ForEach(Action action)
IClientAPI[] localArray;
lock (m_syncRoot)
{
- if (m_array == null)
+ if (m_array is null)
{
if (m_dictbyUUID.Count == 0)
return;
diff --git a/OpenSim/Framework/Console/CommandConsole.cs b/OpenSim/Framework/Console/CommandConsole.cs
index 3da2e386ceb..80d59931675 100755
--- a/OpenSim/Framework/Console/CommandConsole.cs
+++ b/OpenSim/Framework/Console/CommandConsole.cs
@@ -670,7 +670,7 @@ public static string[] Parse(string text)
{
if (index % 2 == 0)
{
- string[] words = unquoted[index].Split(new char[] {' '});
+ string[] words = unquoted[index].Split();
bool option = false;
foreach (string w in words)
diff --git a/OpenSim/Framework/Console/ConsolePluginCommand.cs b/OpenSim/Framework/Console/ConsolePluginCommand.cs
index f4d36874501..2bce8b45c37 100755
--- a/OpenSim/Framework/Console/ConsolePluginCommand.cs
+++ b/OpenSim/Framework/Console/ConsolePluginCommand.cs
@@ -62,7 +62,7 @@ public class ConsolePluginCommand
/// the text displayed in "help showme new commands"
public ConsolePluginCommand(string command, ConsoleCommand dlg, string help)
{
- m_cmdText = command.Split(new char[] { ' ' });
+ m_cmdText = command.Split();
m_commandDelegate = dlg;
m_helpText = help;
}
diff --git a/OpenSim/Framework/Console/LocalConsole.cs b/OpenSim/Framework/Console/LocalConsole.cs
index 58efe84390f..d5c55f1c4c5 100755
--- a/OpenSim/Framework/Console/LocalConsole.cs
+++ b/OpenSim/Framework/Console/LocalConsole.cs
@@ -324,10 +324,8 @@ public override void LockOutput()
m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
int count = m_commandLine.Length + prompt.Length;
- char[] spaces = new char[count];
- for(int i = 0; i < spaces.Length; i++)
- spaces[i] = ' ';
- System.Console.Write(spaces);
+ if(count > 0)
+ System.Console.Write(new string(' ', count));
m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
}
@@ -444,11 +442,12 @@ public override void Output(string format, params object[] components)
m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
int count = m_commandLine.Length + prompt.Length - text.Length;
-
WriteLocalText(text, level);
- for (int i = 0; i < count; ++i)
- System.Console.Write(" ");
- System.Console.WriteLine();
+ if(count > 0)
+ System.Console.WriteLine(new string(' ', count));
+ else
+ System.Console.WriteLine();
+
m_cursorYPosition = System.Console.CursorTop;
Show();
}
@@ -496,8 +495,8 @@ public override string ReadLine(string p, bool isCommand, bool e)
{
Show();
//Reduce collisions with internal read terminal information like cursor position on linux
- //while(System.Console.KeyAvailable == false)
- // Thread.Sleep(100);
+ while(System.Console.KeyAvailable == false)
+ Thread.Sleep(100);
ConsoleKeyInfo key = System.Console.ReadKey(true);
diff --git a/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj b/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj
index 5cfae0bb51d..901fa5d1f8a 100644
--- a/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj
+++ b/OpenSim/Framework/Console/OpenSim.Framework.Console.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Framework.Console
http://opensimulator.org
ServerConsole
@@ -18,9 +18,6 @@
..\..\..\bin\OpenMetaverseTypes.dll
False
-
- False
-
diff --git a/OpenSim/Framework/Console/RemoteConsole.cs b/OpenSim/Framework/Console/RemoteConsole.cs
index 276b7fa5df5..b92af1fcdf8 100755
--- a/OpenSim/Framework/Console/RemoteConsole.cs
+++ b/OpenSim/Framework/Console/RemoteConsole.cs
@@ -322,7 +322,7 @@ public override string ReadLine(string p, bool isCommand, bool e)
for (i=0 ; i < cmd.Length ; i++)
{
- if (cmd[i].Contains(" "))
+ if (cmd[i].Contains(' '))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
@@ -721,12 +721,10 @@ protected Hashtable NoEvents(UUID RequestID, UUID id)
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
- XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
- "", "");
+ XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
- XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
- "");
+ XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", "");
xmldoc.AppendChild(rootElement);
diff --git a/OpenSim/Framework/Constants.cs b/OpenSim/Framework/Constants.cs
index f97b69acc05..5dbd0bd9ace 100644
--- a/OpenSim/Framework/Constants.cs
+++ b/OpenSim/Framework/Constants.cs
@@ -34,6 +34,9 @@ public class Constants
public const int MaxAgentAttachments = 38;
public const int MaxAgentGroups = 60;
+ public const int MaxEstateAccessIds = 500;
+ public const int MaxEstateManagers = 20;
+
// 'RegionSize' is the legacy region size.
// DO NOT USE THIS FOR ANY NEW CODE. Use Scene.RegionInfo.RegionSize[XYZ] as a region might not
// be the legacy region size.
@@ -56,6 +59,8 @@ public class Constants
public const float MinWaterHeight = 0;
public const float MaxWaterHeight = 8000f;
+ public const int MaxTextureResolution = 1024;
+
public static readonly string DefaultTexture = "89556747-24cb-43ed-920b-47caed15465f"; //plywood
public static readonly UUID DefaultTextureID = new UUID(DefaultTexture);
@@ -68,6 +73,9 @@ public class Constants
public static readonly UUID EmptyNotecardID = new UUID(EmptyNotecard);
public static readonly byte[] EmptyNotecardData = osUTF8.GetASCIIBytes("Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length 0\n}\n\0");
+ public static readonly string DefaultMaterial = "968cbad0-4dad-d64e-71b5-72bf13ad051a";
+ public static readonly UUID DefaultMaterialID = new UUID(DefaultMaterial);
+
public static readonly string m_MrOpenSimIDString = "11111111-1111-0000-0000-000100bba000";
public static readonly UUID m_MrOpenSimID = new UUID(m_MrOpenSimIDString);
public static readonly DateTime m_MrOpenSimBorn = new DateTime(2007, 1, 1, 0, 0, 0, DateTimeKind.Utc);
@@ -85,10 +93,10 @@ public enum EstateAccessCodex : uint
public enum EstateAccessLimits : int
{
- AllowedAccess = 500,
+ AllowedAccess = MaxEstateAccessIds,
AllowedGroups = 63,
EstateBans = 500,
- EstateManagers = 10
+ EstateManagers = MaxEstateManagers
}
[Flags]public enum TeleportFlags : uint
diff --git a/OpenSim/Framework/EstateSettings.cs b/OpenSim/Framework/EstateSettings.cs
index 0e9a46e2f3e..ef73dd059b4 100644
--- a/OpenSim/Framework/EstateSettings.cs
+++ b/OpenSim/Framework/EstateSettings.cs
@@ -27,7 +27,6 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Reflection;
using OpenMetaverse;
@@ -249,7 +248,7 @@ public bool AllowEnvironmentOverride
// All those lists...
//
- private List l_EstateManagers = new List();
+ private List l_EstateManagers = new();
public UUID[] EstateManagers
{
@@ -257,7 +256,7 @@ public UUID[] EstateManagers
set { l_EstateManagers = new List(value); }
}
- private List l_EstateBans = new List();
+ private List l_EstateBans = new();
public EstateBan[] EstateBans
{
@@ -265,14 +264,14 @@ public EstateBan[] EstateBans
set { l_EstateBans = new List(value); }
}
- private List l_EstateAccess = new List();
+ private List l_EstateAccess = new();
public UUID[] EstateAccess
{
get { return l_EstateAccess.ToArray(); }
set { l_EstateAccess = new List(value); }
}
- private List l_EstateGroups = new List();
+ private List l_EstateGroups = new();
public UUID[] EstateGroups
{
get { return l_EstateGroups.ToArray(); }
@@ -288,8 +287,7 @@ public EstateSettings()
public void Save()
{
- if (OnSave != null)
- OnSave(this);
+ OnSave?.Invoke(this);
}
public int EstateUsersCount()
@@ -301,15 +299,14 @@ public void AddEstateUser(UUID avatarID)
{
if (avatarID.IsZero())
return;
- if (!l_EstateAccess.Contains(avatarID) &&
- (l_EstateAccess.Count < (int)Constants.EstateAccessLimits.AllowedAccess))
+ if ((l_EstateAccess.Count < (int)Constants.EstateAccessLimits.AllowedAccess) &&
+ !l_EstateAccess.Contains(avatarID))
l_EstateAccess.Add(avatarID);
}
public void RemoveEstateUser(UUID avatarID)
{
- if (l_EstateAccess.Contains(avatarID))
- l_EstateAccess.Remove(avatarID);
+ _ = l_EstateAccess.Remove(avatarID);
}
public int EstateGroupsCount()
@@ -321,15 +318,14 @@ public void AddEstateGroup(UUID avatarID)
{
if (avatarID.IsZero())
return;
- if (!l_EstateGroups.Contains(avatarID) &&
- (l_EstateGroups.Count < (int)Constants.EstateAccessLimits.AllowedGroups))
+ if ((l_EstateGroups.Count < (int)Constants.EstateAccessLimits.AllowedGroups) &&
+ !l_EstateGroups.Contains(avatarID))
l_EstateGroups.Add(avatarID);
}
public void RemoveEstateGroup(UUID avatarID)
{
- if (l_EstateGroups.Contains(avatarID))
- l_EstateGroups.Remove(avatarID);
+ _ = l_EstateGroups.Remove(avatarID);
}
public int EstateManagersCount()
@@ -341,31 +337,24 @@ public void AddEstateManager(UUID avatarID)
{
if (avatarID.IsZero())
return;
- if (!l_EstateManagers.Contains(avatarID) &&
- (l_EstateManagers.Count < (int)Constants.EstateAccessLimits.EstateManagers))
+ if ((l_EstateManagers.Count < (int)Constants.EstateAccessLimits.EstateManagers) &&
+ !l_EstateManagers.Contains(avatarID))
l_EstateManagers.Add(avatarID);
}
public void RemoveEstateManager(UUID avatarID)
{
- if (l_EstateManagers.Contains(avatarID))
- l_EstateManagers.Remove(avatarID);
+ _ = l_EstateManagers.Remove(avatarID);
}
public bool IsEstateManagerOrOwner(UUID avatarID)
{
- if (IsEstateOwner(avatarID))
- return true;
-
- return l_EstateManagers.Contains(avatarID);
+ return m_EstateOwner.Equals(avatarID) || l_EstateManagers.Contains(avatarID);
}
public bool IsEstateOwner(UUID avatarID)
{
- if (avatarID == m_EstateOwner)
- return true;
-
- return false;
+ return m_EstateOwner.Equals(avatarID);
}
public bool IsBanned(UUID avatarID)
@@ -373,8 +362,10 @@ public bool IsBanned(UUID avatarID)
if (!IsEstateManagerOrOwner(avatarID))
{
foreach (EstateBan ban in l_EstateBans)
- if (ban.BannedUserID == avatarID)
+ {
+ if (ban.BannedUserID.Equals(avatarID))
return true;
+ }
}
return false;
}
@@ -384,8 +375,10 @@ public bool IsBanned(UUID avatarID, int userFlags)
if (!IsEstateManagerOrOwner(avatarID))
{
foreach (EstateBan ban in l_EstateBans)
- if (ban.BannedUserID == avatarID)
- return true;
+ {
+ if (ban.BannedUserID.Equals(avatarID))
+ return true;
+ }
if (!HasAccess(avatarID))
{
@@ -415,7 +408,7 @@ public int EstateBansCount()
public void AddBan(EstateBan ban)
{
- if (ban == null)
+ if (ban is null)
return;
if (!IsBanned(ban.BannedUserID, 32) &&
(l_EstateBans.Count < (int)Constants.EstateAccessLimits.EstateBans)) //Ignore age-based bans
@@ -444,11 +437,11 @@ public bool HasAccess(UUID user)
public void SetFromFlags(ulong regionFlags)
{
- ResetHomeOnTeleport = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport) == (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport);
- BlockDwell = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.BlockDwell) == (ulong)OpenMetaverse.RegionFlags.BlockDwell);
- AllowLandmark = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowLandmark) == (ulong)OpenMetaverse.RegionFlags.AllowLandmark);
- AllowParcelChanges = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges) == (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges);
- AllowSetHome = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowSetHome) == (ulong)OpenMetaverse.RegionFlags.AllowSetHome);
+ ResetHomeOnTeleport = (regionFlags & (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport) != 0;
+ BlockDwell = (regionFlags & (ulong)OpenMetaverse.RegionFlags.BlockDwell) != 0;
+ AllowLandmark = (regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowLandmark) != 0;
+ AllowParcelChanges = (regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges) != 0;
+ AllowSetHome = (regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowSetHome) != 0;
}
public bool GroupAccess(UUID groupID)
@@ -458,7 +451,7 @@ public bool GroupAccess(UUID groupID)
public Dictionary ToMap()
{
- Dictionary map = new Dictionary();
+ Dictionary map = new();
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in properties)
{
@@ -467,7 +460,7 @@ public Dictionary ToMap()
continue;
object value = p.GetValue(this, null);
- if (value != null)
+ if (value is not null)
{
if (p.PropertyType.IsArray) // of UUIDs
{
@@ -488,7 +481,7 @@ public Dictionary ToMap()
// EstateBans are special
if (EstateBans.Length > 0)
{
- Dictionary bans = new Dictionary();
+ Dictionary bans = new();
int i = 0;
foreach (EstateBan ban in EstateBans)
bans["ban" + i++] = ban.ToMap();
@@ -527,7 +520,7 @@ public EstateSettings(Dictionary map)
foreach (KeyValuePair kvp in map)
{
PropertyInfo p = this.GetType().GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance);
- if (p == null)
+ if (p is null)
continue;
// EstateBans is a complex type, let's treat it as special
@@ -536,7 +529,7 @@ public EstateSettings(Dictionary map)
if (p.PropertyType.IsArray)
{
- string[] elements = ((string)map[p.Name]).Split(new char[] { ',' });
+ string[] elements = ((string)map[p.Name]).Split(Util.SplitCommaArray);
UUID[] uuids = new UUID[elements.Length];
int i = 0;
foreach (string e in elements)
@@ -548,31 +541,31 @@ public EstateSettings(Dictionary map)
object value = p.GetValue(this, null);
if (value is String)
p.SetValue(this, map[p.Name], null);
- else if (value is UInt32)
- p.SetValue(this, UInt32.Parse((string)map[p.Name]), null);
- else if (value is Boolean)
- p.SetValue(this, Boolean.Parse((string)map[p.Name]), null);
+ else if (value is uint)
+ p.SetValue(this, uint.Parse((string)map[p.Name]), null);
+ else if (value is bool)
+ p.SetValue(this, bool.Parse((string)map[p.Name]), null);
else if (value is UUID)
p.SetValue(this, UUID.Parse((string)map[p.Name]), null);
}
}
// EstateBans are special
- if (map.ContainsKey("EstateBans"))
+ if (map.TryGetValue("EstateBans", out object oEstateBans))
{
- if(map["EstateBans"] is string)
+ if(oEstateBans is string bansmap)
{
// JSON encoded bans map
- Dictionary bdata = new Dictionary();
+ Dictionary bdata = new();
try
{
// bypass libovm, we dont need even more useless high level maps
// this should only be called once.. but no problem, i hope
// (other uses may need more..)
LitJson.JsonMapper.RegisterImporter((input) => new UUID(input));
- bdata = LitJson.JsonMapper.ToObject>((string)map["EstateBans"]);
+ bdata = LitJson.JsonMapper.ToObject>(bansmap);
}
- // catch(Exception e)
+ //catch(Exception e)
catch
{
return;
diff --git a/OpenSim/Framework/ExpiringCacheOS.cs b/OpenSim/Framework/ExpiringCacheOS.cs
index 00be73d1109..6f6de40b7a5 100644
--- a/OpenSim/Framework/ExpiringCacheOS.cs
+++ b/OpenSim/Framework/ExpiringCacheOS.cs
@@ -30,6 +30,7 @@
using System.Threading;
using System.Collections.Generic;
using Timer = System.Threading.Timer;
+using System.Runtime.InteropServices;
namespace OpenSim.Framework
{
@@ -460,6 +461,59 @@ public bool TryGetValue(TKey1 key, int expireMS, out TValue1 value)
return success;
}
+ public ref TValue1 TryGetOrDefaultValue(TKey1 key, out bool existed)
+ {
+ bool gotLock = false;
+ try
+ {
+ try { }
+ finally
+ {
+ m_rwLock.ExitUpgradeableReadLock();
+ gotLock = true;
+ }
+
+ return ref CollectionsMarshal.GetValueRefOrAddDefault(m_values, key, out existed);
+ }
+ finally
+ {
+ if (gotLock)
+ m_rwLock.ExitUpgradeableReadLock();
+ }
+ }
+
+ public ref TValue1 TryGetOrDefaultValue(TKey1 key, int expireMS, out bool existed)
+ {
+ bool gotLock = false;
+ try
+ {
+ try { }
+ finally
+ {
+ m_rwLock.EnterWriteLock();
+ gotLock = true;
+ }
+
+ ref TValue1 ret = ref CollectionsMarshal.GetValueRefOrAddDefault(m_values, key, out existed);
+ int now;
+ if (expireMS > 0)
+ {
+ expireMS = (expireMS > m_expire) ? expireMS : m_expire;
+ now = (int)(Util.GetTimeStampMS() - m_startTS) + expireMS;
+ }
+ else
+ now = int.MinValue;
+
+ m_expireControl[key] = now;
+ return ref ret;
+ }
+ finally
+ {
+ if (gotLock)
+ m_rwLock.EnterWriteLock();
+ }
+ }
+
public TValue1[] Values
{
get
diff --git a/OpenSim/Framework/GridInstantMessage.cs b/OpenSim/Framework/GridInstantMessage.cs
index 7f3980bdf1e..5f1246a9768 100644
--- a/OpenSim/Framework/GridInstantMessage.cs
+++ b/OpenSim/Framework/GridInstantMessage.cs
@@ -50,7 +50,7 @@ public class GridInstantMessage
public GridInstantMessage()
{
- binaryBucket = Array.Empty(); ;
+ binaryBucket = Array.Empty();
}
public GridInstantMessage(GridInstantMessage im, bool addTimestamp)
diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs
index a3008a53c23..965e68eacc8 100755
--- a/OpenSim/Framework/IClientAPI.cs
+++ b/OpenSim/Framework/IClientAPI.cs
@@ -127,21 +127,21 @@ public delegate void RequestObjectPropertiesFamily(
public delegate void ObjectDrop(uint localID, IClientAPI remoteClient);
public delegate void UpdatePrimFlags(
- uint localID, bool UsePhysics, bool IsTemporary, bool IsPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient);
+ uint localID, bool UsePhysics, bool IsTemporary, bool IsPhantom, in ExtraPhysicsData PhysData, IClientAPI remoteClient);
public delegate void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient);
- public delegate void UpdateVector(uint localID, Vector3 pos, IClientAPI remoteClient);
+ public delegate void UpdateVector(uint localID, in Vector3 pos, IClientAPI remoteClient);
public delegate void ClientChangeObject(uint localID, object data ,IClientAPI remoteClient);
- public delegate void UpdatePrimRotation(uint localID, Quaternion rot, IClientAPI remoteClient);
+ public delegate void UpdatePrimRotation(uint localID, in Quaternion rot, IClientAPI remoteClient);
- public delegate void UpdatePrimSingleRotation(uint localID, Quaternion rot, IClientAPI remoteClient);
+ public delegate void UpdatePrimSingleRotation(uint localID, in Quaternion rot, IClientAPI remoteClient);
- public delegate void UpdatePrimSingleRotationPosition(uint localID, Quaternion rot, Vector3 pos, IClientAPI remoteClient);
+ public delegate void UpdatePrimSingleRotationPosition(uint localID, in Quaternion rot, in Vector3 pos, IClientAPI remoteClient);
- public delegate void UpdatePrimGroupRotation(uint localID, Vector3 pos, Quaternion rot, IClientAPI remoteClient);
+ public delegate void UpdatePrimGroupRotation(uint localID, in Vector3 pos, in Quaternion rot, IClientAPI remoteClient);
public delegate void ObjectDuplicate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID, UUID GroupID);
@@ -607,7 +607,7 @@ public enum PrimUpdateFlags : uint
{
None = 0,
AttachmentPoint = 1 << 0,
- Material = 1 << 1,
+ MaterialOvr = 1 << 1,
ClickAction = 1 << 2,
Scale = 1 << 3,
ParentID = 1 << 4,
@@ -630,11 +630,13 @@ public enum PrimUpdateFlags : uint
Sound = 1 << 21,
TerseUpdate = Position | Rotation | Velocity | Acceleration | AngularVelocity,
- FullUpdate = 0x00ffffff,
+ FullUpdate = 0x00ffffff & ~MaterialOvr,
Animations = 1 << 24,
FullUpdatewithAnim = FullUpdate | Animations,
+ FullUpdatewithMatOvr = FullUpdate | MaterialOvr,
+ FullUpdatewithAnimMatOvr = FullUpdate | Animations | MaterialOvr,
UpdateProbe = 0x10000000, // 1 << 28
SendInTransit = 0x20000000, // 1 << 29
@@ -646,6 +648,9 @@ public interface IClientAPI
{
Vector3 StartPos { get; set; }
float StartFar { get; set; }
+ float FOV { get; set; }
+ int viewHeight { get; set; }
+ int viewWidth { get; set; }
UUID AgentId { get; }
@@ -757,7 +762,6 @@ public interface IClientAPI
event DeRezObject OnDeRezObject;
event RezRestoreToWorld OnRezRestoreToWorld;
event Action OnRegionHandShakeReply;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
event GenericCall1 OnRequestWearables;
event Action OnCompleteMovementToRegion;
diff --git a/OpenSim/Framework/InventoryFolderBase.cs b/OpenSim/Framework/InventoryFolderBase.cs
index fb66056fbac..3b262cc1e3f 100644
--- a/OpenSim/Framework/InventoryFolderBase.cs
+++ b/OpenSim/Framework/InventoryFolderBase.cs
@@ -48,9 +48,7 @@ public class InventoryFolderBase : InventoryNodeBase
private short _type;
///
- /// This is used to denote the version of the client, needed
- /// because of the changes clients have with inventory from
- /// time to time (1.19.1 caused us some fits there).
+ /// This is used to denote the version of folder
///
private ushort _version;
diff --git a/OpenSim/Framework/LandData.cs b/OpenSim/Framework/LandData.cs
index 6e989d71949..cbfa5f771a1 100644
--- a/OpenSim/Framework/LandData.cs
+++ b/OpenSim/Framework/LandData.cs
@@ -46,8 +46,8 @@ public class LandAccessEntry
///
public class LandData
{
- private Vector3 _AABBMax = new Vector3();
- private Vector3 _AABBMin = new Vector3();
+ private Vector3 _AABBMax = new();
+ private Vector3 _AABBMin = new();
private int _area = 0;
private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned
private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID
@@ -75,15 +75,15 @@ public class LandData
private string _mediaURL = String.Empty;
private string _musicURL = String.Empty;
private UUID _ownerID = UUID.Zero;
- private List _parcelAccessList = new List();
+ private List _parcelAccessList = new();
private float _passHours = 0;
private int _passPrice = 0;
private int _salePrice = 0; //Unemeplemented. Parcels price.
private int _simwideArea = 0;
private int _simwidePrims = 0;
private UUID _snapshotID = UUID.Zero;
- private Vector3 _userLocation = new Vector3();
- private Vector3 _userLookAt = new Vector3();
+ private Vector3 _userLocation = new();
+ private Vector3 _userLookAt = new();
private int _otherCleanTime = 0;
private string _mediaType = "none/none";
private string _mediaDescription = "";
@@ -763,60 +763,63 @@ public LandData()
///
public LandData Copy()
{
- LandData landData = new LandData();
-
- landData._AABBMax = _AABBMax;
- landData._AABBMin = _AABBMin;
- landData._area = _area;
- landData._auctionID = _auctionID;
- landData._authBuyerID = _authBuyerID;
- landData._category = _category;
- landData._claimDate = _claimDate;
- landData._claimPrice = _claimPrice;
- landData._globalID = _globalID;
- landData.m_fakeID = m_fakeID;
- landData._groupID = _groupID;
- landData._isGroupOwned = _isGroupOwned;
- landData._localID = _localID;
- landData._landingType = _landingType;
- landData._mediaAutoScale = _mediaAutoScale;
- landData._mediaID = _mediaID;
- landData._mediaURL = _mediaURL;
- landData._musicURL = _musicURL;
- landData._ownerID = _ownerID;
- landData._bitmap = (byte[])_bitmap.Clone();
- landData._description = _description;
- landData._flags = _flags;
- landData._name = _name;
- landData._status = _status;
- landData._passHours = _passHours;
- landData._passPrice = _passPrice;
- landData._salePrice = _salePrice;
- landData._snapshotID = _snapshotID;
- landData._userLocation = _userLocation;
- landData._userLookAt = _userLookAt;
- landData._otherCleanTime = _otherCleanTime;
- landData._mediaType = _mediaType;
- landData._mediaDescription = _mediaDescription;
- landData._mediaWidth = _mediaWidth;
- landData._mediaHeight = _mediaHeight;
- landData._mediaLoop = _mediaLoop;
- landData._obscureMusic = _obscureMusic;
- landData._obscureMedia = _obscureMedia;
- landData._simwideArea = _simwideArea;
- landData._simwidePrims = _simwidePrims;
- landData.m_dwell = m_dwell;
- landData.SeeAVs = SeeAVs;
- landData.AnyAVSounds = AnyAVSounds;
- landData.GroupAVSounds = GroupAVSounds;
+ LandData landData = new()
+ {
+ _AABBMax = _AABBMax,
+ _AABBMin = _AABBMin,
+ _area = _area,
+ _auctionID = _auctionID,
+ _authBuyerID = _authBuyerID,
+ _category = _category,
+ _claimDate = _claimDate,
+ _claimPrice = _claimPrice,
+ _globalID = _globalID,
+ m_fakeID = m_fakeID,
+ _groupID = _groupID,
+ _isGroupOwned = _isGroupOwned,
+ _localID = _localID,
+ _landingType = _landingType,
+ _mediaAutoScale = _mediaAutoScale,
+ _mediaID = _mediaID,
+ _mediaURL = _mediaURL,
+ _musicURL = _musicURL,
+ _ownerID = _ownerID,
+ _bitmap = (byte[])_bitmap.Clone(),
+ _description = _description,
+ _flags = _flags,
+ _name = _name,
+ _status = _status,
+ _passHours = _passHours,
+ _passPrice = _passPrice,
+ _salePrice = _salePrice,
+ _snapshotID = _snapshotID,
+ _userLocation = _userLocation,
+ _userLookAt = _userLookAt,
+ _otherCleanTime = _otherCleanTime,
+ _mediaType = _mediaType,
+ _mediaDescription = _mediaDescription,
+ _mediaWidth = _mediaWidth,
+ _mediaHeight = _mediaHeight,
+ _mediaLoop = _mediaLoop,
+ _obscureMusic = _obscureMusic,
+ _obscureMedia = _obscureMedia,
+ _simwideArea = _simwideArea,
+ _simwidePrims = _simwidePrims,
+ m_dwell = m_dwell,
+ SeeAVs = SeeAVs,
+ AnyAVSounds = AnyAVSounds,
+ GroupAVSounds = GroupAVSounds
+ };
landData._parcelAccessList.Clear();
foreach (LandAccessEntry entry in _parcelAccessList)
{
- LandAccessEntry newEntry = new LandAccessEntry();
- newEntry.AgentID = entry.AgentID;
- newEntry.Flags = entry.Flags;
- newEntry.Expires = entry.Expires;
+ LandAccessEntry newEntry = new()
+ {
+ AgentID = entry.AgentID,
+ Flags = entry.Flags,
+ Expires = entry.Expires
+ };
landData._parcelAccessList.Add(newEntry);
}
diff --git a/OpenSim/Framework/LandUpdateArgs.cs b/OpenSim/Framework/LandUpdateArgs.cs
index 6305223f571..7d0acec69ae 100644
--- a/OpenSim/Framework/LandUpdateArgs.cs
+++ b/OpenSim/Framework/LandUpdateArgs.cs
@@ -54,8 +54,6 @@ public class LandUpdateArgs : EventArgs
public int MediaHeight;
public int MediaWidth;
public bool MediaLoop;
- public bool ObscureMusic;
- public bool ObscureMedia;
public bool SeeAVs;
public bool AnyAVSounds;
public bool GroupAVSounds;
diff --git a/OpenSim/Framework/LogWriter.cs b/OpenSim/Framework/LogWriter.cs
index 2e0bf4a354d..5b331c06225 100755
--- a/OpenSim/Framework/LogWriter.cs
+++ b/OpenSim/Framework/LogWriter.cs
@@ -44,19 +44,19 @@ public class LogWriter : IDisposable
{
public bool Enabled { get; private set; }
- private string m_logDirectory = ".";
- private int m_logMaxFileTimeMin = 5; // 5 minutes
+ private readonly string m_logDirectory = ".";
+ private readonly int m_logMaxFileTimeMin = 5; // 5 minutes
public String LogFileHeader { get; set; }
private StreamWriter m_logFile = null;
- private TimeSpan m_logFileLife;
+ private readonly TimeSpan m_logFileLife;
private DateTime m_logFileEndTime;
- private Object m_logFileWriteLock = new Object();
- private bool m_flushWrite;
+ private readonly Object m_logFileWriteLock = new Object();
+ private readonly bool m_flushWrite;
// set externally when debugging. If let 'null', this does not write any error messages.
public ILog ErrorLogger = null;
- private string LogHeader = "[LOG WRITER]";
+ private readonly string LogHeader = "[LOG WRITER]";
///
/// Create a log writer that will not write anything. Good for when not enabled
@@ -78,9 +78,8 @@ public LogWriter()
/// if one is looking for a crash, this is a good thing to turn on.
public LogWriter(string dir, string headr, int maxFileTime, bool flushWrite)
{
- m_logDirectory = dir == null ? "." : dir;
-
- LogFileHeader = headr == null ? "log-" : headr;
+ m_logDirectory = dir ?? ".";
+ LogFileHeader = headr ?? "log-";
m_logMaxFileTimeMin = maxFileTime;
if (m_logMaxFileTimeMin < 1)
@@ -100,13 +99,14 @@ public LogWriter(string dir, string headr, int maxFileTime) : this(dir, headr, m
public void Dispose()
{
- this.Close();
+ Close();
+ GC.SuppressFinalize(this);
}
public void Close()
{
Enabled = false;
- if (m_logFile != null)
+ if (m_logFile is not null)
{
m_logFile.Close();
m_logFile.Dispose();
@@ -116,17 +116,16 @@ public void Close()
public void Write(string line, params object[] args)
{
- if (!Enabled) return;
+ if (!Enabled)
+ return;
Write(String.Format(line, args));
}
public void Flush()
{
- if (!Enabled) return;
- if (m_logFile != null)
- {
- m_logFile.Flush();
- }
+ if (!Enabled)
+ return;
+ m_logFile?.Flush();
}
public void Write(string line)
@@ -137,9 +136,9 @@ public void Write(string line)
lock (m_logFileWriteLock)
{
DateTime now = DateTime.UtcNow;
- if (m_logFile == null || now > m_logFileEndTime)
+ if (m_logFile is null || now > m_logFileEndTime)
{
- if (m_logFile != null)
+ if (m_logFile is not null)
{
m_logFile.Close();
m_logFile.Dispose();
@@ -153,12 +152,12 @@ public void Write(string line)
+ String.Format("{0}{1}.log", LogFileHeader, now.ToString("yyyyMMddHHmmss"));
m_logFile = new StreamWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
}
- if (m_logFile != null)
+ if (m_logFile is not null)
{
StringBuilder buff = new StringBuilder(line.Length + 25);
buff.Append(now.ToString("yyyyMMddHHmmssfff"));
// buff.Append(now.ToString("yyyyMMddHHmmss"));
- buff.Append(",");
+ buff.Append('"');
buff.Append(line);
buff.Append("\r\n");
m_logFile.Write(buff.ToString());
@@ -169,10 +168,7 @@ public void Write(string line)
}
catch (Exception e)
{
- if (ErrorLogger != null)
- {
- ErrorLogger.ErrorFormat("{0}: FAILURE WRITING TO LOGFILE: {1}", LogHeader, e);
- }
+ ErrorLogger?.ErrorFormat("{0}: FAILURE WRITING TO LOGFILE: {1}", LogHeader, e);
Enabled = false;
}
return;
diff --git a/OpenSim/Framework/MapAndArray.cs b/OpenSim/Framework/MapAndArray.cs
index e6b2800e643..412c2ae291d 100644
--- a/OpenSim/Framework/MapAndArray.cs
+++ b/OpenSim/Framework/MapAndArray.cs
@@ -27,6 +27,8 @@
using System;
using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
namespace OpenSim.Framework
{
@@ -82,12 +84,10 @@ public bool AddOrReplace(TKey key, TValue value)
{
lock (m_syncRoot)
{
- bool containedKey = m_dict.ContainsKey(key);
-
- m_dict[key] = value;
+ ref TValue curvalue = ref CollectionsMarshal.GetValueRefOrAddDefault(m_dict, key, out bool existed);
+ curvalue = value;
m_array = null;
-
- return !containedKey;
+ return existed;
}
}
@@ -117,9 +117,8 @@ public bool Remove(TKey key)
{
lock (m_syncRoot)
{
- bool removed = m_dict.Remove(key);
m_array = null;
- return removed;
+ return m_dict.Remove(key);
}
}
@@ -156,7 +155,8 @@ public void Clear()
{
lock (m_syncRoot)
{
- m_dict = new Dictionary();
+ if(m_dict.Count > 0)
+ m_dict = new Dictionary();
m_array = null;
}
}
@@ -171,15 +171,21 @@ public TValue[] GetArray()
{
lock (m_syncRoot)
{
- if (m_array == null)
+ if (m_array is null)
{
if(m_dict.Count == 0)
- return new TValue[0];
+ return Array.Empty();
m_array = new TValue[m_dict.Count];
m_dict.Values.CopyTo(m_array, 0);
}
return m_array;
}
}
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Span GetSpan()
+ {
+ return new Span(GetArray());
+ }
}
}
diff --git a/OpenSim/Framework/Monitoring/BaseStatsCollector.cs b/OpenSim/Framework/Monitoring/BaseStatsCollector.cs
index 0d2c5caf80f..809a705d4ed 100644
--- a/OpenSim/Framework/Monitoring/BaseStatsCollector.cs
+++ b/OpenSim/Framework/Monitoring/BaseStatsCollector.cs
@@ -46,39 +46,36 @@ public virtual string Report(IScene scene = null)
public virtual string Report()
{
StringBuilder sb = new StringBuilder(Environment.NewLine);
- sb.Append("MEMORY STATISTICS");
- sb.Append(Environment.NewLine);
sb.AppendFormat(
- "Heap allocated to OpenSim : {0} MB\n",
- Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0));
-
- sb.AppendFormat(
- "Heap allocation rate (last/avg): {0}/{1}MB/s\n",
+ "Heap allocated: {0}MB \t allocation rate (last/avg): {1}/{2}MB/s\n",
+ Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0),
Math.Round((MemoryWatchdog.LastHeapAllocationRate * 1000) / 1048576.0, 3),
Math.Round((MemoryWatchdog.AverageHeapAllocationRate * 1000) / 1048576.0, 3));
+ GCMemoryInfo gcmem = GC.GetGCMemoryInfo();
+ sb.AppendFormat(
+ "GCTotalCommited: {0}MB \t GCTotalAvaiable {1}MB \t GCHMthreshold {2}MB\n",
+ Math.Round(gcmem.TotalCommittedBytes / 1024.0 / 1024.0),
+ Math.Round(gcmem.TotalAvailableMemoryBytes / 1024.0 / 1024.0),
+ Math.Round(gcmem.HighMemoryLoadThresholdBytes / 1024.0 / 1024.0));
+
try
{
using (Process myprocess = Process.GetCurrentProcess())
{
sb.AppendFormat(
- "Process memory: Physical {0} MB \t Paged {1} MB \t Virtual {2} MB\n",
+ "Process memory: Physical {0}MB \t Paged {1}MB\n",
Math.Round(myprocess.WorkingSet64 / 1024.0 / 1024.0),
- Math.Round(myprocess.PagedMemorySize64 / 1024.0 / 1024.0),
- Math.Round(myprocess.VirtualMemorySize64 / 1024.0 / 1024.0));
+ Math.Round(myprocess.PagedMemorySize64 / 1024.0 / 1024.0));
sb.AppendFormat(
- "Peak process memory: Physical {0} MB \t Paged {1} MB \t Virtual {2} MB\n",
+ "Peak process memory: Physical {0}MB \t Paged {1}MB \t\n",
Math.Round(myprocess.PeakWorkingSet64 / 1024.0 / 1024.0),
- Math.Round(myprocess.PeakPagedMemorySize64 / 1024.0 / 1024.0),
- Math.Round(myprocess.PeakVirtualMemorySize64 / 1024.0 / 1024.0));
+ Math.Round(myprocess.PeakPagedMemorySize64 / 1024.0 / 1024.0));
sb.AppendFormat("\nTotal process Threads {0}\n", myprocess.Threads.Count);
}
}
catch
{ }
-// else
-// sb.Append("Process reported as Exited \n");
-
return sb.ToString();
}
diff --git a/OpenSim/Framework/Monitoring/JobEngine.cs b/OpenSim/Framework/Monitoring/JobEngine.cs
index 3f71811d36a..f1eb75748e8 100644
--- a/OpenSim/Framework/Monitoring/JobEngine.cs
+++ b/OpenSim/Framework/Monitoring/JobEngine.cs
@@ -257,7 +257,6 @@ private void ProcessRequests(object o)
m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,currentJob.Name);
currentJob.Action = null;
- currentJob = null;
}
lock (JobLock)
--m_numberThreads;
diff --git a/OpenSim/Framework/Monitoring/OpenSim.Framework.Monitoring.csproj b/OpenSim/Framework/Monitoring/OpenSim.Framework.Monitoring.csproj
index ce560e9b3a1..c67ba9a67b2 100644
--- a/OpenSim/Framework/Monitoring/OpenSim.Framework.Monitoring.csproj
+++ b/OpenSim/Framework/Monitoring/OpenSim.Framework.Monitoring.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Framework.Monitoring
http://opensimulator.org
OpenSim
diff --git a/OpenSim/Framework/Monitoring/ServerStatsCollector.cs b/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
index a26a6e03660..80a6c9c6af1 100644
--- a/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
+++ b/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
@@ -35,7 +35,6 @@
using log4net;
using Nini.Config;
using OpenMetaverse.StructuredData;
-using OpenSim.Framework;
namespace OpenSim.Framework.Monitoring
{
@@ -57,9 +56,9 @@ public class ServerStatsCollector
public string NetworkInterfaceTypes = "Ethernet";
- readonly int performanceCounterSampleInterval = 500;
-// int lastperformanceCounterSampleTime = 0;
-
+ //readonly int performanceCounterSampleInterval = 500;
+ //int lastperformanceCounterSampleTime = 0;
+ /*
private class PerfCounterControl
{
public PerformanceCounter perfCounter;
@@ -78,6 +77,7 @@ public PerfCounterControl(PerformanceCounter pPc, string pName)
}
PerfCounterControl processorPercentPerfCounter = null;
+ */
// IRegionModuleBase.Initialize
public void Initialise(IConfigSource source)
@@ -138,22 +138,22 @@ private void MakeStat(string pName, string pDesc, string pUnit, string pContaine
public void RegisterServerStats()
{
-// lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
- PerformanceCounter tempPC;
- Stat tempStat;
- string tempName;
+ //lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
+ //PerformanceCounter tempPC;
+ //Stat tempStat;
+ //string tempName;
try
{
- tempName = "CPUPercent";
- tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
- processorPercentPerfCounter = new PerfCounterControl(tempPC);
+ //tempName = "CPUPercent";
+ //tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
+ //processorPercentPerfCounter = new PerfCounterControl(tempPC);
// A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
- tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
- StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
- StatVerbosity.Info);
- StatsManager.RegisterStat(tempStat);
- RegisteredStats.Add(tempName, tempStat);
+ //tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
+ // StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
+ // StatVerbosity.Info);
+ //StatsManager.RegisterStat(tempStat);
+ //RegisteredStats.Add(tempName, tempStat);
MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); });
@@ -300,6 +300,7 @@ public void RegisterServerStats()
});
}
+ /*
// Notes on performance counters:
// "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
// "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
@@ -325,6 +326,7 @@ private void GetNextValue(Stat stat, PerfCounterControl perfControl)
}
}
}
+ */
// Lookup the nic that goes with this stat and set the value by using a fetch action.
// Not sure about closure with delegates inside delegates.
diff --git a/OpenSim/Framework/Monitoring/Stats/Stat.cs b/OpenSim/Framework/Monitoring/Stats/Stat.cs
index 97c76f922ff..2bc8c4c499c 100644
--- a/OpenSim/Framework/Monitoring/Stats/Stat.cs
+++ b/OpenSim/Framework/Monitoring/Stats/Stat.cs
@@ -27,10 +27,7 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
using System.Text;
-using log4net;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Monitoring
@@ -315,9 +312,9 @@ public bool ComputeMeasuresOfInterest(out double lastChangeOverTime, out double
lock (m_samples)
{
- // m_log.DebugFormat(
- // "[STAT]: Samples for {0} are {1}",
- // Name, string.Join(",", m_samples.Select(s => s.ToString()).ToArray()));
+ //m_log.DebugFormat(
+ // "[STAT]: Samples for {0} are {1}",
+ // Name, string.Join(",", m_samples.Select(s => s.ToString()).ToArray()));
foreach (double s in m_samples)
{
@@ -331,8 +328,7 @@ public bool ComputeMeasuresOfInterest(out double lastChangeOverTime, out double
if (lastSample != null && penultimateSample != null)
{
- lastChangeOverTime
- = ((double)lastSample - (double)penultimateSample) / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
+ lastChangeOverTime = ((double)lastSample - (double)penultimateSample) / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
}
int divisor = m_samples.Count <= 1 ? 1 : m_samples.Count - 1;
diff --git a/OpenSim/Framework/Monitoring/StatsManager.cs b/OpenSim/Framework/Monitoring/StatsManager.cs
index 0e5626b164e..447303e7dc3 100755
--- a/OpenSim/Framework/Monitoring/StatsManager.cs
+++ b/OpenSim/Framework/Monitoring/StatsManager.cs
@@ -28,6 +28,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Linq;
using System.Text;
@@ -188,6 +189,43 @@ private static void OutputAllStatsToConsole(ICommandConsole con)
{
foreach (string report in GetAllStatsReports())
con.Output(report);
+ con.Output(MemoryReport());
+ }
+
+ private static string MemoryReport()
+ {
+ StringBuilder sb = new StringBuilder(Environment.NewLine);
+ sb.AppendFormat(
+ "Heap allocated: {0}MB \t allocation rate (last/avg): {1}/{2}MB/s\n",
+ Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0),
+ Math.Round((MemoryWatchdog.LastHeapAllocationRate * 1000) / 1048576.0, 3),
+ Math.Round((MemoryWatchdog.AverageHeapAllocationRate * 1000) / 1048576.0, 3));
+
+ GCMemoryInfo gcmem = GC.GetGCMemoryInfo();
+ sb.AppendFormat(
+ "GCTotalCommited: {0}MB \t GCTotalAvaiable {1}MB \t GCHMthreshold {2}MB\n",
+ Math.Round(gcmem.TotalCommittedBytes / 1024.0 / 1024.0),
+ Math.Round(gcmem.TotalAvailableMemoryBytes / 1024.0 / 1024.0),
+ Math.Round(gcmem.HighMemoryLoadThresholdBytes / 1024.0 / 1024.0));
+
+ try
+ {
+ using (Process myprocess = Process.GetCurrentProcess())
+ {
+ sb.AppendFormat(
+ "Process memory: Physical {0}MB \t Paged {1}MB\n",
+ Math.Round(myprocess.WorkingSet64 / 1024.0 / 1024.0),
+ Math.Round(myprocess.PagedMemorySize64 / 1024.0 / 1024.0));
+ sb.AppendFormat(
+ "Peak process memory: Physical {0}MB \t Paged {1}MB \t\n",
+ Math.Round(myprocess.PeakWorkingSet64 / 1024.0 / 1024.0),
+ Math.Round(myprocess.PeakPagedMemorySize64 / 1024.0 / 1024.0));
+ sb.AppendFormat("\nTotal process Threads {0}\n", myprocess.Threads.Count);
+ }
+ }
+ catch
+ { }
+ return sb.ToString();
}
private static List GetCategoryStatsReports(
diff --git a/OpenSim/Framework/Monitoring/Watchdog.cs b/OpenSim/Framework/Monitoring/Watchdog.cs
index 6ad3cdda892..cb0e5993e54 100644
--- a/OpenSim/Framework/Monitoring/Watchdog.cs
+++ b/OpenSim/Framework/Monitoring/Watchdog.cs
@@ -197,8 +197,8 @@ public static void Stop()
// m_log.DebugFormat(
// "[WATCHDOG]: Stop: Removing thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId);
- if(t.IsAlive)
- t.Abort();
+ //if(t.IsAlive)
+ // t.Abort();
}
m_threads.Clear();
}
@@ -269,18 +269,13 @@ public static bool AbortThread(int threadID)
{
lock (m_threads)
{
- if (m_threads.ContainsKey(threadID))
+ if(RemoveThread(threadID))
{
- ThreadWatchdogInfo twi = m_threads[threadID];
- twi.Thread.Abort();
- RemoveThread(threadID);
-
+ //ThreadWatchdogInfo twi = m_threads[threadID];
+ //twi.Thread.Abort();
return true;
}
- else
- {
- return false;
- }
+ return false;
}
}
@@ -325,11 +320,8 @@ public static ThreadWatchdogInfo GetCurrentThreadInfo()
{
lock (m_threads)
{
- if (m_threads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
- return m_threads[Thread.CurrentThread.ManagedThreadId];
+ return m_threads.TryGetValue(Thread.CurrentThread.ManagedThreadId, out ThreadWatchdogInfo twi) ? twi : null;
}
-
- return null;
}
///
diff --git a/OpenSim/Framework/MultipartForm.cs b/OpenSim/Framework/MultipartForm.cs
index 7a13e8b21cb..35cf82adb30 100644
--- a/OpenSim/Framework/MultipartForm.cs
+++ b/OpenSim/Framework/MultipartForm.cs
@@ -129,11 +129,10 @@ public static HttpWebResponse Post(HttpWebRequest request, List postPar
private static string Boundary()
{
- Random rnd = new Random();
string formDataBoundary = String.Empty;
while (formDataBoundary.Length < 15)
- formDataBoundary = formDataBoundary + rnd.Next();
+ formDataBoundary = formDataBoundary + Random.Shared.Next();
formDataBoundary = formDataBoundary.Substring(0, 15);
formDataBoundary = "-----------------------------" + formDataBoundary;
diff --git a/OpenSim/Framework/ObjectJobEngine.cs b/OpenSim/Framework/ObjectJobEngine.cs
index 11027c9b341..19e59d7147e 100644
--- a/OpenSim/Framework/ObjectJobEngine.cs
+++ b/OpenSim/Framework/ObjectJobEngine.cs
@@ -124,7 +124,7 @@ public void Cancel()
return;
try
{
- while(m_jobQueue.TryTake(out object dummy));
+ while(m_jobQueue.TryTake(out _));
m_cancelSource.Cancel();
}
catch { }
diff --git a/OpenSim/Framework/OpenSim.Framework.csproj b/OpenSim/Framework/OpenSim.Framework.csproj
index 89550fb395d..83ee00b34cb 100644
--- a/OpenSim/Framework/OpenSim.Framework.csproj
+++ b/OpenSim/Framework/OpenSim.Framework.csproj
@@ -1,6 +1,6 @@

- net48
+ net8.0
OpenSim.Framework
http://opensimulator.org
OpenSim.Framework
@@ -28,15 +28,9 @@
..\..\bin\OpenMetaverseTypes.dll
False
-
- False
-
False
-
- False
-
..\..\bin\XMLRPC.dll
False
@@ -190,6 +184,7 @@
+
@@ -208,4 +203,4 @@
VersionInfo.tt
-
\ No newline at end of file
+
diff --git a/OpenSim/Framework/OutboundUrlFilter.cs b/OpenSim/Framework/OutboundUrlFilter.cs
index 63ae3614485..2e3cc2ca157 100644
--- a/OpenSim/Framework/OutboundUrlFilter.cs
+++ b/OpenSim/Framework/OutboundUrlFilter.cs
@@ -33,6 +33,8 @@
using log4net;
using LukeSkywalker.IPNetwork;
using Nini.Config;
+using IPNetwork = LukeSkywalker.IPNetwork.IPNetwork;
+
namespace OpenSim.Framework
{
diff --git a/OpenSim/Framework/PluginLoader.cs b/OpenSim/Framework/PluginLoader.cs
index 884f4dd35e0..044b9de3e76 100644
--- a/OpenSim/Framework/PluginLoader.cs
+++ b/OpenSim/Framework/PluginLoader.cs
@@ -159,17 +159,13 @@ public void Load()
{
log.Info("[PLUGINS]: Loading extension point " + ext);
- if (constraints.ContainsKey(ext))
+ if (constraints.TryGetValue(ext , out IPluginConstraint cons))
{
- IPluginConstraint cons = constraints[ext];
if (cons.Apply(ext))
log.Error("[PLUGINS]: " + ext + " failed constraint: " + cons.Message);
}
- IPluginFilter filter = null;
-
- if (filters.ContainsKey(ext))
- filter = filters[ext];
+ filters.TryGetValue(ext, out IPluginFilter filter);
List loadedPlugins = new List();
foreach (PluginExtensionNode node in AddinManager.GetExtensionNodes(ext))
diff --git a/OpenSim/Framework/PrimitiveBaseShape.cs b/OpenSim/Framework/PrimitiveBaseShape.cs
index 4199288315c..fb9c416ec03 100644
--- a/OpenSim/Framework/PrimitiveBaseShape.cs
+++ b/OpenSim/Framework/PrimitiveBaseShape.cs
@@ -149,17 +149,41 @@ public class PrimitiveBaseShape
[XmlIgnore] private bool _projectionEntry;
[XmlIgnore] private bool _meshFlagsEntry;
- //extra parameters extramesh/flag
[XmlIgnore]
public Primitive.ReflectionProbe ReflectionProbe = null;
- //extra parameters extramesh/flag
[XmlIgnore]
public Primitive.RenderMaterials RenderMaterials = null;
-
public bool MeshFlagEntry
{
- get { return _meshFlagsEntry;}
+ get { return _meshFlagsEntry; }
+ }
+
+ public bool AnimeshEnabled
+ {
+ get
+ {
+ return(_meshFlagsEntry &&
+ (_meshFlags & 0x01) != 0 &&
+ (_sculptType & 0x07) == (int)OpenMetaverse.SculptType.Mesh);
+ }
+ set
+ {
+ if((_sculptType & 0x07) != (int)OpenMetaverse.SculptType.Mesh)
+ {
+ _meshFlagsEntry = false;
+ _meshFlags = 0;
+ return;
+ }
+
+ if (value)
+ {
+ _meshFlagsEntry = true;
+ _meshFlags |= 1;
+ }
+ else
+ _meshFlags &= 0xfe;
+ }
}
public byte ProfileCurve
@@ -177,11 +201,11 @@ public byte ProfileCurve
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
- this._hollowShape = HollowShape.Same;
+ _hollowShape = HollowShape.Same;
}
else
{
- this._hollowShape = (HollowShape)hollowShapeByte;
+ _hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
@@ -193,11 +217,11 @@ public byte ProfileCurve
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
- this._profileShape = ProfileShape.Square;
+ _profileShape = ProfileShape.Square;
}
else
{
- this._profileShape = (ProfileShape)profileShapeByte;
+ _profileShape = (ProfileShape)profileShapeByte;
}
}
}
@@ -221,7 +245,7 @@ public PrimitiveBaseShape()
///
public PrimitiveBaseShape(Primitive prim)
{
-// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
+ //m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
PCode = (byte)prim.PrimData.PCode;
@@ -267,7 +291,7 @@ public Primitive.TextureEntry Textures
{
get
{
-// m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
+ //m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); }
catch { }
@@ -305,55 +329,56 @@ public static PrimitiveBaseShape Default
public static PrimitiveBaseShape Create()
{
- PrimitiveBaseShape shape = new PrimitiveBaseShape();
- return shape;
+ return new PrimitiveBaseShape();
}
public static PrimitiveBaseShape CreateBox()
{
- PrimitiveBaseShape shape = Create();
-
- shape._pathCurve = (byte) Extrusion.Straight;
- shape._profileShape = ProfileShape.Square;
- shape._pathScaleX = 100;
- shape._pathScaleY = 100;
+ PrimitiveBaseShape shape = new()
+ {
+ _pathCurve = (byte)Extrusion.Straight,
+ _profileShape = ProfileShape.Square,
+ _pathScaleX = 100,
+ _pathScaleY = 100
+ };
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
- PrimitiveBaseShape shape = Create();
-
- shape._pathCurve = (byte) Extrusion.Curve1;
- shape._profileShape = ProfileShape.HalfCircle;
- shape._pathScaleX = 100;
- shape._pathScaleY = 100;
+ PrimitiveBaseShape shape = new()
+ {
+ _pathCurve = (byte)Extrusion.Curve1,
+ _profileShape = ProfileShape.HalfCircle,
+ _pathScaleX = 100,
+ _pathScaleY = 100
+ };
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
- PrimitiveBaseShape shape = Create();
-
- shape._pathCurve = (byte) Extrusion.Curve1;
- shape._profileShape = ProfileShape.Square;
-
- shape._pathScaleX = 100;
- shape._pathScaleY = 100;
-
+ PrimitiveBaseShape shape = new()
+ {
+ _pathCurve = (byte)Extrusion.Curve1,
+ _profileShape = ProfileShape.Square,
+ _pathScaleX = 100,
+ _pathScaleY = 100
+ };
return shape;
}
public static PrimitiveBaseShape CreateMesh(int numberOfFaces, UUID meshAssetID)
{
- PrimitiveBaseShape shape = new PrimitiveBaseShape();
-
- shape._pathScaleX = 100;
- shape._pathScaleY = 100;
+ PrimitiveBaseShape shape = new()
+ {
+ _pathScaleX = 100,
+ _pathScaleY = 100
+ };
- if(numberOfFaces <= 0) // oops ?
+ if (numberOfFaces <= 0) // oops ?
numberOfFaces = 1;
switch(numberOfFaces)
@@ -489,329 +514,217 @@ public byte[] ExtraParams
}
}
- public ushort PathBegin {
- get {
- return _pathBegin;
- }
- set {
- _pathBegin = value;
- }
+ public ushort PathBegin
+ {
+ get { return _pathBegin; }
+ set { _pathBegin = value; }
}
- public byte PathCurve {
- get {
- return _pathCurve;
- }
- set {
- _pathCurve = value;
- }
+ public byte PathCurve
+ {
+ get { return _pathCurve; }
+ set { _pathCurve = value; }
}
- public ushort PathEnd {
- get {
- return _pathEnd;
- }
- set {
- _pathEnd = value;
- }
+ public ushort PathEnd
+ {
+ get { return _pathEnd; }
+ set { _pathEnd = value; }
}
- public sbyte PathRadiusOffset {
- get {
- return _pathRadiusOffset;
- }
- set {
- _pathRadiusOffset = value;
- }
+ public sbyte PathRadiusOffset
+ {
+ get { return _pathRadiusOffset; }
+ set { _pathRadiusOffset = value; }
}
- public byte PathRevolutions {
- get {
- return _pathRevolutions;
- }
- set {
- _pathRevolutions = value;
- }
+ public byte PathRevolutions
+ {
+ get { return _pathRevolutions; }
+ set { _pathRevolutions = value; }
}
- public byte PathScaleX {
- get {
- return _pathScaleX;
- }
- set {
- _pathScaleX = value;
- }
+ public byte PathScaleX
+ {
+ get { return _pathScaleX; }
+ set { _pathScaleX = value; }
}
- public byte PathScaleY {
- get {
- return _pathScaleY;
- }
- set {
- _pathScaleY = value;
- }
+ public byte PathScaleY
+ {
+ get { return _pathScaleY; }
+ set { _pathScaleY = value; }
}
- public byte PathShearX {
- get {
- return _pathShearX;
- }
- set {
- _pathShearX = value;
- }
+ public byte PathShearX
+ {
+ get { return _pathShearX; }
+ set { _pathShearX = value; }
}
- public byte PathShearY {
- get {
- return _pathShearY;
- }
- set {
- _pathShearY = value;
- }
+ public byte PathShearY
+ {
+ get { return _pathShearY; }
+ set { _pathShearY = value; }
}
- public sbyte PathSkew {
- get {
- return _pathSkew;
- }
- set {
- _pathSkew = value;
- }
+ public sbyte PathSkew
+ {
+ get { return _pathSkew; }
+ set { _pathSkew = value; }
}
- public sbyte PathTaperX {
- get {
- return _pathTaperX;
- }
- set {
- _pathTaperX = value;
- }
+ public sbyte PathTaperX
+ {
+ get { return _pathTaperX; }
+ set { _pathTaperX = value; }
}
- public sbyte PathTaperY {
- get {
- return _pathTaperY;
- }
- set {
- _pathTaperY = value;
- }
+ public sbyte PathTaperY
+ {
+ get { return _pathTaperY; }
+ set { _pathTaperY = value; }
}
- public sbyte PathTwist {
- get {
- return _pathTwist;
- }
- set {
- _pathTwist = value;
- }
+ public sbyte PathTwist
+ {
+ get { return _pathTwist; }
+ set { _pathTwist = value; }
}
- public sbyte PathTwistBegin {
- get {
- return _pathTwistBegin;
- }
- set {
- _pathTwistBegin = value;
- }
+ public sbyte PathTwistBegin
+ {
+ get { return _pathTwistBegin; }
+ set { _pathTwistBegin = value; }
}
- public byte PCode {
- get {
- return _pCode;
- }
- set {
- _pCode = value;
- }
+ public byte PCode
+ {
+ get { return _pCode; }
+ set { _pCode = value; }
}
- public ushort ProfileBegin {
- get {
- return _profileBegin;
- }
- set {
- _profileBegin = value;
- }
+ public ushort ProfileBegin
+ {
+ get { return _profileBegin; }
+ set { _profileBegin = value; }
}
- public ushort ProfileEnd {
- get {
- return _profileEnd;
- }
- set {
- _profileEnd = value;
- }
+ public ushort ProfileEnd
+ {
+ get { return _profileEnd; }
+ set { _profileEnd = value; }
}
- public ushort ProfileHollow {
- get {
- return _profileHollow;
- }
- set {
- _profileHollow = value;
- }
+ public ushort ProfileHollow
+ {
+ get { return _profileHollow; }
+ set { _profileHollow = value; }
}
- public Vector3 Scale {
- get {
- return _scale;
- }
- set {
- _scale = value;
- }
+ public Vector3 Scale
+ {
+ get { return _scale; }
+ set { _scale = value; }
}
- public byte State {
- get {
- return _state;
- }
- set {
- _state = value;
- }
+ public byte State
+ {
+ get { return _state; }
+ set { _state = value; }
}
- public byte LastAttachPoint {
- get {
- return _lastattach;
- }
- set {
- _lastattach = value;
- }
+ public byte LastAttachPoint
+ {
+ get { return _lastattach; }
+ set { _lastattach = value; }
}
- public ProfileShape ProfileShape {
- get {
- return _profileShape;
- }
- set {
- _profileShape = value;
- }
+ public ProfileShape ProfileShape
+ {
+ get { return _profileShape; }
+ set { _profileShape = value; }
}
- public HollowShape HollowShape {
- get {
- return _hollowShape;
- }
- set {
- _hollowShape = value;
- }
+ public HollowShape HollowShape
+ {
+ get { return _hollowShape; }
+ set { _hollowShape = value; }
}
- public UUID SculptTexture {
- get {
- return _sculptTexture;
- }
- set {
- _sculptTexture = value;
- }
+ public UUID SculptTexture
+ {
+ get { return _sculptTexture; }
+ set { _sculptTexture = value; }
}
public byte SculptType
{
- get
- {
- return _sculptType;
- }
- set
- {
- _sculptType = value;
- }
+ get { return _sculptType; }
+ set { _sculptType = value; }
}
// This is only used at runtime. For sculpties this holds the texture data, and for meshes
// the mesh data.
public byte[] SculptData
{
- get
- {
- return _sculptData;
- }
- set
- {
-// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Setting SculptData to data with length {0}", value.Length);
- _sculptData = value;
- }
+ get { return _sculptData; }
+ set { _sculptData = value; }
}
public int FlexiSoftness
{
- get
- {
- return _flexiSoftness;
- }
- set
- {
- _flexiSoftness = value;
- }
+ get { return _flexiSoftness; }
+ set { _flexiSoftness = value; }
}
- public float FlexiTension {
- get {
- return _flexiTension;
- }
- set {
- _flexiTension = value;
- }
+ public float FlexiTension
+ {
+ get { return _flexiTension; }
+ set { _flexiTension = value; }
}
- public float FlexiDrag {
- get {
- return _flexiDrag;
- }
- set {
- _flexiDrag = value;
- }
+ public float FlexiDrag
+ {
+ get { return _flexiDrag; }
+ set { _flexiDrag = value; }
}
- public float FlexiGravity {
- get {
- return _flexiGravity;
- }
- set {
- _flexiGravity = value;
- }
+ public float FlexiGravity
+ {
+ get { return _flexiGravity; }
+ set { _flexiGravity = value; }
}
- public float FlexiWind {
- get {
- return _flexiWind;
- }
- set {
- _flexiWind = value;
- }
+ public float FlexiWind
+ {
+ get { return _flexiWind; }
+ set { _flexiWind = value; }
}
- public float FlexiForceX {
- get {
- return _flexiForceX;
- }
- set {
- _flexiForceX = value;
- }
+ public float FlexiForceX
+ {
+ get { return _flexiForceX; }
+ set { _flexiForceX = value; }
}
- public float FlexiForceY {
- get {
- return _flexiForceY;
- }
- set {
- _flexiForceY = value;
- }
+ public float FlexiForceY
+ {
+ get { return _flexiForceY; }
+ set { _flexiForceY = value; }
}
- public float FlexiForceZ {
- get {
- return _flexiForceZ;
- }
- set {
- _flexiForceZ = value;
- }
+ public float FlexiForceZ
+ {
+ get { return _flexiForceZ; }
+ set { _flexiForceZ = value; }
}
- public float LightColorR {
- get {
- return _lightColorR;
- }
- set {
+ public float LightColorR
+ {
+ get { return _lightColorR; }
+ set
+ {
if (value < 0)
_lightColorR = 0;
else if (value > 1.0f)
@@ -821,11 +734,11 @@ public float LightColorR {
}
}
- public float LightColorG {
- get {
- return _lightColorG;
- }
- set {
+ public float LightColorG
+ {
+ get { return _lightColorG; }
+ set
+ {
if (value < 0)
_lightColorG = 0;
else if (value > 1.0f)
@@ -835,11 +748,11 @@ public float LightColorG {
}
}
- public float LightColorB {
- get {
- return _lightColorB;
- }
- set {
+ public float LightColorB
+ {
+ get { return _lightColorB; }
+ set
+ {
if (value < 0)
_lightColorB = 0;
else if (value > 1.0f)
@@ -849,11 +762,11 @@ public float LightColorB {
}
}
- public float LightColorA {
- get {
- return _lightColorA;
- }
- set {
+ public float LightColorA
+ {
+ get { return _lightColorA; }
+ set
+ {
if (value < 0)
_lightColorA = 0;
else if (value > 1.0f)
@@ -863,113 +776,77 @@ public float LightColorA {
}
}
- public float LightRadius {
- get {
- return _lightRadius;
- }
- set {
- _lightRadius = value;
- }
+ public float LightRadius
+ {
+ get { return _lightRadius; }
+ set { _lightRadius = value; }
}
- public float LightCutoff {
- get {
- return _lightCutoff;
- }
- set {
- _lightCutoff = value;
- }
+ public float LightCutoff
+ {
+ get { return _lightCutoff; }
+ set { _lightCutoff = value; }
}
- public float LightFalloff {
- get {
- return _lightFalloff;
- }
- set {
- _lightFalloff = value;
- }
+ public float LightFalloff
+ {
+ get { return _lightFalloff; }
+ set { _lightFalloff = value; }
}
- public float LightIntensity {
- get {
- return _lightIntensity;
- }
- set {
- _lightIntensity = value;
- }
+ public float LightIntensity
+ {
+ get { return _lightIntensity; }
+ set { _lightIntensity = value; }
}
// only means we do have flexi data
- public bool FlexiEntry {
- get {
- return _flexiEntry;
- }
- set {
- _flexiEntry = value;
- }
+ public bool FlexiEntry
+ {
+ get { return _flexiEntry; }
+ set { _flexiEntry = value; }
}
- public bool LightEntry {
- get {
- return _lightEntry;
- }
- set {
- _lightEntry = value;
- }
+ public bool LightEntry
+ {
+ get { return _lightEntry; }
+ set { _lightEntry = value; }
}
- public bool SculptEntry {
- get {
- return _sculptEntry;
- }
- set {
- _sculptEntry = value;
- }
+ public bool SculptEntry
+ {
+ get { return _sculptEntry; }
+ set { _sculptEntry = value; }
}
- public bool ProjectionEntry {
- get {
- return _projectionEntry;
- }
- set {
- _projectionEntry = value;
- }
+ public bool ProjectionEntry
+ {
+ get { return _projectionEntry; }
+ set { _projectionEntry = value; }
}
- public UUID ProjectionTextureUUID {
- get {
- return _projectionTextureID;
- }
- set {
- _projectionTextureID = value;
- }
+ public UUID ProjectionTextureUUID
+ {
+ get { return _projectionTextureID; }
+ set { _projectionTextureID = value; }
}
- public float ProjectionFOV {
- get {
- return _projectionFOV;
- }
- set {
- _projectionFOV = value;
- }
+ public float ProjectionFOV
+ {
+ get { return _projectionFOV; }
+ set { _projectionFOV = value; }
}
- public float ProjectionFocus {
- get {
- return _projectionFocus;
- }
- set {
- _projectionFocus = value;
- }
+ public float ProjectionFocus
+ {
+ get { return _projectionFocus; }
+ set { _projectionFocus = value; }
}
- public float ProjectionAmbiance {
- get {
- return _projectionAmb;
- }
- set {
- _projectionAmb = value;
- }
+ public float ProjectionAmbiance
+ {
+ get { return _projectionAmb; }
+ set { _projectionAmb = value; }
}
public ulong GetMeshKey(Vector3 size, float lod)
@@ -981,38 +858,35 @@ public ulong GetMeshKey(Vector3 size, float lod, bool convex)
{
ulong hash = 5381;
- hash = djb2(hash, this.PathCurve);
- hash = djb2(hash, (byte)((byte)this.HollowShape | (byte)this.ProfileShape));
- hash = djb2(hash, this.PathBegin);
- hash = djb2(hash, this.PathEnd);
- hash = djb2(hash, this.PathScaleX);
- hash = djb2(hash, this.PathScaleY);
- hash = djb2(hash, this.PathShearX);
- hash = djb2(hash, this.PathShearY);
- hash = djb2(hash, (byte)this.PathTwist);
- hash = djb2(hash, (byte)this.PathTwistBegin);
- hash = djb2(hash, (byte)this.PathRadiusOffset);
- hash = djb2(hash, (byte)this.PathTaperX);
- hash = djb2(hash, (byte)this.PathTaperY);
- hash = djb2(hash, this.PathRevolutions);
- hash = djb2(hash, (byte)this.PathSkew);
- hash = djb2(hash, this.ProfileBegin);
- hash = djb2(hash, this.ProfileEnd);
- hash = djb2(hash, this.ProfileHollow);
+ hash = djb2(hash, PathCurve);
+ hash = djb2(hash, (byte)((byte)HollowShape | (byte)ProfileShape));
+ hash = djb2(hash, PathBegin);
+ hash = djb2(hash, PathEnd);
+ hash = djb2(hash, PathScaleX);
+ hash = djb2(hash, PathScaleY);
+ hash = djb2(hash, PathShearX);
+ hash = djb2(hash, PathShearY);
+ hash = djb2(hash, (byte)PathTwist);
+ hash = djb2(hash, (byte)PathTwistBegin);
+ hash = djb2(hash, (byte)PathRadiusOffset);
+ hash = djb2(hash, (byte)PathTaperX);
+ hash = djb2(hash, (byte)PathTaperY);
+ hash = djb2(hash, PathRevolutions);
+ hash = djb2(hash, (byte)PathSkew);
+ hash = djb2(hash, ProfileBegin);
+ hash = djb2(hash, ProfileEnd);
+ hash = djb2(hash, ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
hash = djb2(hash, size.X);
hash = djb2(hash, size.Y);
hash = djb2(hash, size.Z);
-
- // Include LOD in hash, accounting for endianness
+
hash = djb2(hash, lod);
- byte[] lodBytes = new byte[4];
-
// include sculpt UUID
- if (this.SculptEntry)
+ if (SculptEntry)
{
byte[] scaleBytes = this.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
@@ -1025,20 +899,20 @@ public ulong GetMeshKey(Vector3 size, float lod, bool convex)
return hash;
}
- private ulong djb2(ulong hash, byte c)
+ private static ulong djb2(ulong hash, byte c)
{
//return ((hash << 5) + hash) + (ulong)c;
return 33 * hash + (ulong)c;
}
- private ulong djb2(ulong hash, ushort c)
+ private static ulong djb2(ulong hash, ushort c)
{
//hash = ((hash << 5) + hash) + (ulong)((byte)c);
//return ((hash << 5) + hash) + (ulong)(c >> 8);
return 33 * hash + c;
}
- private ulong djb2(ulong hash, float c)
+ private static ulong djb2(ulong hash, float c)
{
//hash = ((hash << 5) + hash) + (ulong)((byte)c);
//return ((hash << 5) + hash) + (ulong)(c >> 8);
@@ -1097,15 +971,11 @@ public unsafe byte[] ExtraParamsToBytes()
TotalBytesLength += 9 + 2 + 4; // data
}
- if (RenderMaterials != null)
+ bool hasRenderMaterials = RenderMaterials is not null && RenderMaterials.entries is not null && RenderMaterials.entries.Length > 0;
+ if (hasRenderMaterials)
{
ExtraParamsNum++;
- if (RenderMaterials.entries == null || RenderMaterials.entries.Length == 0)
- TotalBytesLength++;
- else
- {
- TotalBytesLength += 1 + 17 * RenderMaterials.entries.Length + 2 + 4; // data
- }
+ TotalBytesLength += 1 + 17 * RenderMaterials.entries.Length + 2 + 4; // data
}
byte[] safeReturnBytes = new byte[TotalBytesLength];
@@ -1193,7 +1063,7 @@ public unsafe byte[] ExtraParamsToBytes()
*returnBytes++ = ReflectionProbe.Flags;
}
- if (RenderMaterials != null && RenderMaterials.entries != null && RenderMaterials.entries.Length > 0)
+ if (hasRenderMaterials)
{
*returnBytes = MaterialsEP; returnBytes += 2;
@@ -1267,6 +1137,7 @@ public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
if (!inUse)
{
_meshFlagsEntry = false;
+ _meshFlags = 0;
return;
}
ReadMeshFlagsData(data, 0);
@@ -1427,7 +1298,7 @@ public void ReadLightData(byte[] data, int pos)
if (data.Length - pos >= 16)
{
_lightEntry = true;
- Color4 lColor = new Color4(data, pos, false);
+ Color4 lColor = new(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
@@ -1476,16 +1347,8 @@ public void ReadProjectionData(byte[] data, int pos)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadMeshFlagsData(byte[] data, int pos)
{
- if (data.Length - pos >= 4)
- {
- _meshFlagsEntry = true;
- _meshFlags = Utils.BytesToUInt(data, pos);
- }
- else
- {
- _meshFlagsEntry = true;
- _meshFlags = 0;
- }
+ _meshFlagsEntry = true;
+ _meshFlags = data.Length - pos >= 4 ? Utils.BytesToUInt(data, pos) : 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -1518,10 +1381,8 @@ public int ReadRenderMaterials(byte[] data, int pos, int size)
entries[i].id = new UUID(data, pos);
pos += 16;
}
- RenderMaterials = new Primitive.RenderMaterials
- {
- entries = entries
- };
+ RenderMaterials ??= new Primitive.RenderMaterials();
+ RenderMaterials.entries = entries;
}
}
return size + 4;
@@ -1547,84 +1408,172 @@ public Primitive ToOmvPrimitive()
///
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
- OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
-
- prim.Scale = this.Scale;
- prim.Position = position;
- prim.Rotation = rotation;
+ OpenMetaverse.Primitive prim = new()
+ {
+ Scale = this.Scale,
+ Position = position,
+ Rotation = rotation
+ };
- if (this.SculptEntry)
+ if (SculptEntry)
{
- prim.Sculpt = new Primitive.SculptData();
- prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
- prim.Sculpt.SculptTexture = this.SculptTexture;
+ prim.Sculpt = new Primitive.SculptData
+ {
+ Type = (SculptType)SculptType,
+ SculptTexture = SculptTexture
+ };
}
- prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
- prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
- prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
- prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
+ prim.PrimData.PathShearX = PathShearX < 128 ? (float)PathShearX * 0.01f : (float)(PathShearX - 256) * 0.01f;
+ prim.PrimData.PathShearY = PathShearY < 128 ? (float)PathShearY * 0.01f : (float)(PathShearY - 256) * 0.01f;
+ prim.PrimData.PathBegin = (float)PathBegin * 2.0e-5f;
+ prim.PrimData.PathEnd = 1.0f - (float)PathEnd * 2.0e-5f;
- prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
- prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
+ prim.PrimData.PathScaleX = (200 - PathScaleX) * 0.01f;
+ prim.PrimData.PathScaleY = (200 - PathScaleY) * 0.01f;
- prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
- prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
+ prim.PrimData.PathTaperX = PathTaperX * 0.01f;
+ prim.PrimData.PathTaperY = PathTaperY * 0.01f;
- prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
- prim.PrimData.PathTwist = this.PathTwist * 0.01f;
+ prim.PrimData.PathTwistBegin = PathTwistBegin * 0.01f;
+ prim.PrimData.PathTwist = PathTwist * 0.01f;
- prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
- prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
- prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
+ prim.PrimData.ProfileBegin = (float)ProfileBegin * 2.0e-5f;
+ prim.PrimData.ProfileEnd = 1.0f - (float)ProfileEnd * 2.0e-5f;
+ prim.PrimData.ProfileHollow = (float)ProfileHollow * 2.0e-5f;
- prim.PrimData.profileCurve = this.ProfileCurve;
- prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
+ prim.PrimData.profileCurve = ProfileCurve;
+ prim.PrimData.ProfileHole = (HoleType)HollowShape;
- prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
- prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
- prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
- prim.PrimData.PathSkew = 0.01f * this.PathSkew;
+ prim.PrimData.PathCurve = (PathCurve)PathCurve;
+ prim.PrimData.PathRadiusOffset = 0.01f * PathRadiusOffset;
+ prim.PrimData.PathRevolutions = 1.0f + 0.015f * PathRevolutions;
+ prim.PrimData.PathSkew = 0.01f * PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
- if (this.FlexiEntry)
+ if (FlexiEntry)
{
- prim.Flexible = new Primitive.FlexibleData();
- prim.Flexible.Drag = this.FlexiDrag;
- prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
- prim.Flexible.Gravity = this.FlexiGravity;
- prim.Flexible.Softness = this.FlexiSoftness;
- prim.Flexible.Tension = this.FlexiTension;
- prim.Flexible.Wind = this.FlexiWind;
+ prim.Flexible = new Primitive.FlexibleData
+ {
+ Drag = FlexiDrag,
+ Force = new Vector3(FlexiForceX, FlexiForceY, FlexiForceZ),
+ Gravity = FlexiGravity,
+ Softness = FlexiSoftness,
+ Tension = FlexiTension,
+ Wind = FlexiWind
+ };
}
- if (this.LightEntry)
+ if (LightEntry)
{
- prim.Light = new Primitive.LightData();
- prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
- prim.Light.Cutoff = this.LightCutoff;
- prim.Light.Falloff = this.LightFalloff;
- prim.Light.Intensity = this.LightIntensity;
- prim.Light.Radius = this.LightRadius;
+ prim.Light = new Primitive.LightData
+ {
+ Color = new Color4(LightColorR, LightColorG, LightColorB, LightColorA),
+ Cutoff = LightCutoff,
+ Falloff = LightFalloff,
+ Intensity = LightIntensity,
+ Radius = LightRadius
+ };
}
- prim.Textures = this.Textures;
+ prim.Textures = Textures;
- prim.Properties = new Primitive.ObjectProperties();
- prim.Properties.Name = "Object";
- prim.Properties.Description = "";
- prim.Properties.CreatorID = UUID.Zero;
- prim.Properties.GroupID = UUID.Zero;
- prim.Properties.OwnerID = UUID.Zero;
- prim.Properties.Permissions = new Permissions();
- prim.Properties.SalePrice = 10;
- prim.Properties.SaleType = new SaleType();
+ prim.Properties = new Primitive.ObjectProperties
+ {
+ Name = "Object",
+ Description = "",
+ CreatorID = UUID.Zero,
+ GroupID = UUID.Zero,
+ OwnerID = UUID.Zero,
+ Permissions = new Permissions(),
+ SalePrice = 10,
+ SaleType = new SaleType()
+ };
return prim;
}
+ public byte[] RenderMaterialsOvrToRawBin()
+ {
+ // byte: number of entries
+ // repeat:
+ // byte; entry face index
+ // byte; low entry override utf8 length
+ // byte: high entry override utf8 length
+ // utf8 bytes: override
+
+ if (RenderMaterials is null)
+ return null;
+
+ if (RenderMaterials.overrides is null || RenderMaterials.overrides.Length == 0)
+ return new byte[] { 0 }; // store so outdated viewer caches can be updated
+
+ int nentries = 0;
+ for (int i = 0; i < RenderMaterials.overrides.Length; i++)
+ {
+ if (!string.IsNullOrEmpty(RenderMaterials.overrides[i].data))
+ nentries++;
+ }
+ if(nentries == 0)
+ return new byte[] { 0 };
+
+ osUTF8 sb = OSUTF8Cached.Acquire();
+ sb.Append((byte)nentries);
+ for (int i = 0; i < RenderMaterials.overrides.Length; i++)
+ {
+ if (string.IsNullOrEmpty(RenderMaterials.overrides[i].data))
+ continue;
+ sb.Append(RenderMaterials.overrides[i].te_index);
+ int len = RenderMaterials.overrides[i].data.Length;
+ sb.Append((byte)(len & 0xff));
+ sb.Append((byte)((len >> 8) & 0xff));
+ sb.Append(RenderMaterials.overrides[i].data);
+ }
+ return OSUTF8Cached.GetArrayAndRelease(sb);
+ }
+
+ public void RenderMaterialsOvrFromRawBin(byte[] data)
+ {
+ if (RenderMaterials is not null && RenderMaterials.overrides is not null)
+ RenderMaterials.overrides = null;
+
+ if (data is null || data.Length < 1)
+ return;
+ int nentries = data[0];
+ if (nentries > 128)
+ return;
+ if (nentries == 0) // for outdated viewer caches
+ {
+ RenderMaterials ??= new Primitive.RenderMaterials();
+ return;
+ }
+
+ int indx = 1;
+ Primitive.RenderMaterials.RenderMaterialOverrideEntry[] overrides = new Primitive.RenderMaterials.RenderMaterialOverrideEntry[nentries];
+ try
+ {
+ for(int i = 0; i < overrides.Length; i++)
+ {
+ overrides[i].te_index = data[indx++];
+ int ovrlen = data[indx++];
+ ovrlen += data[indx++] << 8;
+ overrides[i].data = Utils.BytesToString(data,indx, ovrlen);
+ if(overrides[i].data.StartsWith("{\"asset")) // ignore old test data
+ return;
+ indx += ovrlen;
+ }
+ }
+ catch
+ {
+ return;
+ }
+
+ RenderMaterials ??= new Primitive.RenderMaterials();
+ RenderMaterials.overrides = overrides;
+ }
+
///
/// Encapsulates a list of media entries.
///
@@ -1647,15 +1596,15 @@ public string ToXml()
{
lock (this)
{
- using (StringWriter sw = new StringWriter())
+ using (StringWriter sw = new())
{
- using (XmlTextWriter xtw = new XmlTextWriter(sw))
+ using (XmlTextWriter xtw = new(sw))
{
xtw.WriteStartElement("OSMedia");
xtw.WriteAttributeString("type", MEDIA_TEXTURE_TYPE);
xtw.WriteAttributeString("version", "0.1");
- OSDArray meArray = new OSDArray();
+ OSDArray meArray = new();
foreach (MediaEntry me in this)
{
OSD osd = (null == me ? new OSD() : me.GetOSD());
@@ -1684,7 +1633,7 @@ public void WriteXml(XmlWriter writer)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MediaList FromXml(string rawXml)
{
- MediaList ml = new MediaList();
+ MediaList ml = new();
ml.ReadXml(rawXml);
if(ml.Count == 0)
return null;
@@ -1695,9 +1644,9 @@ public void ReadXml(string rawXml)
{
try
{
- using (StringReader sr = new StringReader(rawXml))
+ using (StringReader sr = new(rawXml))
{
- using (XmlTextReader xtr = new XmlTextReader(sr))
+ using (XmlTextReader xtr = new(sr))
{
xtr.DtdProcessing = DtdProcessing.Ignore;
xtr.MoveToContent();
@@ -1710,10 +1659,9 @@ public void ReadXml(string rawXml)
xtr.ReadStartElement("OSMedia");
OSD osdp = OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
- if(osdp == null || !(osdp is OSDArray))
+ if(osdp is not OSDArray osdMeArray)
return;
- OSDArray osdMeArray = osdp as OSDArray;
if(osdMeArray.Count == 0)
return;
diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs
index 7091f97d6e8..7b51c5ec96f 100644
--- a/OpenSim/Framework/RegionInfo.cs
+++ b/OpenSim/Framework/RegionInfo.cs
@@ -527,7 +527,7 @@ private void ReadNiniConfig(IConfigSource source, string name)
config.Set("Location", location);
}
- string[] locationElements = location.Split(new char[] { ',' });
+ string[] locationElements = location.Split(Util.SplitCommaArray);
RegionLocX = Convert.ToUInt32(locationElements[0]);
RegionLocY = Convert.ToUInt32(locationElements[1]);
@@ -743,7 +743,7 @@ private void DoDefaultLandingSanityChecks()
if (DefaultLandingPoint.Z < 0f)
DefaultLandingPoint.Z = 0f;
- if (ValuesCapped == true)
+ if (ValuesCapped)
m_log.WarnFormat("[RegionInfo]: The default landing location for {0} has been capped to {1}", RegionName, DefaultLandingPoint);
}
@@ -955,12 +955,13 @@ public void UnpackRegionInfoData(OSDMap args)
UInt32.TryParse(args["region_yloc"].AsString(), out locy);
RegionLocY = locy;
}
- if (args.ContainsKey("region_size_x"))
- RegionSizeX = (uint)args["region_size_x"].AsInteger();
- if (args.ContainsKey("region_size_y"))
- RegionSizeY = (uint)args["region_size_y"].AsInteger();
- if (args.ContainsKey("region_size_z"))
- RegionSizeZ = (uint)args["region_size_z"].AsInteger();
+ OSD osdtmp;
+ if (args.TryGetValue("region_size_x", out osdtmp))
+ RegionSizeX = (uint)osdtmp.AsInteger();
+ if (args.TryGetValue("region_size_y", out osdtmp))
+ RegionSizeY = (uint)osdtmp.AsInteger();
+ if (args.TryGetValue("region_size_z", out osdtmp))
+ RegionSizeZ = (uint)osdtmp.AsInteger();
IPAddress ip_addr = null;
if (args["internal_ep_address"] != null)
diff --git a/OpenSim/Framework/RegionSettings.cs b/OpenSim/Framework/RegionSettings.cs
index ff9ae3c35d8..90814f771db 100644
--- a/OpenSim/Framework/RegionSettings.cs
+++ b/OpenSim/Framework/RegionSettings.cs
@@ -49,15 +49,15 @@ public void SetLocation(Vector3 pos, Quaternion rot, Vector3 point)
// Next we need to rotate this vector into the spawn point's
// coordinate system
rot.W = -rot.W;
- offset = offset * rot;
+ offset *= rot;
Vector3 dir = Vector3.Normalize(offset);
// Get the bearing (yaw)
- Yaw = (float)Math.Atan2(dir.Y, dir.X);
+ Yaw = MathF.Atan2(dir.Y, dir.X);
// Get the elevation (pitch)
- Pitch = (float)-Math.Atan2(dir.Z, Math.Sqrt(dir.X * dir.X + dir.Y * dir.Y));
+ Pitch = -MathF.Atan2(dir.Z, MathF.Sqrt(dir.X * dir.X + dir.Y * dir.Y));
}
public Vector3 GetLocation(Vector3 pos, Quaternion rot)
@@ -92,10 +92,12 @@ public static SpawnPoint Parse(string str)
if (parts.Length != 3)
throw new ArgumentException("Invalid string: " + str);
- SpawnPoint sp = new SpawnPoint();
- sp.Yaw = float.Parse(parts[0]);
- sp.Pitch = float.Parse(parts[1]);
- sp.Distance = float.Parse(parts[2]);
+ SpawnPoint sp = new()
+ {
+ Yaw = float.Parse(parts[0]),
+ Pitch = float.Parse(parts[1]),
+ Distance = float.Parse(parts[2])
+ };
return sp;
}
}
@@ -109,15 +111,14 @@ public class RegionSettings
///
/// These appear to be terrain textures that are shipped with the client.
///
- public static readonly UUID DEFAULT_TERRAIN_TEXTURE_1 = new UUID("b8d3965a-ad78-bf43-699b-bff8eca6c975");
- public static readonly UUID DEFAULT_TERRAIN_TEXTURE_2 = new UUID("abb783e6-3e93-26c0-248a-247666855da3");
- public static readonly UUID DEFAULT_TERRAIN_TEXTURE_3 = new UUID("179cdabd-398a-9b6b-1391-4dc333ba321f");
- public static readonly UUID DEFAULT_TERRAIN_TEXTURE_4 = new UUID("beb169c7-11ea-fff2-efe5-0f24dc881df2");
+ public static readonly UUID DEFAULT_TERRAIN_TEXTURE_1 = new("b8d3965a-ad78-bf43-699b-bff8eca6c975");
+ public static readonly UUID DEFAULT_TERRAIN_TEXTURE_2 = new("abb783e6-3e93-26c0-248a-247666855da3");
+ public static readonly UUID DEFAULT_TERRAIN_TEXTURE_3 = new("179cdabd-398a-9b6b-1391-4dc333ba321f");
+ public static readonly UUID DEFAULT_TERRAIN_TEXTURE_4 = new("beb169c7-11ea-fff2-efe5-0f24dc881df2");
public void Save()
{
- if (OnSave != null)
- OnSave(this);
+ OnSave?.Invoke(this);
}
private UUID m_RegionUUID = UUID.Zero;
@@ -287,56 +288,56 @@ public double Elevation1NW
public double Elevation2NW
{
get { return m_Elevation2NW; }
- set { m_Elevation2NW = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation2NW = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_Elevation1NE = 10;
public double Elevation1NE
{
get { return m_Elevation1NE; }
- set { m_Elevation1NE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation1NE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_Elevation2NE = 60;
public double Elevation2NE
{
get { return m_Elevation2NE; }
- set { m_Elevation2NE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation2NE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_Elevation1SE = 10;
public double Elevation1SE
{
get { return m_Elevation1SE; }
- set { m_Elevation1SE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation1SE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_Elevation2SE = 60;
public double Elevation2SE
{
get { return m_Elevation2SE; }
- set { m_Elevation2SE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation2SE = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_Elevation1SW = 10;
public double Elevation1SW
{
get { return m_Elevation1SW; }
- set { m_Elevation1SW = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation1SW = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_Elevation2SW = 60;
public double Elevation2SW
{
get { return m_Elevation2SW; }
- set { m_Elevation2SW = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap); ; }
+ set { m_Elevation2SW = Utils.Clamp(value, Constants.MinTerrainHeightmap, Constants.MaxTerrainHeightmap);}
}
private double m_WaterHeight = 20;
public double WaterHeight
{
get { return m_WaterHeight; }
- set { m_WaterHeight = Utils.Clamp(value, Constants.MinWaterHeight, Constants.MaxWaterHeight); }
+ set { m_WaterHeight = Utils.Clamp(value, Constants.MinWaterHeight, Constants.MaxWaterHeight);}
}
private double m_TerrainRaiseLimit = 100;
@@ -426,7 +427,7 @@ public String LoadedCreationDate
{
get
{
- TimeSpan ts = new TimeSpan(0, 0, LoadedCreationDateTime);
+ TimeSpan ts = new(0, 0, LoadedCreationDateTime);
DateTime stamp = new DateTime(1970, 1, 1) + ts;
return stamp.ToLongDateString();
}
@@ -436,7 +437,7 @@ public String LoadedCreationTime
{
get
{
- TimeSpan ts = new TimeSpan(0, 0, LoadedCreationDateTime);
+ TimeSpan ts = new(0, 0, LoadedCreationDateTime);
DateTime stamp = new DateTime(1970, 1, 1) + ts;
return stamp.ToLongTimeString();
}
@@ -479,7 +480,7 @@ public bool HasTelehub
///
/// Our connected Telehub's SpawnPoints
///
- public List l_SpawnPoints = new List();
+ public List l_SpawnPoints = new();
// Add a SpawnPoint
// ** These are not region coordinates **
diff --git a/OpenSim/Framework/RegionURI.cs b/OpenSim/Framework/RegionURI.cs
index 56bb04416fe..d3e0a8dbc11 100644
--- a/OpenSim/Framework/RegionURI.cs
+++ b/OpenSim/Framework/RegionURI.cs
@@ -32,17 +32,18 @@ namespace OpenSim.Framework
{
public class RegionURI
{
- private static byte[] schemaSep = osUTF8.GetASCIIBytes("://");
- private static byte[] altschemaSep = osUTF8.GetASCIIBytes("|!!");
- private static byte[] nameSep = osUTF8.GetASCIIBytes(":/ ");
- private static byte[] altnameSep = osUTF8.GetASCIIBytes(":/ +|");
- private static byte[] escapePref = osUTF8.GetASCIIBytes("+%");
- private static byte[] altPortSepPref = osUTF8.GetASCIIBytes(":|");
+ private static readonly byte[] schemaSep = osUTF8.GetASCIIBytes("://");
+ private static readonly byte[] altschemaSep = osUTF8.GetASCIIBytes("|!!");
+ private static readonly byte[] nameSep = osUTF8.GetASCIIBytes(":/ ");
+ private static readonly byte[] altnameSep = osUTF8.GetASCIIBytes(":/ +|");
+ private static readonly byte[] escapePref = osUTF8.GetASCIIBytes("+%");
+ private static readonly byte[] altPortSepPref = osUTF8.GetASCIIBytes(":|");
+ private static readonly byte[] forbidonname = osUTF8.GetASCIIBytes(".,:;\\/");
public enum URIFlags : int
{
None = 0,
- Valid = 1 << 0,
+ //Valid = 1 << 0,
HasHost = 1 << 1,
HasResolvedHost = 1 << 2,
HasUserName = 1 << 3,
@@ -70,7 +71,7 @@ public RegionURI(string _originalURI)
{
originalURI = _originalURI;
Parse(_originalURI);
- if (!HasHost)
+ if (!HasHost && HasRegionName)
Flags |= URIFlags.IsLocalGrid;
}
@@ -81,7 +82,10 @@ public RegionURI(string _originalURI, GridInfo gi)
if(!HasHost)
{
- Flags |= URIFlags.IsLocalGrid;
+ if(!HasRegionName)
+ Flags = URIFlags.None;
+ else
+ Flags |= URIFlags.IsLocalGrid;
return;
}
if(gi == null)
@@ -290,6 +294,12 @@ public void Parse(string inputURI)
if (tmpSlice.Length <= 0)
return;
+ if(tmpSlice.IndexOfAny(forbidonname) > 0)
+ {
+ Flags = URIFlags.None;
+ return;
+ }
+
RegionName = tmpSlice.ToString();
Flags |= URIFlags.HasRegionName;
diff --git a/OpenSim/Framework/RegistryCore.cs b/OpenSim/Framework/RegistryCore.cs
index 98d595a847d..d5e13bbde7b 100644
--- a/OpenSim/Framework/RegistryCore.cs
+++ b/OpenSim/Framework/RegistryCore.cs
@@ -53,9 +53,9 @@ public void RegisterInterface(T iface)
public bool TryGet(out T iface)
{
- if (m_moduleInterfaces.ContainsKey(typeof(T)))
+ if (m_moduleInterfaces.TryGetValue(typeof(T), out object o))
{
- iface = (T)m_moduleInterfaces[typeof(T)];
+ iface = (T)o;
return true;
}
iface = default(T);
diff --git a/OpenSim/Framework/RestClient.cs b/OpenSim/Framework/RestClient.cs
index 4c0d9031f1f..b79f0c76a0b 100644
--- a/OpenSim/Framework/RestClient.cs
+++ b/OpenSim/Framework/RestClient.cs
@@ -29,9 +29,10 @@
using System.Collections.Generic;
using System.IO;
using System.Net;
+using System.Net.Http;
using System.Reflection;
+using System.Runtime.CompilerServices;
using System.Text;
-using System.Threading;
using System.Web;
using log4net;
@@ -44,17 +45,6 @@ namespace OpenSim.Framework
///
///
/// This class is a generic implementation of a REST (Representational State Transfer) web service. This
- /// class is designed to execute both synchronously and asynchronously.
- ///
- /// Internally the implementation works as a two stage asynchronous web-client.
- /// When the request is initiated, RestClient will query asynchronously for for a web-response,
- /// sleeping until the initial response is returned by the server. Once the initial response is retrieved
- /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response
- /// object into a memorystream as a sequence of asynchronous reads.
- ///
- /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
- /// 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 : IDisposable
{
@@ -67,17 +57,17 @@ public class RestClient : IDisposable
///
/// The base Uri of the web-service e.g. http://www.google.com
///
- private string _url;
+ private readonly string _url;
///
/// Path elements of the query
///
- private List _pathElements = new List();
+ private readonly List _pathElements = new();
///
/// Parameter elements of the query, e.g. min=34
///
- private Dictionary _parameterElements = new Dictionary();
+ private readonly Dictionary _parameterElements = new();
///
/// Request method. E.g. GET, POST, PUT or DELETE
@@ -87,44 +77,23 @@ public class RestClient : IDisposable
///
/// Temporary buffer used to store bytes temporarily as they come in from the server
///
- private byte[] _readbuf;
+ private readonly byte[] _readbuf;
///
/// MemoryStream representing the resulting resource
///
- private MemoryStream _resource;
-
- ///
- /// WebRequest object, held as a member variable
- ///
- private HttpWebRequest _request;
-
- ///
- /// WebResponse object, held as a member variable, so we can close it
- ///
- private HttpWebResponse _response;
-
- ///
- /// This flag will help block the main synchroneous method, in case we run in synchroneous mode
- ///
- //public static ManualResetEvent _allDone = new ManualResetEvent(false);
+ private readonly MemoryStream _resource;
///
/// Default time out period
///
- //private const int DefaultTimeout = 10*1000; // 10 seconds timeout
+ private const int DefaultTimeout = 90000; // 90 seconds timeout
///
/// Default Buffer size of a block requested from the web-server
///
private const int BufferSize = 4 * 4096; // Read blocks of 4 * 4 KB.
- ///
- /// if an exception occours during async processing, we need to save it, so it can be
- /// rethrown on the primary thread;
- ///
- private Exception _asyncException;
-
#endregion member variables
#region constructors
@@ -138,12 +107,10 @@ public RestClient(string url)
_url = url;
_readbuf = new byte[BufferSize];
_resource = new MemoryStream();
- _request = null;
- _response = null;
_lock = new object();
}
- private object _lock;
+ private readonly object _lock;
#endregion constructors
@@ -239,12 +206,12 @@ public string RequestMethod
/// fully constructed Uri
private Uri buildUri()
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
sb.Append(_url);
foreach (string e in _pathElements)
{
- sb.Append("/");
+ sb.Append('/');
sb.Append(e);
}
@@ -253,16 +220,16 @@ private Uri buildUri()
{
if (firstElement)
{
- sb.Append("?");
+ sb.Append('?');
firstElement = false;
}
else
- sb.Append("&");
+ sb.Append('&');
sb.Append(kv.Key);
if (!string.IsNullOrEmpty(kv.Value))
{
- sb.Append("=");
+ sb.Append('=');
sb.Append(kv.Value);
}
}
@@ -271,47 +238,10 @@ private Uri buildUri()
return new Uri(sb.ToString());
}
- #region Async communications with server
-
- ///
- /// Async method, invoked when a block of data has been received from the service
- ///
- ///
- private void StreamIsReadyDelegate(IAsyncResult ar)
- {
- try
- {
- Stream s = (Stream) ar.AsyncState;
- int read = s.EndRead(ar);
-
- if (read > 0)
- {
- _resource.Write(_readbuf, 0, read);
- // IAsyncResult asynchronousResult =
- // s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
- s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
-
- // TODO! Implement timeout, without killing the server
- //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
- }
- else
- {
- s.Close();
- //_allDone.Set();
- }
- }
- catch (Exception e)
- {
- //_allDone.Set();
- _asyncException = e;
- }
- }
-
- #endregion Async communications with server
-
///
/// Perform a synchronous request
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryStream Request()
{
return Request(null);
@@ -324,53 +254,78 @@ public MemoryStream Request(IServiceAuth auth)
{
lock (_lock)
{
+ Uri uri = null;
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
try
{
- _request = (HttpWebRequest) WebRequest.Create(buildUri());
- _request.ContentType = "application/xml";
- _request.Timeout = 90000;
- _request.Method = RequestMethod;
- _asyncException = null;
- if (auth != null)
- auth.AddAuthorization(_request.Headers);
- else
- _request.AllowWriteStreamBuffering = false;
+ client = WebUtil.GetNewGlobalHttpClient(DefaultTimeout);
+ uri = buildUri();
+ request = new(new HttpMethod(RequestMethod), uri);
+
+ auth?.AddAuthorization(request.Headers);
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
+
+ //if (keepalive)
+ {
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
+ }
+ //else
+ // request.Headers.TryAddWithoutValidation("Connection", "close");
+
if (WebUtil.DebugLevel >= 3)
- m_log.DebugFormat("[REST CLIENT] {0} to {1}", _request.Method, _request.RequestUri);
+ m_log.DebugFormat("[REST CLIENT] {0} to {1}", RequestMethod, uri);
+
+ //_request.ContentType = "application/xml";
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+ responseMessage.EnsureSuccessStatusCode();
- using (_response = (HttpWebResponse) _request.GetResponse())
+ Stream respStream = responseMessage.Content.ReadAsStream();
+ int length = respStream.Read(_readbuf, 0, BufferSize);
+ while (length > 0)
{
- using (Stream src = _response.GetResponseStream())
- {
- int length = src.Read(_readbuf, 0, BufferSize);
- while (length > 0)
- {
- _resource.Write(_readbuf, 0, length);
- length = src.Read(_readbuf, 0, BufferSize);
- }
- }
+ _resource.Write(_readbuf, 0, length);
+ length = respStream.Read(_readbuf, 0, BufferSize);
}
}
- catch (WebException e)
+ catch (HttpRequestException e)
{
- using (HttpWebResponse errorResponse = e.Response as HttpWebResponse)
+ if(uri is not null)
{
- if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
+ if (e.StatusCode is HttpStatusCode status)
{
- // This is often benign. E.g., requesting a missing asset will return 404.
- m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString());
+ if (status == HttpStatusCode.NotFound)
+ {
+ // This is often benign. E.g., requesting a missing asset will return 404.
+ m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", uri.ToString());
+ }
+ else
+ {
+ m_log.Error($"[REST CLIENT] Error fetching resource from server: {uri} status: {status} {e.Message}");
+ }
}
else
{
- m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e);
+ m_log.Error($"[REST CLIENT] Error fetching resource from server: {uri} {e.Message}");
}
}
+ else
+ {
+ m_log.Error($"[REST CLIENT] Error fetching null resource from server: {e.Message}");
+ }
return null;
}
-
- if (_asyncException != null)
- throw _asyncException;
+ finally
+ {
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
+ }
if (_resource != null)
{
@@ -388,216 +343,64 @@ public MemoryStream Request(IServiceAuth auth)
// just sync post data, ignoring result
public void POSTRequest(byte[] src, IServiceAuth auth)
{
+ Uri uri = null;
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
try
{
- _request = (HttpWebRequest)WebRequest.Create(buildUri());
- _request.ContentType = "application/xml";
- _request.Timeout = 90000;
- _request.Method = "POST";
- _asyncException = null;
- _request.ContentLength = src.Length;
- if (auth != null)
- auth.AddAuthorization(_request.Headers);
- else
- _request.AllowWriteStreamBuffering = false;
- }
- catch (Exception e)
- {
- m_log.WarnFormat("[REST]: POST {0} failed with exception {1} {2}",
- _request.RequestUri, e.Message, e.StackTrace);
- return;
- }
+ client = WebUtil.GetNewGlobalHttpClient(DefaultTimeout);
+ uri = buildUri();
+ request = new(HttpMethod.Post, uri);
- try
- {
- using (Stream dst = _request.GetRequestStream())
- {
- dst.Write(src, 0, src.Length);
- }
+ auth?.AddAuthorization(request.Headers);
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
- using(HttpWebResponse response = (HttpWebResponse)_request.GetResponse())
+ //if (keepalive)
{
- using (Stream responseStream = response.GetResponseStream())
- {
- using (StreamReader reader = new StreamReader(responseStream))
- {
- string responseStr = reader.ReadToEnd();
- if (WebUtil.DebugLevel >= 5)
- {
- int reqnum = WebUtil.RequestNumber++;
- WebUtil.LogOutgoingDetail("REST POST", responseStr);
- }
- }
- }
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
}
+ //else
+ // request.Headers.TryAddWithoutValidation("Connection", "close");
+
+ request.Content = new ByteArrayContent(src);
+ request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/xml");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", src.Length.ToString());
+
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseContentRead);
+ responseMessage.EnsureSuccessStatusCode();
}
- catch (WebException e)
+ catch (HttpRequestException e)
{
- m_log.WarnFormat("[REST]: POST {0} failed with status {1} and message {2}",
- _request.RequestUri, e.Status, e.Message);
+ if(uri is not null)
+ {
+ if (e.StatusCode is HttpStatusCode status)
+ m_log.Warn($"[REST]: POST {uri} failed with status {status} and message {e.Message}");
+ else
+ m_log.Warn($"[REST]: POST {uri} failed with message {e.Message}");
+ }
+ else
+ m_log.Warn($"[REST]: POST failed {e.Message}");
return;
}
catch (Exception e)
{
- m_log.WarnFormat("[REST]: AsyncPOST {0} failed with exception {1} {2}",
- _request.RequestUri, e.Message, e.StackTrace);
+ if (uri is not null)
+ m_log.Warn($"[REST]: POST {uri} failed with message {e.Message}");
+ else
+ m_log.Warn($"[REST]: POST failed {e.Message}");
return;
}
- }
-
- }
-
- internal class SimpleAsyncResult : IAsyncResult
- {
- private readonly AsyncCallback m_callback;
-
- ///
- /// Is process completed?
- ///
- /// Should really be boolean, but VolatileRead has no boolean method
- private byte m_completed;
-
- ///
- /// Did process complete synchronously?
- ///
- /// I have a hard time imagining a scenario where this is the case, again, same issue about
- /// booleans and VolatileRead as m_completed
- ///
- private byte m_completedSynchronously;
-
- private readonly object m_asyncState;
- private ManualResetEvent m_waitHandle;
- private Exception m_exception;
-
- internal SimpleAsyncResult(AsyncCallback cb, object state)
- {
- m_callback = cb;
- m_asyncState = state;
- m_completed = 0;
- m_completedSynchronously = 1;
- }
-
- #region IAsyncResult Members
-
- public object AsyncState
- {
- get { return m_asyncState; }
- }
-
- public WaitHandle AsyncWaitHandle
- {
- get
+ finally
{
- if (m_waitHandle == null)
- {
- bool done = IsCompleted;
- ManualResetEvent mre = new ManualResetEvent(done);
- if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
- {
- mre.Close();
- }
- else
- {
- if (!done && IsCompleted)
- {
- m_waitHandle.Set();
- }
- }
- }
-
- return m_waitHandle;
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
}
}
-
- public bool CompletedSynchronously
- {
- get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
- }
-
-
- public bool IsCompleted
- {
- get { return Thread.VolatileRead(ref m_completed) == 1; }
- }
-
- #endregion
-
- #region class Methods
-
- internal void SetAsCompleted(bool completedSynchronously)
- {
- m_completed = 1;
- if (completedSynchronously)
- m_completedSynchronously = 1;
- else
- m_completedSynchronously = 0;
-
- SignalCompletion();
- }
-
- internal void HandleException(Exception e, bool completedSynchronously)
- {
- m_completed = 1;
- if (completedSynchronously)
- m_completedSynchronously = 1;
- else
- m_completedSynchronously = 0;
- m_exception = e;
-
- SignalCompletion();
- }
-
- private void SignalCompletion()
- {
- if (m_waitHandle != null) m_waitHandle.Set();
-
- if (m_callback != null) m_callback(this);
- }
-
- public void EndInvoke()
- {
- // This method assumes that only 1 thread calls EndInvoke
- if (!IsCompleted)
- {
- // If the operation isn't done, wait for it
- AsyncWaitHandle.WaitOne();
- AsyncWaitHandle.Close();
- m_waitHandle.Close();
- m_waitHandle = null; // Allow early GC
- }
-
- // Operation is done: if an exception occured, throw it
- if (m_exception != null) throw m_exception;
- }
-
- #endregion
- }
-
- internal class AsyncResult : SimpleAsyncResult
- {
- private T m_result = default(T);
-
- public AsyncResult(AsyncCallback asyncCallback, Object state) :
- base(asyncCallback, state)
- {
- }
-
- public void SetAsCompleted(T result, bool completedSynchronously)
- {
- // Save the asynchronous operation's result
- m_result = result;
-
- // Tell the base class that the operation completed
- // sucessfully (no exception)
- base.SetAsCompleted(completedSynchronously);
- }
-
- public new T EndInvoke()
- {
- base.EndInvoke();
- return m_result;
- }
}
-
}
diff --git a/OpenSim/Framework/SLUtil.cs b/OpenSim/Framework/SLUtil.cs
index fd539a3e420..d824bbdf2f9 100644
--- a/OpenSim/Framework/SLUtil.cs
+++ b/OpenSim/Framework/SLUtil.cs
@@ -27,23 +27,21 @@
using OpenMetaverse;
using System;
+using System.Collections.Frozen;
using System.Collections.Generic;
using System.Globalization;
+using System.Runtime.CompilerServices;
namespace OpenSim.Framework
{
public static class SLUtil
{
-// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+ //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
///
/// Asset types used only in OpenSim.
/// To avoid clashing with the code numbers used in Second Life, use only negative numbers here.
///
- public enum OpenSimAssetType : sbyte
- {
- Material = -2
- }
#region SL / file extension / content-type conversions
@@ -55,81 +53,48 @@ public static object AssetTypeFromCode(sbyte assetType)
{
if (Enum.IsDefined(typeof(OpenMetaverse.AssetType), assetType))
return (OpenMetaverse.AssetType)assetType;
- else if (Enum.IsDefined(typeof(OpenSimAssetType), assetType))
- return (OpenSimAssetType)assetType;
else
return OpenMetaverse.AssetType.Unknown;
}
- private class TypeMapping
+ private struct TypeMapping
{
- private sbyte assetType;
- private sbyte inventoryType;
- private string contentType;
- private string contentType2;
- private string extension;
-
- public sbyte AssetTypeCode
- {
- get { return assetType; }
- }
-
- public object AssetType
- {
- get { return AssetTypeFromCode(assetType); }
- }
-
- public sbyte InventoryType
- {
- get { return inventoryType; }
- }
-
- public string ContentType
- {
- get { return contentType; }
- }
-
- public string ContentType2
- {
- get { return contentType2; }
- }
-
- public string Extension
- {
- get { return extension; }
- }
+ public readonly sbyte AssetType;
+ public readonly sbyte InventoryType;
+ public readonly string ContentType;
+ public readonly string ContentType2;
+ public readonly string Extension;
private TypeMapping(sbyte assetType, sbyte inventoryType, string contentType, string contentType2, string extension)
{
- this.assetType = assetType;
- this.inventoryType = inventoryType;
- this.contentType = contentType;
- this.contentType2 = contentType2;
- this.extension = extension;
+ AssetType = assetType;
+ InventoryType = inventoryType;
+ ContentType = contentType;
+ ContentType2 = contentType2;
+ Extension = extension;
}
public TypeMapping(AssetType assetType, sbyte inventoryType, string contentType, string contentType2, string extension)
- : this((sbyte)assetType, inventoryType, contentType, contentType2, extension)
{
+ AssetType = (sbyte)assetType;
+ InventoryType = inventoryType;
+ ContentType = contentType;
+ ContentType2 = contentType2;
+ Extension = extension;
}
public TypeMapping(AssetType assetType, InventoryType inventoryType, string contentType, string contentType2, string extension)
- : this((sbyte)assetType, (sbyte)inventoryType, contentType, contentType2, extension)
+ : this(assetType, (sbyte)inventoryType, contentType, contentType2, extension)
{
}
public TypeMapping(AssetType assetType, InventoryType inventoryType, string contentType, string extension)
- : this((sbyte)assetType, (sbyte)inventoryType, contentType, null, extension)
+ : this(assetType, (sbyte)inventoryType, contentType, null, extension)
{
}
public TypeMapping(AssetType assetType, FolderType inventoryType, string contentType, string extension)
- : this((sbyte)assetType, (sbyte)inventoryType, contentType, null, extension)
- {
- }
-
- public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, string contentType, string extension)
- : this((sbyte)assetType, (sbyte)inventoryType, contentType, null, extension)
+ : this(assetType, (sbyte)inventoryType, contentType, null, extension)
{
}
}
@@ -140,7 +105,7 @@ public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, stri
/// AssetType "AssetType.Texture" -> Content-Type "image-xj2c"
/// Content-Type "image/x-j2c" -> InventoryType "InventoryType.Texture"
///
- private static TypeMapping[] MAPPINGS = new TypeMapping[] {
+ private static TypeMapping[] MAPPINGS = [
new TypeMapping(AssetType.Unknown, InventoryType.Unknown, "application/octet-stream", "bin"),
new TypeMapping(AssetType.Texture, InventoryType.Texture, "image/x-j2c", "image/jp2", "j2c"),
new TypeMapping(AssetType.Texture, InventoryType.Snapshot, "image/x-j2c", "image/jp2", "j2c"),
@@ -183,15 +148,15 @@ public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, stri
new TypeMapping(AssetType.Folder, InventoryType.Folder, "application/vnd.ll.folder", "folder"),
// OpenSim specific
- new TypeMapping(OpenSimAssetType.Material, InventoryType.Unknown, "application/llsd+xml", "material")
- };
-
- private static Dictionary asset2Content;
- private static Dictionary asset2Extension;
- private static Dictionary inventory2Content;
- private static Dictionary content2Asset;
- private static Dictionary content2Inventory;
- private static Dictionary name2Asset = new Dictionary()
+ new TypeMapping(AssetType.OSMaterial, InventoryType.Unknown, "application/llsd+xml", "material")
+ ];
+
+ private static readonly FrozenDictionary asset2Content;
+ private static readonly FrozenDictionary asset2Extension;
+ private static readonly FrozenDictionary inventory2Content;
+ private static readonly FrozenDictionary content2Asset;
+ private static readonly FrozenDictionary content2Inventory;
+ private static readonly FrozenDictionary name2Asset = new Dictionary()
{
{"texture", AssetType.Texture },
{"sound", AssetType.Sound},
@@ -215,8 +180,9 @@ public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, stri
{"mesh", AssetType.Mesh},
{"settings", AssetType.Settings},
{"material", AssetType.Material}
- };
- private static Dictionary name2Inventory = new Dictionary()
+ }.ToFrozenDictionary();
+
+ private static readonly FrozenDictionary name2Inventory = new Dictionary()
{
{"texture", FolderType.Texture},
{"sound", FolderType.Sound},
@@ -242,108 +208,94 @@ public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, stri
{"settings", FolderType.Settings},
{"material", FolderType.Material},
{"suitcase", FolderType.Suitcase}
- };
+ }.ToFrozenDictionary();
static SLUtil()
{
- asset2Content = new Dictionary();
- asset2Extension = new Dictionary();
- inventory2Content = new Dictionary();
- content2Asset = new Dictionary();
- content2Inventory = new Dictionary();
+ Dictionary asset2Contentd = [];
+ Dictionary asset2Extensiond = [];
+ Dictionary inventory2Contentd = [];
+ Dictionary content2Assetd = [];
+ Dictionary content2Inventoryd = [];
foreach (TypeMapping mapping in MAPPINGS)
{
- sbyte assetType = mapping.AssetTypeCode;
- if (!asset2Content.ContainsKey(assetType))
- asset2Content.Add(assetType, mapping.ContentType);
-
- if (!asset2Extension.ContainsKey(assetType))
- asset2Extension.Add(assetType, mapping.Extension);
+ sbyte assetType = mapping.AssetType;
+ asset2Contentd.TryAdd(assetType, mapping.ContentType);
+ asset2Extensiond.TryAdd(assetType, mapping.Extension);
- if (!inventory2Content.ContainsKey(mapping.InventoryType))
- inventory2Content.Add(mapping.InventoryType, mapping.ContentType);
+ inventory2Contentd.TryAdd(mapping.InventoryType, mapping.ContentType);
- if (!content2Asset.ContainsKey(mapping.ContentType))
- content2Asset.Add(mapping.ContentType, assetType);
+ content2Assetd.TryAdd(mapping.ContentType, assetType);
- if (!content2Inventory.ContainsKey(mapping.ContentType))
- content2Inventory.Add(mapping.ContentType, mapping.InventoryType);
+ content2Inventoryd.TryAdd(mapping.ContentType, mapping.InventoryType);
if (mapping.ContentType2 != null)
{
- if (!content2Asset.ContainsKey(mapping.ContentType2))
- content2Asset.Add(mapping.ContentType2, assetType);
- if (!content2Inventory.ContainsKey(mapping.ContentType2))
- content2Inventory.Add(mapping.ContentType2, mapping.InventoryType);
+ content2Assetd.TryAdd(mapping.ContentType2, assetType);
+ content2Inventoryd.TryAdd(mapping.ContentType2, mapping.InventoryType);
}
}
+ asset2Content = asset2Contentd.ToFrozenDictionary();
+ asset2Extension = asset2Extensiond.ToFrozenDictionary();
+ inventory2Content = inventory2Contentd.ToFrozenDictionary();
+ content2Asset = content2Assetd.ToFrozenDictionary();
+ content2Inventory = content2Inventoryd.ToFrozenDictionary();
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static AssetType SLAssetName2Type(string name)
{
- if (name2Asset.TryGetValue(name, out AssetType type))
- return type;
- return AssetType.Unknown;
+ return name2Asset.TryGetValue(name, out AssetType type) ? type : AssetType.Unknown;
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FolderType SLInvName2Type(string name)
{
- if (name2Inventory.TryGetValue(name, out FolderType type))
- return type;
- return FolderType.None;
+ return name2Inventory.TryGetValue(name, out FolderType type) ? type : FolderType.None;
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string SLAssetTypeToContentType(int assetType)
{
- string contentType;
- if (!asset2Content.TryGetValue((sbyte)assetType, out contentType))
- contentType = asset2Content[(sbyte)AssetType.Unknown];
- return contentType;
+ return asset2Content.TryGetValue((sbyte)assetType, out string contentType) ? contentType : asset2Content[(sbyte)AssetType.Unknown];
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string SLInvTypeToContentType(int invType)
{
- string contentType;
- if (!inventory2Content.TryGetValue((sbyte)invType, out contentType))
- contentType = inventory2Content[(sbyte)InventoryType.Unknown];
- return contentType;
+ return inventory2Content.TryGetValue((sbyte)invType, out string contentType) ? contentType : inventory2Content[(sbyte)InventoryType.Unknown];
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static sbyte ContentTypeToSLAssetType(string contentType)
{
- sbyte assetType;
- if (!content2Asset.TryGetValue(contentType, out assetType))
- assetType = (sbyte)AssetType.Unknown;
- return (sbyte)assetType;
+ return content2Asset.TryGetValue(contentType, out sbyte assetType) ? assetType : (sbyte)AssetType.Unknown;
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static sbyte ContentTypeToSLInvType(string contentType)
{
- sbyte invType;
- if (!content2Inventory.TryGetValue(contentType, out invType))
- invType = (sbyte)InventoryType.Unknown;
- return (sbyte)invType;
+ return content2Inventory.TryGetValue(contentType, out sbyte invType) ? invType : (sbyte)InventoryType.Unknown;
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string SLAssetTypeToExtension(int assetType)
{
- string extension;
- if (!asset2Extension.TryGetValue((sbyte)assetType, out extension))
- extension = asset2Extension[(sbyte)AssetType.Unknown];
- return extension;
+ return asset2Extension.TryGetValue((sbyte)assetType, out string extension) ? extension : asset2Extension[(sbyte)AssetType.Unknown];
}
#endregion SL / file extension / content-type conversions
- static char[] seps = new char[] { '\t', '\n' };
- static char[] stringseps = new char[] { '|', '\n' };
+ static readonly char[] seps = new char[] { '\t', '\n' };
+ static readonly char[] stringseps = new char[] { '|', '\n' };
static byte[] moronize = new byte[16]
{
60, 17, 94, 81, 4, 244, 82, 60, 159, 166, 152, 175, 241, 3, 71, 48
};
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
static int getField(string note, int start, string name, bool isString, out string value)
{
value = String.Empty;
@@ -615,8 +567,8 @@ public static List GetEmbeddedAssetIDs(byte[] data)
if(indx > 0)
{
indx += 14;
- List textIDs = Util.GetUUIDsOnString(ref note, indx, note.Length - indx);
- if(textIDs.Count > 0)
+ List textIDs = Util.GetUUIDsOnString(note.AsSpan(indx, note.Length - indx));
+ if (textIDs.Count > 0)
ids.AddRange(textIDs);
}
if (ids.Count == 0)
diff --git a/OpenSim/Framework/Serialization/ArchiveConstants.cs b/OpenSim/Framework/Serialization/ArchiveConstants.cs
index 8715d0196d6..245bc0bf286 100644
--- a/OpenSim/Framework/Serialization/ArchiveConstants.cs
+++ b/OpenSim/Framework/Serialization/ArchiveConstants.cs
@@ -29,7 +29,6 @@
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
-using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
namespace OpenSim.Framework.Serialization
{
@@ -96,7 +95,7 @@ public class ArchiveConstants
///
/// Template used for creating filenames in OpenSim Archives.
///
- public const string OAR_OBJECT_FILENAME_TEMPLATE = "{0}_{1:000}-{2:000}-{3:000}__{4}.xml";
+ public const string OAR_OBJECT_FILENAME_TEMPLATE = "{0}_{1:#000}-{2:#000}-{3:#000}__{4}.xml";
///
/// Extensions used for asset types in the archive
@@ -125,7 +124,7 @@ static ArchiveConstants()
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV] = ASSET_EXTENSION_SEPARATOR + "sound.wav";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Texture] = ASSET_EXTENSION_SEPARATOR + "texture.jp2";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TextureTGA] = ASSET_EXTENSION_SEPARATOR + "texture.tga";
- ASSET_TYPE_TO_EXTENSION[(sbyte)OpenSimAssetType.Material] = ASSET_EXTENSION_SEPARATOR + "material.xml";
+ ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.OSMaterial] = ASSET_EXTENSION_SEPARATOR + "material.xml";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Settings] = ASSET_EXTENSION_SEPARATOR + "settings.bin";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Material] = ASSET_EXTENSION_SEPARATOR + "prmat.dat";
@@ -148,14 +147,14 @@ static ArchiveConstants()
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "sound.wav"] = (sbyte)AssetType.SoundWAV;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.jp2"] = (sbyte)AssetType.Texture;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"] = (sbyte)AssetType.TextureTGA;
- EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "material.xml"] = (sbyte)OpenSimAssetType.Material;
+ EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "material.xml"] = (sbyte)AssetType.OSMaterial;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "settings.bin"] = (sbyte)AssetType.Settings;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "prmat.dat"] = (sbyte)AssetType.Material;
}
public static string CreateOarLandDataPath(LandData ld)
{
- return string.Format("{0}{1}.xml", ArchiveConstants.LANDDATA_PATH, ld.GlobalID);
+ return $"{ArchiveConstants.LANDDATA_PATH}{ld.GlobalID}.xml";
}
///
@@ -169,7 +168,7 @@ public static string CreateOarObjectFilename(string objectName, UUID uuid, Vecto
{
return string.Format(
OAR_OBJECT_FILENAME_TEMPLATE, objectName,
- Math.Round(pos.X), Math.Round(pos.Y), Math.Round(pos.Z),
+ MathF.Round(pos.X), MathF.Round(pos.Y), MathF.Round(pos.Z),
uuid);
}
@@ -192,7 +191,7 @@ public static string CreateOarObjectPath(string objectName, UUID uuid, Vector3 p
///
public static string ExtractPlainPathFromIarPath(string iarPath)
{
- List plainDirs = new List();
+ List plainDirs = new();
string[] iarDirs = iarPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
diff --git a/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs b/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs
index 423c1dc75ef..7aa8b1ae1e6 100644
--- a/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs
+++ b/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs
@@ -222,7 +222,7 @@ public static string RewriteSOP(string xmlData, string sceneName, string homeURL
using (StringWriter sw = new StringWriter())
using (XmlTextWriter writer = new XmlTextWriter(sw))
using (XmlTextReader wrappedReader = new XmlTextReader(xmlData, XmlNodeType.Element, null))
- using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment, DtdProcessing = DtdProcessing.Ignore}))
+ using (XmlReader reader = XmlReader.Create(wrappedReader, Util.SharedXmlReaderSettings))
{
TransformXml(reader, writer, sceneName, homeURL, userService, scopeID);
diff --git a/OpenSim/Framework/Serialization/OpenSim.Framework.Serialization.csproj b/OpenSim/Framework/Serialization/OpenSim.Framework.Serialization.csproj
index 8260c678602..ed01cd433fd 100644
--- a/OpenSim/Framework/Serialization/OpenSim.Framework.Serialization.csproj
+++ b/OpenSim/Framework/Serialization/OpenSim.Framework.Serialization.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Framework.Serialization
http://opensimulator.org
OpenSim
diff --git a/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs b/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs
deleted file mode 100644
index e81cb78cfd2..00000000000
--- a/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using NUnit.Framework;
-using OpenSim.Framework;
-using OpenSim.Framework.Serialization.External;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Serialization.Tests
-{
- [TestFixture]
- public class LandDataSerializerTest : OpenSimTestCase
- {
- private LandData land;
- private LandData landWithParcelAccessList;
-
-// private static string preSerialized = "\n\n 128\n 0\n 00000000-0000-0000-0000-000000000000\n 10\n 0\n 0\n 54ff9641-dd40-4a2c-b1f1-47dd3af24e50\n d740204e-bbbf-44aa-949d-02c7d739f6a5\n False\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n land data to test LandDataSerializer\n 536870944\n 2\n LandDataSerializerTest Land\n 0\n 0\n 1\n d4452578-2f25-4b97-a81b-819af559cfd7\n http://videos.opensimulator.org/bumblebee.mp4\n \n 1b8eedf9-6d15-448b-8015-24286f1756bf\n \n 0\n 0\n 0\n 00000000-0000-0000-0000-000000000000\n <0, 0, 0>\n <0, 0, 0>\n 0\n 0\n";
- private static string preSerializedWithParcelAccessList
- = "\n\n 128\n 0\n 00000000-0000-0000-0000-000000000000\n 10\n 0\n 0\n 54ff9641-dd40-4a2c-b1f1-47dd3af24e50\n d740204e-bbbf-44aa-949d-02c7d739f6a5\n False\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n land data to test LandDataSerializer\n 536870944\n 2\n LandDataSerializerTest Land\n 0\n 0\n 1\n d4452578-2f25-4b97-a81b-819af559cfd7\n http://videos.opensimulator.org/bumblebee.mp4\n \n 1b8eedf9-6d15-448b-8015-24286f1756bf\n \n \n 62d65d45-c91a-4f77-862c-46557d978b6c\n \n 2\n \n \n ec2a8d18-2378-4fe0-8b68-2a31b57c481e\n \n 1\n \n \n 0\n 0\n 0\n 00000000-0000-0000-0000-000000000000\n <0, 0, 0>\n <0, 0, 0>\n 0\n 0\n";
-
- [SetUp]
- public void setup()
- {
- // setup LandData object
- this.land = new LandData();
- this.land.AABBMax = new Vector3(1, 2, 3);
- this.land.AABBMin = new Vector3(129, 130, 131);
- this.land.Area = 128;
- this.land.AuctionID = 4;
- this.land.AuthBuyerID = new UUID("7176df0c-6c50-45db-8a37-5e78be56a0cd");
- this.land.Category = ParcelCategory.Residential;
- this.land.ClaimDate = 1;
- this.land.ClaimPrice = 2;
- this.land.GlobalID = new UUID("54ff9641-dd40-4a2c-b1f1-47dd3af24e50");
- this.land.GroupID = new UUID("d740204e-bbbf-44aa-949d-02c7d739f6a5");
- this.land.Description = "land data to test LandDataSerializer";
- this.land.Flags = (uint)(ParcelFlags.AllowDamage | ParcelFlags.AllowVoiceChat);
- this.land.LandingType = (byte)LandingType.Direct;
- this.land.Name = "LandDataSerializerTest Land";
- this.land.Status = ParcelStatus.Leased;
- this.land.LocalID = 1;
- this.land.MediaAutoScale = (byte)0x01;
- this.land.MediaID = new UUID("d4452578-2f25-4b97-a81b-819af559cfd7");
- this.land.MediaURL = "http://videos.opensimulator.org/bumblebee.mp4";
- this.land.OwnerID = new UUID("1b8eedf9-6d15-448b-8015-24286f1756bf");
-
- this.landWithParcelAccessList = this.land.Copy();
- this.landWithParcelAccessList.ParcelAccessList.Clear();
-
- LandAccessEntry pae0 = new LandAccessEntry();
- pae0.AgentID = new UUID("62d65d45-c91a-4f77-862c-46557d978b6c");
- pae0.Flags = AccessList.Ban;
- pae0.Expires = 0;
- this.landWithParcelAccessList.ParcelAccessList.Add(pae0);
-
- LandAccessEntry pae1 = new LandAccessEntry();
- pae1.AgentID = new UUID("ec2a8d18-2378-4fe0-8b68-2a31b57c481e");
- pae1.Flags = AccessList.Access;
- pae1.Expires = 0;
- this.landWithParcelAccessList.ParcelAccessList.Add(pae1);
- }
-
- ///
- /// Test the LandDataSerializer.Serialize() method
- ///
-// [Test]
-// public void LandDataSerializerSerializeTest()
-// {
-// TestHelpers.InMethod();
-//
-// string serialized = LandDataSerializer.Serialize(this.land).Replace("\r\n", "\n");
-// Assert.That(serialized.Length > 0, "Serialize(LandData) returned empty string");
-//
-// // adding a simple boolean variable because resharper nUnit integration doesn't like this
-// // XML data in the Assert.That statement. Not sure why.
-// bool result = (serialized == preSerialized);
-// Assert.That(result, "result of Serialize LandData does not match expected result");
-//
-// string serializedWithParcelAccessList = LandDataSerializer.Serialize(this.landWithParcelAccessList).Replace("\r\n", "\n");
-// Assert.That(serializedWithParcelAccessList.Length > 0,
-// "Serialize(LandData) returned empty string for LandData object with ParcelAccessList");
-// result = (serializedWithParcelAccessList == preSerializedWithParcelAccessList);
-// Assert.That(result,
-// "result of Serialize(LandData) does not match expected result (pre-serialized with parcel access list");
-// }
-
- ///
- /// Test the LandDataSerializer.Deserialize() method
- ///
- [Test]
- public void TestLandDataDeserializeNoAccessLists()
- {
- TestHelpers.InMethod();
-// log4net.Config.XmlConfigurator.Configure();
-
- Dictionary options = new Dictionary();
- LandData ld = LandDataSerializer.Deserialize(LandDataSerializer.Serialize(this.land, options));
- Assert.That(ld, Is.Not.Null, "Deserialize(string) returned null");
-// Assert.That(ld.AABBMax, Is.EqualTo(land.AABBMax));
-// Assert.That(ld.AABBMin, Is.EqualTo(land.AABBMin));
- Assert.That(ld.Area, Is.EqualTo(land.Area));
- Assert.That(ld.AuctionID, Is.EqualTo(land.AuctionID));
- Assert.That(ld.AuthBuyerID, Is.EqualTo(land.AuthBuyerID));
- Assert.That(ld.Category, Is.EqualTo(land.Category));
- Assert.That(ld.ClaimDate, Is.EqualTo(land.ClaimDate));
- Assert.That(ld.ClaimPrice, Is.EqualTo(land.ClaimPrice));
- Assert.That(ld.GlobalID, Is.EqualTo(land.GlobalID), "Reified LandData.GlobalID != original LandData.GlobalID");
- Assert.That(ld.GroupID, Is.EqualTo(land.GroupID));
- Assert.That(ld.Description, Is.EqualTo(land.Description));
- Assert.That(ld.Flags, Is.EqualTo(land.Flags));
- Assert.That(ld.LandingType, Is.EqualTo(land.LandingType));
- Assert.That(ld.Name, Is.EqualTo(land.Name), "Reified LandData.Name != original LandData.Name");
- Assert.That(ld.Status, Is.EqualTo(land.Status));
- Assert.That(ld.LocalID, Is.EqualTo(land.LocalID));
- Assert.That(ld.MediaAutoScale, Is.EqualTo(land.MediaAutoScale));
- Assert.That(ld.MediaID, Is.EqualTo(land.MediaID));
- Assert.That(ld.MediaURL, Is.EqualTo(land.MediaURL));
- Assert.That(ld.OwnerID, Is.EqualTo(land.OwnerID));
- }
-
- [Test]
- public void TestLandDataDeserializeWithAccessLists()
- {
- TestHelpers.InMethod();
-// log4net.Config.XmlConfigurator.Configure();
-
- LandData ld = LandDataSerializer.Deserialize(LandDataSerializerTest.preSerializedWithParcelAccessList);
- Assert.That(ld != null,
- "Deserialize(string) returned null (pre-serialized with parcel access list)");
- Assert.That(ld.GlobalID == this.landWithParcelAccessList.GlobalID,
- "Reified LandData.GlobalID != original LandData.GlobalID (pre-serialized with parcel access list)");
- Assert.That(ld.Name == this.landWithParcelAccessList.Name,
- "Reified LandData.Name != original LandData.Name (pre-serialized with parcel access list)");
- Assert.That(ld.ParcelAccessList.Count, Is.EqualTo(2));
- Assert.That(ld.ParcelAccessList[0].AgentID, Is.EqualTo(UUID.Parse("62d65d45-c91a-4f77-862c-46557d978b6c")));
- }
- }
-}
diff --git a/OpenSim/Framework/Serialization/Tests/OpenSim.Framework.Serialization.Tests.csproj b/OpenSim/Framework/Serialization/Tests/OpenSim.Framework.Serialization.Tests.csproj
deleted file mode 100644
index 1a9ddda6c3c..00000000000
--- a/OpenSim/Framework/Serialization/Tests/OpenSim.Framework.Serialization.Tests.csproj
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
- net48
-
-
-
-
-
-
-
-
-
- ..\..\..\..\bin\OpenMetaverse.dll
- False
-
-
- ..\..\..\..\bin\OpenMetaverse.StructuredData.dll
- False
-
-
- ..\..\..\..\bin\OpenMetaverseTypes.dll
- False
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/OpenSim/Framework/Serialization/Tests/RegionSettingsSerializerTests.cs b/OpenSim/Framework/Serialization/Tests/RegionSettingsSerializerTests.cs
deleted file mode 100644
index 4f3f2ddde31..00000000000
--- a/OpenSim/Framework/Serialization/Tests/RegionSettingsSerializerTests.cs
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using NUnit.Framework;
-using OpenSim.Framework;
-using OpenSim.Framework.Serialization.External;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Serialization.Tests
-{
- [TestFixture]
- public class RegionSettingsSerializerTests : OpenSimTestCase
- {
- private string m_serializedRs = @"
-
-
- True
- True
- True
- True
- True
- True
- True
- True
- True
- 1
- True
- 40
- 1.4
-
-
- 00000000-0000-0000-0000-000000000020
- 00000000-0000-0000-0000-000000000040
- 00000000-0000-0000-0000-000000000060
- 00000000-0000-0000-0000-000000000080
- 1.9
- 15.9
- 49
- 45.3
- 2.1
- 4.5
- 9.2
- 19.2
-
-
- 23
- 17.9
- 0.4
- True
- true
- 12
-
-
- 00000000-0000-0000-0000-111111111111
- 1,-2,0.33
-
-";
-
- private RegionSettings m_rs;
-
- [SetUp]
- public void Setup()
- {
- m_rs = new RegionSettings();
- m_rs.AgentLimit = 17;
- m_rs.AllowDamage = true;
- m_rs.AllowLandJoinDivide = true;
- m_rs.AllowLandResell = true;
- m_rs.BlockFly = true;
- m_rs.BlockShowInSearch = true;
- m_rs.BlockTerraform = true;
- m_rs.DisableCollisions = true;
- m_rs.DisablePhysics = true;
- m_rs.DisableScripts = true;
- m_rs.Elevation1NW = 15.9;
- m_rs.Elevation1NE = 45.3;
- m_rs.Elevation1SE = 49;
- m_rs.Elevation1SW = 1.9;
- m_rs.Elevation2NW = 4.5;
- m_rs.Elevation2NE = 19.2;
- m_rs.Elevation2SE = 9.2;
- m_rs.Elevation2SW = 2.1;
- m_rs.FixedSun = true;
- m_rs.SunPosition = 12.0;
- m_rs.ObjectBonus = 1.4;
- m_rs.RestrictPushing = true;
- m_rs.TerrainLowerLimit = 0.4;
- m_rs.TerrainRaiseLimit = 17.9;
- m_rs.TerrainTexture1 = UUID.Parse("00000000-0000-0000-0000-000000000020");
- m_rs.TerrainTexture2 = UUID.Parse("00000000-0000-0000-0000-000000000040");
- m_rs.TerrainTexture3 = UUID.Parse("00000000-0000-0000-0000-000000000060");
- m_rs.TerrainTexture4 = UUID.Parse("00000000-0000-0000-0000-000000000080");
- m_rs.UseEstateSun = true;
- m_rs.WaterHeight = 23;
- m_rs.TelehubObject = UUID.Parse("00000000-0000-0000-0000-111111111111");
- m_rs.AddSpawnPoint(SpawnPoint.Parse("1,-2,0.33"));
- }
-
- [Test]
- public void TestRegionSettingsDeserialize()
- {
- TestHelpers.InMethod();
-// log4net.Config.XmlConfigurator.Configure();
-
- RegionSettings deserRs = RegionSettingsSerializer.Deserialize(m_serializedRs, out ViewerEnvironment dummy, new EstateSettings());
- Assert.That(deserRs, Is.Not.Null);
- Assert.That(deserRs.TerrainTexture2, Is.EqualTo(m_rs.TerrainTexture2));
- Assert.That(deserRs.DisablePhysics, Is.EqualTo(m_rs.DisablePhysics));
- Assert.That(deserRs.TerrainLowerLimit, Is.EqualTo(m_rs.TerrainLowerLimit));
- Assert.That(deserRs.TelehubObject, Is.EqualTo(m_rs.TelehubObject));
- Assert.That(deserRs.SpawnPoints()[0].ToString(), Is.EqualTo(m_rs.SpawnPoints()[0].ToString()));
- }
- }
-}
diff --git a/OpenSim/Framework/Servers/BaseOpenSimServer.cs b/OpenSim/Framework/Servers/BaseOpenSimServer.cs
index 5feb7b521fb..940713b17cb 100644
--- a/OpenSim/Framework/Servers/BaseOpenSimServer.cs
+++ b/OpenSim/Framework/Servers/BaseOpenSimServer.cs
@@ -27,28 +27,21 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Reflection;
using System.Text;
-using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using log4net;
-using log4net.Appender;
-using log4net.Core;
-using log4net.Repository;
using OpenMetaverse;
-using OpenMetaverse.StructuredData;
using OpenSim.Framework;
-using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
-using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Timer=System.Timers.Timer;
using Nini.Config;
+using System.Runtime.InteropServices;
namespace OpenSim.Framework.Servers
{
@@ -89,8 +82,8 @@ public BaseOpenSimServer() : base()
m_osSecret = UUID.Random().ToString();
}
- private static bool m_NoVerifyCertChain = false;
- private static bool m_NoVerifyCertHostname = false;
+ private static bool m_NoVerifyCertChain = true;
+ private static bool m_NoVerifyCertHostname = true;
public static bool ValidateServerCertificate(
object sender,
@@ -124,6 +117,8 @@ protected virtual void StartupSpecific()
m_NoVerifyCertHostname = startupConfig.GetBoolean("NoVerifyCertHostname", m_NoVerifyCertHostname);
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
+ WebUtil.SetupHTTPClients(m_NoVerifyCertChain, m_NoVerifyCertHostname, null, 32 );
+
int logShowStatsSeconds = startupConfig.GetInt("LogShowStatsSeconds", m_periodDiagnosticTimerMS / 1000);
m_periodDiagnosticTimerMS = logShowStatsSeconds * 1000;
m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
@@ -184,21 +179,9 @@ public virtual void Startup()
{
m_log.Info("[STARTUP]: Beginning startup processing");
- m_log.Info("[STARTUP]: version: " + m_version + Environment.NewLine);
- // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
- // the clr version number doesn't match the project version number under Mono.
- //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
- m_log.InfoFormat(
- "[STARTUP]: Operating system version: {0}, .NET platform {1}, {2}-bit\n",
- Environment.OSVersion, Environment.OSVersion.Platform, Environment.Is64BitProcess ? "64" : "32");
-
- // next code can be changed on .net 4.7.x
- if(Util.IsWindows())
- m_log.InfoFormat("[STARTUP]: Processor Architecture: {0}({1})",
- System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE", EnvironmentVariableTarget.Machine),
- BitConverter.IsLittleEndian ?"le":"be");
-
- // on other platforms we need to wait for .net4.7.1
+ m_log.Info("[STARTUP]: version: " + m_version);
+ m_log.Info($"[STARTUP]: Operating system version: {Environment.OSVersion}, .NET platform {Util.RuntimePlatformStr}, Runtime {Environment.Version}");
+ m_log.Info($"[STARTUP]: Processor Architecture: {RuntimeInformation.ProcessArchitecture}({(BitConverter.IsLittleEndian ? "le" : "be")} {(Environment.Is64BitProcess ? "64" : "32")}bit)");
try
{
StartupSpecific();
@@ -208,12 +191,6 @@ public virtual void Startup()
m_log.Fatal("Fatal error: " + e.ToString());
Environment.Exit(1);
}
-
- //TimeSpan timeTaken = DateTime.Now - m_startuptime;
-
-// MainConsole.Instance.OutputFormat(
-// "PLEASE WAIT FOR LOGINS TO BE ENABLED ON REGIONS ONCE SCRIPTS HAVE STARTED. Non-script portion of startup took {0}m {1}s.",
-// timeTaken.Minutes, timeTaken.Seconds);
}
public string osSecret
diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
index be6c97346df..9fa9edfe2e0 100644
--- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
+++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
@@ -46,17 +46,17 @@
using Nwc.XmlRpc;
using OpenSim.Framework.Monitoring;
using OpenMetaverse.StructuredData;
-
+using OpenMetaverse;
namespace OpenSim.Framework.Servers.HttpServer
{
public class BaseHttpServer : IHttpServer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- private HttpServerLogWriter httpserverlog = new HttpServerLogWriter();
- private static Encoding UTF8NoBOM = new System.Text.UTF8Encoding(false);
+ private readonly HttpServerLogWriter httpserverlog = new HttpServerLogWriter();
+ private static readonly Encoding UTF8NoBOM = new System.Text.UTF8Encoding(false);
public static PollServiceRequestManager m_pollServiceManager;
- private static object m_generalLock = new object();
+ private static readonly object m_generalLock = new object();
private string HTTP404;
///
@@ -90,7 +90,6 @@ public class BaseHttpServer : IHttpServer
///
private Stat m_requestsProcessedStat;
- private volatile int NotSocketErrors = 0;
public volatile bool HTTPDRunning = false;
protected tinyHTTPListener m_httpListener;
@@ -218,7 +217,7 @@ private void load_cert(string CPath, string CPass)
{
try
{
- m_cert = new X509Certificate2(CPath, CPass);
+ m_cert = new X509Certificate2(CPath, CPass);
X509Extension ext = m_cert.Extensions["2.5.29.17"];
if(ext != null)
{
@@ -283,7 +282,7 @@ static bool MatchDNS(string hostname, string dns)
if (indx2 != -1)
return false; // there can only be one;
- string end = dns.Substring(indx + 1);
+ string end = dns[(indx + 1)..];
int hostlen = hostname.Length;
int endlen = end.Length;
int length = hostlen - endlen;
@@ -299,7 +298,7 @@ static bool MatchDNS(string hostname, string dns)
return ((indx2 == -1) || (indx2 >= length));
}
- string start = dns.Substring(0, indx);
+ string start = dns[..indx];
return (String.Compare(hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);
}
@@ -336,19 +335,15 @@ public bool CheckSSLCertHost(string hostname)
///
public void AddStreamHandler(IRequestHandler handler)
{
- string httpMethod = handler.HttpMethod;
- string path = handler.Path;
-
- if(path == "/")
+ if(handler.Path.Equals("/"))
{
- if(httpMethod == "GET")
+ if(handler.HttpMethod.Equals("GET"))
m_RootDefaultGET = handler;
return;
}
- string handlerKey = GetHandlerKey(httpMethod, path);
-
+ string handlerKey = GetHandlerKey(handler.HttpMethod, handler.Path);
// m_log.DebugFormat("[BASE HTTP SERVER]: Adding handler key {0}", handlerKey);
m_streamHandlers.TryAdd(handlerKey, handler);
}
@@ -419,7 +414,6 @@ public bool AddXmlRPCHandler(string method, XmlRpcMethod handler, bool keepAlive
m_rpcHandlers[method] = handler;
m_rpcHandlersKeepAlive[method] = keepAlive; // default
}
-
return true;
}
@@ -427,7 +421,7 @@ public XmlRpcMethod GetXmlRPCHandler(string method)
{
lock (m_rpcHandlers)
{
- return (m_rpcHandlers.TryGetValue(method, out XmlRpcMethod xm)) ? xm : null;
+ return m_rpcHandlers.TryGetValue(method, out XmlRpcMethod xm) ? xm : null;
}
}
@@ -435,7 +429,7 @@ public bool TryGetXmlRPCHandler(string method, out XmlRpcMethod handler)
{
lock (m_rpcHandlers)
{
- return (m_rpcHandlers.TryGetValue(method, out handler));
+ return m_rpcHandlers.TryGetValue(method, out handler);
}
}
@@ -450,9 +444,8 @@ public bool AddJsonRPCHandler(string method, JsonRPCMethod handler)
{
lock(jsonRpcHandlers)
{
- jsonRpcHandlers.Add(method, handler);
+ return jsonRpcHandlers.TryAdd(method, handler);
}
- return true;
}
public JsonRPCMethod GetJsonRPCHandler(string method)
@@ -472,18 +465,10 @@ public List GetJsonRpcHandlerKeys()
public bool AddHTTPHandler(string methodName, GenericHTTPMethod handler)
{
//m_log.DebugFormat("[BASE HTTP SERVER]: Registering {0}", methodName);
-
lock (m_HTTPHandlers)
{
- if (!m_HTTPHandlers.ContainsKey(methodName))
- {
- m_HTTPHandlers.Add(methodName, handler);
- return true;
- }
+ return m_HTTPHandlers.TryAdd(methodName, handler);
}
-
- //must already have a handler for that path so return false
- return false;
}
public List GetHTTPHandlerKeys()
@@ -518,13 +503,8 @@ public bool AddLLSDHandler(string path, LLSDMethod handler)
{
lock (m_llsdHandlers)
{
- if (!m_llsdHandlers.ContainsKey(path))
- {
- m_llsdHandlers.Add(path, handler);
- return true;
- }
+ return m_llsdHandlers.TryAdd(path, handler);
}
- return false;
}
public List GetLLSDHandlerKeys()
@@ -594,12 +574,12 @@ public void OnRequest(object source, RequestEventArgs args)
{
psEvArgs.RequestsReceived++;
PollServiceHttpRequest psreq = new PollServiceHttpRequest(psEvArgs, request);
- if(psEvArgs.Request == null)
+ if(psEvArgs.Request is null)
m_pollServiceManager.Enqueue(psreq);
else
{
OSHttpResponse resp = psEvArgs.Request.Invoke(psreq.RequestID, osRequest);
- if(resp == null)
+ if(resp is null)
m_pollServiceManager.Enqueue(psreq);
else
resp.Send();
@@ -613,7 +593,7 @@ public void OnRequest(object source, RequestEventArgs args)
}
catch (Exception e)
{
- m_log.Error(string.Format("[BASE HTTP SERVER]: OnRequest() failed: {0} ", e.Message), e);
+ m_log.Error($"[BASE HTTP SERVER]: OnRequest() failed: {e.Message}");
}
}
@@ -624,28 +604,22 @@ public void OnRequest(object source, RequestEventArgs args)
///
public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response)
{
- string requestMethod = request.HttpMethod;
- string uriString = request.RawUrl;
-
int requestStartTick = Environment.TickCount;
-
- // Will be adjusted later on.
int requestEndTick = requestStartTick;
IRequestHandler requestHandler = null;
-
byte[] responseData = null;
try
{
// OpenSim.Framework.WebUtil.OSHeaderRequestID
-// if (request.Headers["opensim-request-id"] != null)
-// reqnum = String.Format("{0}:{1}",request.RemoteIPEndPoint,request.Headers["opensim-request-id"]);
- //m_log.DebugFormat("[BASE HTTP SERVER]: <{0}> handle request for {1}",reqnum,request.RawUrl);
+ // if (request.Headers["opensim-request-id"] != null)
+ // reqnum = String.Format("{0}:{1}",request.RemoteIPEndPoint,request.Headers["opensim-request-id"]);
+ // m_log.DebugFormat("[BASE HTTP SERVER]: <{0}> handle request for {1}",reqnum,request.RawUrl);
Culture.SetCurrentCulture();
- if (request.HttpMethod == "OPTIONS")
+ if (request.HttpMethod.Equals("OPTIONS"))
{
//need to check this
response.AddHeader("Access-Control-Allow-Origin", "*");
@@ -653,7 +627,7 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
response.StatusCode = (int)HttpStatusCode.OK;
- if (request.InputStream != null && request.InputStream.CanRead)
+ if (request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Dispose();
requestEndTick = Environment.TickCount;
@@ -662,20 +636,18 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
return;
}
- string path = request.UriPath;
- if (path == "/")
+ if (request.UriPath.Equals("/"))
{
response.StatusCode = (int)HttpStatusCode.NotFound; // default
- if (m_RootDefaultGET != null && request.HttpMethod == "GET")
+ if (m_RootDefaultGET is not null && request.HttpMethod.Equals("GET"))
{
- if(m_RootDefaultGET is IStreamedRequestHandler)
+ if(m_RootDefaultGET is IStreamedRequestHandler isrh)
{
- IStreamedRequestHandler isrh = m_RootDefaultGET as IStreamedRequestHandler;
- response.RawBuffer = isrh.Handle(path, request.InputStream, request, response);
+ response.RawBuffer = isrh.Handle(request.UriPath, request.InputStream, request, response);
response.StatusCode = (int)HttpStatusCode.OK;
}
- if (request.InputStream != null && request.InputStream.CanRead)
+ if (request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Dispose();
requestEndTick = Environment.TickCount;
@@ -720,7 +692,7 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
}
}
- if (request.InputStream != null && request.InputStream.CanRead)
+ if (request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Dispose();
requestEndTick = Environment.TickCount;
@@ -729,7 +701,7 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
return;
}
- path = Util.TrimEndSlash(path);
+ string path = Util.TrimEndSlash(request.UriPath);
if (TryGetSimpleStreamHandler(path, out ISimpleStreamHandler hdr))
{
@@ -737,7 +709,7 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
LogIncomingToStreamHandler(request, hdr);
hdr.Handle(request, response);
- if (request.InputStream != null && request.InputStream.CanRead)
+ if (request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Dispose();
requestEndTick = Environment.TickCount;
@@ -756,16 +728,13 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type.
- if (requestHandler is IStreamedRequestHandler)
+ if (requestHandler is IStreamedRequestHandler streamedRequestHandler)
{
- IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler;
-
buffer = streamedRequestHandler.Handle(path, request.InputStream, request, response);
}
- else if (requestHandler is IGenericHTTPHandler)
+ else if (requestHandler is IGenericHTTPHandler HTTPRequestHandler)
{
//m_log.Debug("[BASE HTTP SERVER]: Found Caps based HTTP Handler");
- IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler;
string requestBody;
Encoding encoding = Encoding.UTF8;
@@ -854,10 +823,10 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
}
}
- if(request.InputStream != null && request.InputStream.CanRead)
+ if(request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Dispose();
- if (buffer != null)
+ if (buffer is not null)
{
if (WebUtil.DebugLevel >= 5)
{
@@ -866,10 +835,10 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
if (WebUtil.DebugLevel >= 6)
{
// Always truncate binary blobs. We don't have a ContentType, so detect them using the request name.
- if ((requestHandler != null && requestHandler.Name == "GetMesh"))
+ if (requestHandler is not null && requestHandler.Name.Equals("GetMesh"))
{
if (output.Length > WebUtil.MaxRequestDiagLength)
- output = output.Substring(0, WebUtil.MaxRequestDiagLength) + "...";
+ output = string.Concat(output.AsSpan(0, WebUtil.MaxRequestDiagLength), "...");
}
}
@@ -903,7 +872,7 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
//
// An alternative may be to turn off all response write exceptions on the HttpListener, but let's go
// with the minimum first
- m_log.Warn(String.Format("[BASE HTTP SERVER]: HandleRequest threw {0}.\nNOTE: this may be spurious on Linux ", e.Message), e);
+ m_log.Warn($"[BASE HTTP SERVER]: HandleRequest threw {e.Message}.\nNOTE: this may be spurious on Linux");
}
catch (IOException e)
{
@@ -922,7 +891,7 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
}
finally
{
- if(request.InputStream != null && request.InputStream.CanRead)
+ if(request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Close();
int tickdiff = requestEndTick - requestStartTick;
@@ -931,10 +900,10 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
m_log.InfoFormat(
"[LOGHTTP] Slow handling of {0} {1} {2} {3} {4} from {5} took {6}ms",
RequestNumber,
- requestMethod,
- uriString,
- requestHandler != null ? requestHandler.Name : "",
- requestHandler != null ? requestHandler.Description : "",
+ request.HttpMethod,
+ request.RawUrl,
+ requestHandler is null ? "" : requestHandler.Name,
+ requestHandler is null ? "" : requestHandler.Description,
request.RemoteIPEndPoint,
tickdiff);
}
@@ -953,12 +922,10 @@ public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response
if (DebugLevel == 5)
{
if (output.Length > WebUtil.MaxRequestDiagLength)
- output = output.Substring(0, WebUtil.MaxRequestDiagLength) + "...";
+ output = string.Concat(output.AsSpan(0, WebUtil.MaxRequestDiagLength), "...");
}
m_log.DebugFormat("[LOGHTTP] RESPONSE {0}: {1}", RequestNumber, output);
}
-
- responseData = null;
}
}
@@ -1101,7 +1068,7 @@ private bool TryGetPollServiceHTTPHandler(string handlerKey, out PollServiceEven
if(m_pollHandlers.TryGetValue(handlerKey, out oServiceEventArgs))
return true;
- if(m_pollHandlersVarPath.Count > 0 && handlerKey.Length >= 45)
+ if(!m_pollHandlersVarPath.IsEmpty && handlerKey.Length >= 45)
{
// tuned for lsl requests, the only ones that should reach this, so be strict (/lslhttp/uuid.ToString())
int indx = handlerKey.IndexOf('/', 44);
@@ -1110,7 +1077,7 @@ private bool TryGetPollServiceHTTPHandler(string handlerKey, out PollServiceEven
if(m_pollHandlersVarPath.TryGetValue(handlerKey, out oServiceEventArgs))
return true;
}
- else if(m_pollHandlersVarPath.TryGetValue(handlerKey.Substring(0, indx), out oServiceEventArgs))
+ else if(m_pollHandlersVarPath.TryGetValue(handlerKey[..indx], out oServiceEventArgs))
return true;
}
@@ -1165,7 +1132,7 @@ private bool TryGetSimpleStreamHandler(string uripath, out ISimpleStreamHandler
if(indx < 0 || indx == uripath.Length - 1)
return false;
- return m_simpleStreamVarPath.TryGetValue(uripath.Substring(0,indx), out handler);
+ return m_simpleStreamVarPath.TryGetValue(uripath[..indx], out handler);
}
///
@@ -1209,7 +1176,7 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
{
if (requestStream.CanRead)
requestStream.Dispose();
- if (innerStream != null && innerStream.CanRead)
+ if (innerStream is not null && innerStream.CanRead)
innerStream.Dispose();
response.StatusCode = (int)HttpStatusCode.BadRequest;
@@ -1235,11 +1202,11 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
{
if (requestStream.CanRead)
requestStream.Dispose();
- if (innerStream != null && innerStream.CanRead)
+ if (innerStream is not null && innerStream.CanRead)
innerStream.Dispose();
}
- if (xmlRprcRequest == null)
+ if (xmlRprcRequest is null)
return;
string methodName = xmlRprcRequest.MethodName;
@@ -1267,7 +1234,7 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
string xfflower = xff.ToLower();
foreach (string s in request.Headers.AllKeys)
{
- if (s != null && s.Equals(xfflower))
+ if (s is not null && s.Equals(xfflower))
{
xff = xfflower;
break;
@@ -1291,12 +1258,8 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
}
catch(Exception e)
{
- string errorMessage
- = String.Format(
- "Requested method [{0}] from {1} threw exception: {2} {3}",
- methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace);
-
- m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
+ string errorMessage = $"Requested method [{methodName}] from {request.RemoteIPEndPoint.Address} threw exception: {e.Message}";
+ m_log.Error($"[BASE HTTP SERVER]: {errorMessage}");
// if the registered XmlRpc method threw an exception, we pass a fault-code along
xmlRpcResponse = new XmlRpcResponse();
@@ -1349,7 +1312,7 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response,
{
if (requestStream.CanRead)
requestStream.Dispose();
- if (innerStream != null && innerStream.CanRead)
+ if (innerStream is not null && innerStream.CanRead)
innerStream.Dispose();
response.StatusCode = (int)HttpStatusCode.BadRequest;
@@ -1376,11 +1339,11 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response,
{
if (requestStream.CanRead)
requestStream.Dispose();
- if (innerStream != null && innerStream.CanRead)
+ if (innerStream is not null && innerStream.CanRead)
innerStream.Dispose();
}
- if (xmlRprcRequest == null)
+ if (xmlRprcRequest is null)
{
response.StatusCode = (int)HttpStatusCode.NotFound;
response.KeepAlive = false;
@@ -1395,10 +1358,9 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response,
return;
}
- XmlRpcMethod method;
bool methodWasFound;
- methodWasFound = rpcHandlers.TryGetValue(methodName, out method);
+ methodWasFound = rpcHandlers.TryGetValue(methodName, out XmlRpcMethod method);
XmlRpcResponse xmlRpcResponse;
if (methodWasFound)
@@ -1406,27 +1368,20 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response,
xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
xmlRprcRequest.Params.Add(request.Url); // Param[2]
- string xff = "X-Forwarded-For";
- string xfflower = xff.ToLower();
foreach (string s in request.Headers.AllKeys)
{
- if (s != null && s.Equals(xfflower))
+ if (s is not null && s.Equals("x-forwarded-for", StringComparison.OrdinalIgnoreCase))
{
- xff = xfflower;
+ xmlRprcRequest.Params.Add(request.Headers.Get(s)); // Param[3]
break;
}
}
- xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3]
// reserve this for
// ... by Fumi.Iseki for DTLNSLMoneyServer
// BUT make its presence possible to detect/parse
- string rcn = request.IHttpClientContext.SSLCommonName;
- if (!string.IsNullOrWhiteSpace(rcn))
- {
- rcn = "SSLCN:" + rcn;
- xmlRprcRequest.Params.Add(rcn); // Param[4] or Param[5]
- }
+ if (!string.IsNullOrWhiteSpace(request.IHttpClientContext.SSLCommonName))
+ xmlRprcRequest.Params.Add("SSLCN:" + request.IHttpClientContext.SSLCommonName); // Param[4] or Param[5]
try
{
@@ -1435,8 +1390,8 @@ public void HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response,
catch (Exception e)
{
string errorMessage = string.Format(
- "Requested method [{0}] from {1} threw exception: {2} {3}",
- methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace);
+ "Requested method [{0}] from {1} threw exception: {2}",
+ methodName, request.RemoteIPEndPoint.Address, e.Message);
m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
@@ -1492,10 +1447,10 @@ private void HandleJsonRpcRequests(OSHttpRequest request, OSHttpResponse respons
jsonRpcResponse.Error.Message = e.Message;
}
- if (request.InputStream != null && request.InputStream.CanRead)
+ if (request.InputStream is not null && request.InputStream.CanRead)
request.InputStream.Dispose();
- if (jsonRpcRequest != null)
+ if (jsonRpcRequest is not null)
{
// If we have no id, then it's a "notification"
if (jsonRpcRequest.TryGetValue("id", out OSD val))
@@ -1547,7 +1502,7 @@ private void HandleJsonRpcRequests(OSHttpRequest request, OSHttpResponse respons
private void HandleLLSDLogin(OSHttpRequest request, OSHttpResponse response)
{
- if (m_defaultLlsdHandler == null)
+ if (m_defaultLlsdHandler is null)
return;
response.StatusCode = (int)HttpStatusCode.BadRequest;
@@ -1555,11 +1510,11 @@ private void HandleLLSDLogin(OSHttpRequest request, OSHttpResponse response)
try
{
OSD llsdRequest = OSDParser.DeserializeLLSDXml(request.InputStream);
- if (llsdRequest == null || !(llsdRequest is OSDMap))
+ if (llsdRequest is not OSDMap)
return;
OSD llsdResponse = m_defaultLlsdHandler(llsdRequest, request.RemoteIPEndPoint);
- if (llsdResponse != null)
+ if (llsdResponse is not null)
{
response.ContentType = "application/llsd+xml";
response.RawBuffer = OSDParser.SerializeLLSDXmlBytes(llsdResponse);
@@ -1593,7 +1548,7 @@ private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response
m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
}
- if (llsdRequest == null)
+ if (llsdRequest is null)
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
return null;
@@ -1609,14 +1564,14 @@ private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response
llsdResponse = null;
}
- if (llsdResponse == null)
+ if (llsdResponse is null)
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
return null;
}
byte[] buffer = Array.Empty();
- if (llsdResponse.ToString() == "shutdown404!")
+ if (llsdResponse.ToString().Equals("shutdown404!"))
{
response.ContentType = "text/plain";
response.StatusCode = (int)HttpStatusCode.NotFound;
@@ -1634,9 +1589,9 @@ private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response
return buffer;
}
- private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
+ private static byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
{
- if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
+ if (request.AcceptTypes is not null && request.AcceptTypes.Length > 0)
{
foreach (string strAccept in request.AcceptTypes)
{
@@ -1655,7 +1610,7 @@ private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response,
}
}
- if (!String.IsNullOrEmpty(request.ContentType))
+ if (!string.IsNullOrEmpty(request.ContentType))
{
switch (request.ContentType)
{
@@ -1677,6 +1632,14 @@ private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response,
return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
}
+ private ReadOnlySpan CleanSearchPath(ReadOnlySpan path)
+ {
+ path = path.Trim().TrimEnd('/');
+ if (path[0] == '/')
+ return path;
+ return ("/" + path.ToString()).AsSpan();
+ }
+
///
/// Checks if we have an Exact path in the LLSD handlers for the path provided
///
@@ -1684,38 +1647,22 @@ private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response,
/// true if we have one, false if not
private bool DoWeHaveALLSDHandler(string path)
{
- string[] pathbase = path.Split('/');
- string searchquery = "/";
-
- if (pathbase.Length < 1)
- return false;
-
- for (int i = 1; i < pathbase.Length; i++)
+ if(m_llsdHandlers.Count == 0)
{
- searchquery += pathbase[i];
- if (pathbase.Length - 1 != i)
- searchquery += "/";
+ return false;
}
- string bestMatch = null;
+ var searchquery = CleanSearchPath(path.AsSpan());
lock (m_llsdHandlers)
{
foreach (string pattern in m_llsdHandlers.Keys)
{
- if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
- bestMatch = pattern;
+ if (searchquery.Length >= pattern.Length && searchquery.StartsWith(pattern))
+ return true;
}
}
-
- if (String.IsNullOrEmpty(bestMatch))
- {
- return false;
- }
- else
- {
- return true;
- }
+ return false;
}
///
@@ -1725,64 +1672,34 @@ private bool DoWeHaveALLSDHandler(string path)
/// true if we have one, false if not
private bool DoWeHaveAHTTPHandler(string path)
{
- string[] pathbase = path.Split('/');
- string searchquery = "/";
-
- if (pathbase.Length < 1)
- return false;
-
- for (int i = 1; i < pathbase.Length; i++)
- {
- searchquery += pathbase[i];
- if (pathbase.Length - 1 != i)
- searchquery += "/";
- }
-
- string bestMatch = null;
+ var searchquery = CleanSearchPath(path.AsSpan());
//m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery);
-
lock (m_HTTPHandlers)
{
foreach (string pattern in m_HTTPHandlers.Keys)
{
- if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length)
- {
- bestMatch = pattern;
- }
- }
-
- if (String.IsNullOrEmpty(bestMatch))
- {
- return false;
- }
- else
- {
- return true;
+ if (searchquery.Length >= pattern.Length && searchquery.StartsWith(pattern))
+ return true;
}
}
+ return false;
}
private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler)
{
- llsdHandler = null;
+ if(m_llsdHandlers.Count == 0)
+ {
+ llsdHandler = null;
+ return false;
+ }
+
// Pull out the first part of the path
// splitting the path by '/' means we'll get the following return..
// {0}/{1}/{2}
// where {0} isn't something we really control 100%
- string[] pathbase = path.Split('/');
- string searchquery = "/";
-
- if (pathbase.Length < 1)
- return false;
-
- for (int i=1; i bestMatch.Length)
+ if (nomatch || searchquery.Length > bestMatch.Length)
{
- // You have to specifically register for '/' and to get it, you must specificaly request it
- //
- if (pattern == "/" && searchquery == "/" || pattern != "/")
- bestMatch = pattern;
+ bestMatch = pattern;
+ nomatch = false;
}
}
}
- if (String.IsNullOrEmpty(bestMatch))
+ if (nomatch)
{
llsdHandler = null;
return false;
}
- else
+ if (bestMatch == "/" && searchquery != "/")
{
- llsdHandler = m_llsdHandlers[bestMatch];
- return true;
+ llsdHandler = null;
+ return false;
}
+
+ llsdHandler = m_llsdHandlers[bestMatch];
+ return true;
}
}
@@ -1848,8 +1766,6 @@ public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
// to display the form, or process it.
// a better way would be nifty.
- byte[] buffer;
-
string requestBody;
using(StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8))
requestBody = reader.ReadToEnd();
@@ -1859,7 +1775,7 @@ public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
Hashtable requestVars = new Hashtable();
- string host = String.Empty;
+ string host = string.Empty;
string[] querystringkeys = request.QueryString.AllKeys;
string[] rHeaders = request.Headers.AllKeys;
@@ -1871,8 +1787,8 @@ public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
foreach (string queryname in querystringkeys)
{
-// m_log.DebugFormat(
-// "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
+ //m_log.DebugFormat(
+ // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]);
if(!string.IsNullOrEmpty(queryname))
{
keysvals.Add(queryname, request.QueryString[queryname]);
@@ -1882,93 +1798,73 @@ public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response)
foreach (string headername in rHeaders)
{
-// m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
+ //m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]);
headervals[headername] = request.Headers[headername];
}
keysvals.Add("headers", headervals);
keysvals.Add("querystringkeys", querystringkeys);
keysvals.Add("requestvars", requestVars);
-// keysvals.Add("form", request.Form);
+ //keysvals.Add("form", request.Form);
Hashtable responsedata2 = requestprocessor(keysvals);
- buffer = DoHTTPGruntWork(responsedata2, response);
- return buffer;
+ return DoHTTPGruntWork(responsedata2, response);
}
private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler)
{
- httpHandler = null;
- // Pull out the first part of the path
- // splitting the path by '/' means we'll get the following return..
- // {0}/{1}/{2}
- // where {0} isn't something we really control 100%
-
- string[] pathbase = path.Split('/');
- string searchquery = "/";
-
- if (pathbase.Length < 1)
- return false;
-
- for (int i = 1; i < pathbase.Length; i++)
+ if(m_HTTPHandlers.Count == 0)
{
- searchquery += pathbase[i];
- if (pathbase.Length - 1 != i)
- searchquery += "/";
+ httpHandler = null;
+ return false;
}
- // while the matching algorithm below doesn't require it, we're expecting a query in the form
- //
- // [] = optional
- // /resource/UUID/action[/action]
- //
- // now try to get the closest match to the reigstered path
- // at least for OGP, registered path would probably only consist of the /resource/
-
+ var searchquery = CleanSearchPath(path);
string bestMatch = null;
+ bool nomatch = true;
-// m_log.DebugFormat(
-// "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
+ //m_log.DebugFormat(
+ // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery);
lock (m_HTTPHandlers)
{
foreach (string pattern in m_HTTPHandlers.Keys)
{
- if (searchquery.ToLower().StartsWith(pattern.ToLower()))
+ if (searchquery.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase))
{
- if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length)
+ if (nomatch || searchquery.Length > bestMatch.Length)
{
- // You have to specifically register for '/' and to get it, you must specifically request it
- if (pattern == "/" && searchquery == "/" || pattern != "/")
- bestMatch = pattern;
+ bestMatch = pattern;
+ nomatch = false;
}
}
}
- if (string.IsNullOrEmpty(bestMatch))
+ if (nomatch)
{
httpHandler = null;
return false;
}
- else
- {
- if (bestMatch == "/" && searchquery != "/")
- return false;
- httpHandler = m_HTTPHandlers[bestMatch];
- return true;
+ if (bestMatch == "/" && searchquery != "/")
+ {
+ httpHandler = null;
+ return false;
}
+
+ httpHandler = m_HTTPHandlers[bestMatch];
+ return true;
}
}
- internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
+ internal static byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
{
int responsecode;
- string responseString = String.Empty;
+ string responseString = string.Empty;
byte[] responseData = null;
string contentType;
- if (responsedata == null)
+ if (responsedata is null)
{
responsecode = 500;
responseString = "No response could be obtained";
@@ -1981,13 +1877,11 @@ internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
{
//m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
responsecode = (int)responsedata["int_response_code"];
- if (responsedata["bin_response_data"] != null)
- responseData = (byte[])responsedata["bin_response_data"];
+ contentType = (string)responsedata["content_type"];
+ if (responsedata["bin_response_data"] is byte[] b)
+ responseData = b;
else
responseString = (string)responsedata["str_response_string"];
- contentType = (string)responsedata["content_type"];
- if (responseString == null)
- responseString = String.Empty;
}
catch
{
@@ -1999,13 +1893,10 @@ internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
}
if (responsedata.ContainsKey("error_status_text"))
- {
response.StatusDescription = (string)responsedata["error_status_text"];
- }
+
if (responsedata.ContainsKey("http_protocol_version"))
- {
response.ProtocolVersion = (string)responsedata["http_protocol_version"];
- }
if (responsedata.ContainsKey("keepalive"))
{
@@ -2045,12 +1936,15 @@ internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
byte[] buffer;
- if (responseData != null)
+ if (responseData is not null)
{
buffer = responseData;
}
else
{
+ if(string.IsNullOrEmpty(responseString))
+ return null;
+
if (!(contentType.Contains("image")
|| contentType.Contains("x-shockwave-flash")
|| contentType.Contains("application/x-oar")
@@ -2064,11 +1958,9 @@ internal byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpResponse response)
// Binary!
buffer = Convert.FromBase64String(responseString);
}
-
response.ContentLength64 = buffer.Length;
response.ContentEncoding = Encoding.UTF8;
}
-
return buffer;
}
@@ -2100,14 +1992,11 @@ public void Start()
///
public void Start(bool performPollResponsesAsync, bool runPool)
{
- m_log.InfoFormat(
- "[BASE HTTP SERVER]: Starting {0} server on port {1}", UseSSL ? "HTTPS" : "HTTP", Port);
+ m_log.Info($"[BASE HTTP SERVER]: Starting HTTP{(UseSSL ? "S" : "")} server on port {Port}");
try
{
//m_httpListener = new HttpListener();
-
- NotSocketErrors = 0;
if (!m_ssl)
{
m_httpListener = tinyHTTPListener.Create(m_listenIPAddress, (int)m_port);
@@ -2124,7 +2013,7 @@ public void Start(bool performPollResponsesAsync, bool runPool)
else
{
m_httpListener = tinyHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert);
- if(m_certificateValidationCallback != null)
+ if(m_certificateValidationCallback is not null)
m_httpListener.CertificateValidationCallback = m_certificateValidationCallback;
m_httpListener.ExceptionThrown += httpServerException;
if (DebugLevel > 0)
@@ -2141,8 +2030,7 @@ public void Start(bool performPollResponsesAsync, bool runPool)
{
if (runPool)
{
- if(m_pollServiceManager == null)
- m_pollServiceManager = new PollServiceRequestManager(performPollResponsesAsync, 2, 25000);
+ m_pollServiceManager ??= new PollServiceRequestManager(performPollResponsesAsync, 2, 25000);
m_pollServiceManager.Start();
}
}
@@ -2174,20 +2062,9 @@ public void Start(bool performPollResponsesAsync, bool runPool)
StatsManager.RegisterStat(m_requestsProcessedStat);
}
- public void httpServerDisconnectMonitor(IHttpClientContext source, SocketError err)
+ public static void httpServerException(object source, Exception exception)
{
- switch (err)
- {
- case SocketError.NotSocket:
- NotSocketErrors++;
-
- break;
- }
- }
-
- public void httpServerException(object source, Exception exception)
- {
- if (source.ToString() == "HttpServer.HttpListener" && exception.ToString().StartsWith("Mono.Security.Protocol.Tls.TlsException"))
+ if (source.ToString().Equals("HttpServer.HttpListener") && exception.ToString().StartsWith("Mono.Security.Protocol.Tls.TlsException"))
return;
m_log.ErrorFormat("[BASE HTTP SERVER]: {0} had an exception {1}", source.ToString(), exception.ToString());
}
@@ -2221,34 +2098,35 @@ public void Stop(bool stopPool = false)
public void RemoveStreamHandler(string httpMethod, string path)
{
- if (m_streamHandlers.TryRemove(path, out IRequestHandler dummy))
+ if (m_streamHandlers.TryRemove(path, out _))
return;
string handlerKey = GetHandlerKey(httpMethod, path);
//m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey);
- m_streamHandlers.TryRemove(handlerKey, out dummy);
+ m_streamHandlers.TryRemove(handlerKey, out _);
}
public void RemoveStreamHandler(string path)
{
- m_streamHandlers.TryRemove(path, out IRequestHandler dummy);
+ m_streamHandlers.TryRemove(path, out IRequestHandler _);
}
public void RemoveSimpleStreamHandler(string path)
{
- if(m_simpleStreamHandlers.TryRemove(path, out ISimpleStreamHandler dummy))
+ if(m_simpleStreamHandlers.TryRemove(path, out _))
return;
- m_simpleStreamVarPath.TryRemove(path, out ISimpleStreamHandler dummy2);
+ m_simpleStreamVarPath.TryRemove(path, out _);
}
public void RemoveHTTPHandler(string httpMethod, string path)
{
- if (path == null) return; // Caps module isn't loaded, tries to remove handler where path = null
+ if (string.IsNullOrEmpty(path))
+ return; // Caps module isn't loaded, tries to remove handler where path = null
lock (m_HTTPHandlers)
{
- if (httpMethod != null && httpMethod.Length == 0)
+ if (httpMethod is not null && httpMethod.Length == 0)
{
m_HTTPHandlers.Remove(path);
return;
@@ -2260,14 +2138,14 @@ public void RemoveHTTPHandler(string httpMethod, string path)
public void RemovePollServiceHTTPHandler(string httpMethod, string path)
{
- if(!m_pollHandlers.TryRemove(path, out PollServiceEventArgs dummy))
- m_pollHandlersVarPath.TryRemove(path, out PollServiceEventArgs dummy2);
+ if(!m_pollHandlers.TryRemove(path, out _))
+ m_pollHandlersVarPath.TryRemove(path, out _);
}
public void RemovePollServiceHTTPHandler(string path)
{
- if(!m_pollHandlers.TryRemove(path, out PollServiceEventArgs dummy))
- m_pollHandlersVarPath.TryRemove(path, out PollServiceEventArgs dummy2);
+ if(!m_pollHandlers.TryRemove(path, out _))
+ m_pollHandlersVarPath.TryRemove(path, out _);
}
//public bool RemoveAgentHandler(string agent, IHttpAgentHandler handler)
@@ -2301,9 +2179,7 @@ public bool RemoveLLSDHandler(string path, LLSDMethod handler)
{
lock (m_llsdHandlers)
{
- LLSDMethod foundHandler;
-
- if (m_llsdHandlers.TryGetValue(path, out foundHandler) && foundHandler == handler)
+ if (m_llsdHandlers.TryGetValue(path, out LLSDMethod foundHandler) && foundHandler == handler)
{
m_llsdHandlers.Remove(path);
return true;
@@ -2410,7 +2286,7 @@ public void Write(object source, LogPrio priority, string message)
public class IndexPHPHandler : SimpleStreamHandler
{
- BaseHttpServer m_server;
+ readonly BaseHttpServer m_server;
public IndexPHPHandler(BaseHttpServer server)
: base("/index.php")
@@ -2421,7 +2297,7 @@ public IndexPHPHandler(BaseHttpServer server)
protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
httpResponse.KeepAlive = false;
- if (m_server == null || !m_server.HTTPDRunning)
+ if (m_server is null || !m_server.HTTPDRunning)
{
httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
return;
@@ -2434,17 +2310,19 @@ protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpRespon
}
if (httpRequest.QueryFlags.Contains("about"))
{
- httpResponse.Redirect("http://opensimulator.org/wiki/0.9.2.2_Release");
+ httpResponse.Redirect("http://opensimulator.org/wiki/0.9.3.0_Release");
return;
}
- if (!httpRequest.QueryAsDictionary.TryGetValue("method", out string methods) || string.IsNullOrWhiteSpace(methods))
+ if (!httpRequest.QueryAsDictionary.TryGetValue("method", out string method) || string.IsNullOrWhiteSpace(method))
{
- httpResponse.StatusCode = (int)HttpStatusCode.NotFound; ;
+ httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
- string[] splited = methods.Split(new char[] { ',' });
- string method = splited[0];
+ int indx = method.IndexOf(',');
+ if(indx > 0)
+ method = method[..indx];
+
if (string.IsNullOrWhiteSpace(method))
{
httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
@@ -2452,7 +2330,7 @@ protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpRespon
}
SimpleStreamMethod sh = m_server.TryGetIndexPHPMethodHandler(method);
- if (sh == null)
+ if (sh is null)
{
httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
return;
diff --git a/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpRequest.cs
index 62558f2b572..61fa8239a3d 100644
--- a/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpRequest.cs
@@ -32,7 +32,6 @@
using System.IO;
using System.Net;
using System.Text;
-using System.Web;
namespace OpenSim.Framework.Servers.HttpServer
{
@@ -43,7 +42,6 @@ public interface IOSHttpRequest
long ContentLength { get; }
long ContentLength64 { get; }
string ContentType { get; }
- HttpCookieCollection Cookies { get; }
bool HasEntityBody { get; }
NameValueCollection Headers { get; }
string HttpMethod { get; }
diff --git a/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs b/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs
index 7a128489d1d..d2e986fe88b 100644
--- a/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs
+++ b/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs
@@ -25,13 +25,9 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-using System;
-using System.Collections;
-using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
-using System.Web;
namespace OpenSim.Framework.Servers.HttpServer
{
diff --git a/OpenSim/Framework/Servers/HttpServer/JsonRpcRequestManager.cs b/OpenSim/Framework/Servers/HttpServer/JsonRpcRequestManager.cs
index c615961d9f3..4bd3a82b923 100644
--- a/OpenSim/Framework/Servers/HttpServer/JsonRpcRequestManager.cs
+++ b/OpenSim/Framework/Servers/HttpServer/JsonRpcRequestManager.cs
@@ -68,28 +68,30 @@ public JsonRpcRequestManager()
///
public bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
{
- if (jsonId == null)
+ if (jsonId is null)
throw new ArgumentNullException("jsonId");
- if (uri == null)
+ if (uri is null)
throw new ArgumentNullException("uri");
- if (method == null)
+ if (method is null)
throw new ArgumentNullException("method");
- if (parameters == null)
+ if (parameters is null)
throw new ArgumentNullException("parameters");
if(string.IsNullOrWhiteSpace(uri))
return false;
- OSDMap request = new OSDMap();
- request.Add("jsonrpc", OSD.FromString("2.0"));
- request.Add("id", OSD.FromString(jsonId));
- request.Add("method", OSD.FromString(method));
- request.Add("params", OSD.SerializeMembers(parameters));
+ OSDMap request = new()
+ {
+ { "jsonrpc", OSD.FromString("2.0") },
+ { "id", OSD.FromString(jsonId) },
+ { "method", OSD.FromString(method) },
+ { "params", OSD.SerializeMembers(parameters) }
+ };
- OSDMap response;
+ OSDMap outerResponse;
try
{
- response = WebUtil.PostToService(uri, request, 10000, true);
+ outerResponse = WebUtil.PostToService(uri, request, 10000, true);
}
catch (Exception e)
{
@@ -98,14 +100,13 @@ public bool JsonRpcRequest(ref object parameters, string method, string uri, str
}
OSD osdtmp;
- if (!response.TryGetValue("_Result", out osdtmp) || !(osdtmp is OSDMap))
+ if (!outerResponse.TryGetValue("_Result", out osdtmp) || (osdtmp is not OSDMap response))
{
m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an invalid response: {2}",
- method, uri, OSDParser.SerializeJsonString(response));
+ method, uri, OSDParser.SerializeJsonString(outerResponse));
return false;
}
- response = osdtmp as OSDMap;
if (response.TryGetValue("error", out osdtmp))
{
m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an error: {2}",
@@ -113,14 +114,14 @@ public bool JsonRpcRequest(ref object parameters, string method, string uri, str
return false;
}
- if (!response.TryGetValue("result", out osdtmp) || !(osdtmp is OSDMap))
+ if (!response.TryGetValue("result", out osdtmp) || (osdtmp is not OSDMap resultmap))
{
m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an invalid response: {2}",
method, uri, OSDParser.SerializeJsonString(response));
return false;
}
- OSD.DeserializeMembers(ref parameters, (OSDMap)osdtmp);
+ OSD.DeserializeMembers(ref parameters, resultmap);
return true;
}
@@ -147,16 +148,18 @@ public bool JsonRpcRequest(ref OSD data, string method, string uri, string jsonI
if (string.IsNullOrEmpty(jsonId))
jsonId = UUID.Random().ToString();
- OSDMap request = new OSDMap();
- request.Add("jsonrpc", OSD.FromString("2.0"));
- request.Add("id", OSD.FromString(jsonId));
- request.Add("method", OSD.FromString(method));
- request.Add("params", data);
+ OSDMap request = new()
+ {
+ { "jsonrpc", OSD.FromString("2.0") },
+ { "id", OSD.FromString(jsonId) },
+ { "method", OSD.FromString(method) },
+ { "params", data }
+ };
- OSDMap response;
+ OSDMap outerresponse;
try
{
- response = WebUtil.PostToService(uri, request, 10000, true);
+ outerresponse = WebUtil.PostToService(uri, request, 10000, true);
}
catch (Exception e)
{
@@ -165,13 +168,12 @@ public bool JsonRpcRequest(ref OSD data, string method, string uri, string jsonI
}
OSD osdtmp;
- if (!response.TryGetValue("_Result", out osdtmp) || !(osdtmp is OSDMap))
+ if (!outerresponse.TryGetValue("_Result", out osdtmp) || (osdtmp is not OSDMap response))
{
m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an invalid response: {2}",
- method, uri, OSDParser.SerializeJsonString(response));
+ method, uri, OSDParser.SerializeJsonString(outerresponse));
return false;
}
- response = osdtmp as OSDMap;
if (response.TryGetValue("error", out osdtmp))
{
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpRequest.cs
index f3487d8b9a2..7510e04469a 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpRequest.cs
@@ -33,99 +33,97 @@
using System.Net;
using System.Reflection;
using System.Text;
-using System.Web;
using OSHttpServer;
using log4net;
+using System.Runtime.CompilerServices;
+
namespace OpenSim.Framework.Servers.HttpServer
{
public class OSHttpRequest : IOSHttpRequest
{
- private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+ //private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- protected IHttpRequest m_request = null;
- protected IHttpClientContext m_context = null;
+ protected readonly IHttpRequest m_request = null;
public string[] AcceptTypes
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.AcceptTypes; }
}
public Encoding ContentEncoding
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_contentEncoding; }
}
private Encoding m_contentEncoding;
public long ContentLength
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.ContentLength; }
}
public long ContentLength64
{
- get { return ContentLength; }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return m_request.ContentLength; }
}
public string ContentType
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_contentType; }
}
private string m_contentType;
- public HttpCookieCollection Cookies
- {
- get
- {
- RequestCookies cookies = m_request.Cookies;
- HttpCookieCollection httpCookies = new HttpCookieCollection();
- if(cookies != null)
- {
- foreach (RequestCookie cookie in cookies)
- httpCookies.Add(new HttpCookie(cookie.Name, cookie.Value));
- }
- return httpCookies;
- }
- }
-
public bool HasEntityBody
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.ContentLength != 0; }
}
public NameValueCollection Headers
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.Headers; }
}
public string HttpMethod
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.Method; }
}
public Stream InputStream
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.Body; }
}
public bool IsSecured
{
- get { return m_context.IsSecured; }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return m_request.Context.IsSecured; }
}
public bool KeepAlive
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return ConnectionType.KeepAlive == m_request.Connection; }
}
public NameValueCollection QueryString
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.QueryString;}
}
private Hashtable m_queryAsHashtable = null;
public Hashtable Query
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (m_queryAsHashtable == null)
@@ -138,6 +136,7 @@ public Hashtable Query
private Dictionary _queryAsDictionay = null;
public Dictionary QueryAsDictionary
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_queryAsDictionay == null)
@@ -149,6 +148,7 @@ public Dictionary QueryAsDictionary
private HashSet m_queryFlags = null;
public HashSet QueryFlags
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (m_queryFlags == null)
@@ -163,48 +163,57 @@ public HashSet QueryFlags
public string RawUrl
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.Uri.AbsolutePath; }
}
public IPEndPoint RemoteIPEndPoint
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.RemoteIPEndPoint; }
}
public IPEndPoint LocalIPEndPoint
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.LocalIPEndPoint; }
}
public Uri Url
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.Uri; }
}
public string UriPath
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.UriPath; }
}
public string UserAgent
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_userAgent; }
}
private string m_userAgent;
public double ArrivalTS
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request.ArrivalTS;}
}
internal IHttpRequest IHttpRequest
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_request; }
}
internal IHttpClientContext IHttpClientContext
{
- get { return m_context; }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return m_request.Context; }
}
///
@@ -213,6 +222,7 @@ internal IHttpClientContext IHttpClientContext
///
internal Dictionary Whiteboard
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _whiteboard; }
}
private Dictionary _whiteboard = new Dictionary();
@@ -222,7 +232,6 @@ public OSHttpRequest() {}
public OSHttpRequest(IHttpRequest req)
{
m_request = req;
- m_context = req.Context;
if (null != req.Headers["content-encoding"])
{
@@ -241,12 +250,12 @@ public OSHttpRequest(IHttpRequest req)
if (null != req.Headers["user-agent"])
m_userAgent = req.Headers["user-agent"];
-// Form = new Hashtable();
-// foreach (HttpInputItem item in req.Form)
-// {
-// _log.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
-// Form.Add(item.Name, item.Value);
-// }
+ //Form = new Hashtable();
+ //foreach (HttpInputItem item in req.Form)
+ //{
+ // _log.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
+ // Form.Add(item.Name, item.Value);
+ //}
}
private void BuildQueryDictionary()
@@ -254,7 +263,7 @@ private void BuildQueryDictionary()
NameValueCollection q = m_request.QueryString;
_queryAsDictionay = new Dictionary();
m_queryFlags = new HashSet();
- for(int i = 0; i
public virtual string ContentType
{
- get
- {
- return _httpResponse.ContentType;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.ContentType; }
- set
- {
- _httpResponse.ContentType = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.ContentType = value; }
}
///
@@ -77,15 +74,11 @@ public virtual string ContentType
///
public long ContentLength
{
- get
- {
- return _httpResponse.ContentLength;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.ContentLength; }
- set
- {
- _httpResponse.ContentLength = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.ContentLength = value; }
}
///
@@ -93,7 +86,10 @@ public long ContentLength
///
public long ContentLength64
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return ContentLength; }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
set { ContentLength = value; }
}
@@ -102,31 +98,20 @@ public long ContentLength64
///
public Encoding ContentEncoding
{
- get
- {
- return _httpResponse.Encoding;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Encoding; }
- set
- {
- _httpResponse.Encoding = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.Encoding = value; }
}
public bool KeepAlive
{
- get
- {
- return _httpResponse.Connection == ConnectionType.KeepAlive;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Connection == ConnectionType.KeepAlive; }
- set
- {
- if (value)
- _httpResponse.Connection = ConnectionType.KeepAlive;
- else
- _httpResponse.Connection = ConnectionType.Close;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.Connection = value ? ConnectionType.KeepAlive : ConnectionType.Close; }
}
///
@@ -136,11 +121,10 @@ public bool KeepAlive
///
public int KeepAliveTimeout
{
- get
- {
- return _httpResponse.KeepAlive;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.KeepAlive; }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
if (value == 0)
@@ -148,7 +132,6 @@ public int KeepAliveTimeout
_httpResponse.Connection = ConnectionType.Close;
_httpResponse.KeepAlive = 0;
}
-
else
{
_httpResponse.Connection = ConnectionType.KeepAlive;
@@ -165,23 +148,17 @@ public int KeepAliveTimeout
///
public Stream OutputStream
{
- get
- {
- return _httpResponse.Body;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Body; }
}
public string ProtocolVersion
{
- get
- {
- return _httpResponse.ProtocolVersion;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.ProtocolVersion; }
- set
- {
- _httpResponse.ProtocolVersion = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.ProtocolVersion = value; }
}
///
@@ -189,58 +166,44 @@ public string ProtocolVersion
///
public Stream Body
{
- get
- {
- return _httpResponse.Body;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Body; }
}
public byte[] RawBuffer
{
- get
- {
- return _httpResponse.RawBuffer;
- }
- set
- {
- _httpResponse.RawBuffer = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.RawBuffer; }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.RawBuffer = value; }
}
public int RawBufferStart
{
- get
- {
- return _httpResponse.RawBufferStart;
- }
- set
- {
- _httpResponse.RawBufferStart = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.RawBufferStart; }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.RawBufferStart = value; }
}
public int RawBufferLen
{
- get
- {
- return _httpResponse.RawBufferLen;
- }
- set
- {
- _httpResponse.RawBufferLen = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.RawBufferLen; }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.RawBufferLen = value; }
}
public int Priority
{
- get
- {
- return _httpResponse.Priority;
- }
- set
- {
- _httpResponse.Priority = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Priority; }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.Priority = value; }
}
///
@@ -248,15 +211,11 @@ public int Priority
///
public bool SendChunked
{
- get
- {
- return _httpResponse.Chunked;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Chunked; }
- set
- {
- _httpResponse.Chunked = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.Chunked = value; }
}
///
@@ -264,20 +223,17 @@ public bool SendChunked
///
public virtual int StatusCode
{
- get
- {
- return (int)_httpResponse.Status;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return (int)_httpResponse.Status; }
- set
- {
- _httpResponse.Status = (HttpStatusCode)value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.Status = (HttpStatusCode)value; }
}
public double RequestTS
{
- get {return _httpResponse.RequestTS; }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.RequestTS; }
}
///
@@ -285,18 +241,14 @@ public double RequestTS
///
public string StatusDescription
{
- get
- {
- return _httpResponse.Reason;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return _httpResponse.Reason; }
- set
- {
- _httpResponse.Reason = value;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set { _httpResponse.Reason = value; }
}
- protected IHttpResponse _httpResponse;
+ protected readonly IHttpResponse _httpResponse;
public OSHttpResponse() {}
@@ -326,6 +278,7 @@ public OSHttpResponse(HttpResponse resp)
///
/// redirection target url
/// the response Status, must be Found, Redirect, Moved,MovedPermanently,RedirectKeepVerb, RedirectMethod, TemporaryRedirect. Defaults to Redirect
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Redirect(string url, HttpStatusCode redirStatusCode = HttpStatusCode.Redirect)
{
_httpResponse.Redirect(url, redirStatusCode);
@@ -338,6 +291,7 @@ public void Redirect(string url, HttpStatusCode redirStatusCode = HttpStatusCode
/// name
/// string containing the header field
/// value
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddHeader(string key, string value)
{
_httpResponse.AddHeader(key, value);
@@ -346,6 +300,7 @@ public void AddHeader(string key, string value)
///
/// Send the response back to the remote client
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Send()
{
_httpResponse.Chunked = false;
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/BodyEventArgs.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/BodyEventArgs.cs
index 91dec7945ab..a1ed60056ac 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/BodyEventArgs.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/BodyEventArgs.cs
@@ -3,53 +3,23 @@
namespace OSHttpServer.Parser
{
///
- /// Arguments used when more body bytes have come.
+ /// Arguments used when body bytes have come.
///
public class BodyEventArgs : EventArgs
{
///
- /// Initializes a new instance of the class.
+ /// Gets or sets buffer that contains the received bytes.
///
- /// buffer that contains the received bytes.
- /// offset in buffer where to start processing.
- /// number of bytes from that should be parsed.
- public BodyEventArgs(byte[] buffer, int offset, int count)
- {
- Buffer = buffer;
- Offset = offset;
- Count = count;
- }
+ public byte[] Buffer;
///
- /// Initializes a new instance of the class.
+ /// number of bytes from that should be parsed.
///
- public BodyEventArgs()
- {
- }
+ public int Count;
///
- /// Gets or sets buffer that contains the received bytes.
- ///
- public byte[] Buffer { get; set; }
- /*
- ///
- /// Gets or sets number of bytes used by the request.
- ///
- public int BytesUsed { get; set; }
- */
- ///
- /// Gets or sets number of bytes from that should be parsed.
- ///
- public int Count { get; set; }
- /*
- ///
- /// Gets or sets whether the body is complete.
- ///
- public bool IsBodyComplete { get; set; }
- */
- ///
- /// Gets or sets offset in buffer where to start processing.
+ /// offset in buffer where to start processing.
///
- public int Offset { get; set; }
+ public int Offset;
}
}
\ No newline at end of file
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ContextTimeoutManager.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ContextTimeoutManager.cs
index e2c3dc21391..bebe2fbb486 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ContextTimeoutManager.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ContextTimeoutManager.cs
@@ -43,12 +43,12 @@ public static class ContextTimeoutManager
/// Use a Thread or a Timer to monitor the ugly
///
private static Thread m_internalThread = null;
- private static object m_threadLock = new object();
- private static ConcurrentQueue m_contexts = new ConcurrentQueue();
- private static ConcurrentQueue m_highPrio = new ConcurrentQueue();
- private static ConcurrentQueue m_midPrio = new ConcurrentQueue();
- private static ConcurrentQueue m_lowPrio = new ConcurrentQueue();
- private static AutoResetEvent m_processWaitEven = new AutoResetEvent(false);
+ private static readonly object m_threadLock = new();
+ private static readonly ConcurrentQueue m_contexts = new();
+ private static readonly ConcurrentQueue m_highPrio = new();
+ private static readonly ConcurrentQueue m_midPrio = new();
+ private static readonly ConcurrentQueue m_lowPrio = new();
+ private static AutoResetEvent m_processWaitEven = new(false);
private static bool m_shuttingDown;
private static int m_ActiveSendingCount;
@@ -100,7 +100,7 @@ private static void ThreadRunProcess()
break;
double now = GetTimeStamp();
- if(m_contexts.Count > 0)
+ if(!m_contexts.IsEmpty)
{
ProcessSendQueues();
@@ -322,7 +322,7 @@ public static void EnqueueSend(HttpClientContext context, int priority)
default:
return;
}
- m_processWaitEven.Set();
+ m_processWaitEven?.Set();
}
public static void PulseWaitSend()
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HeaderEventArgs.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HeaderEventArgs.cs
index 23a57e97e2b..35bb894d3d8 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HeaderEventArgs.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HeaderEventArgs.cs
@@ -9,24 +9,6 @@ namespace OSHttpServer.Parser
public class HeaderEventArgs : EventArgs
{
public osUTF8Slice Name;
- public string Value;
-
- ///
- /// Initializes a new instance of the class.
- ///
- public HeaderEventArgs()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Name of header.
- /// Header value.
- public HeaderEventArgs(osUTF8Slice name, string value)
- {
- Name = name;
- Value = value;
- }
+ public osUTF8Slice Value;
}
}
\ No newline at end of file
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpClientContext.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpClientContext.cs
index cf636cede5d..70e7adfeaa0 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpClientContext.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpClientContext.cs
@@ -9,6 +9,7 @@
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using OpenMetaverse;
+using System.Threading.Tasks;
namespace OSHttpServer
{
@@ -26,7 +27,7 @@ public class HttpClientContext : IHttpClientContext, IDisposable
static private int basecontextID;
Queue m_requests;
- object m_requestsLock = new object();
+ readonly object m_requestsLock = new();
public int m_maxRequests = MAXREQUESTS;
public bool m_waitingResponse;
@@ -130,10 +131,10 @@ public HttpClientContext(bool secured, IPEndPoint remoteEndPoint,
{
SslStream _ssl = (SslStream)m_stream;
X509Certificate _cert1 = _ssl.RemoteCertificate;
- if (_cert1 != null)
+ if (_cert1 is not null)
{
- X509Certificate2 _cert2 = new X509Certificate2(_cert1);
- if (_cert2 != null)
+ X509Certificate2 _cert2 = new(_cert1);
+ if (_cert2 is not null)
SSLCommonName = _cert2.GetNameInfo(X509NameType.SimpleName, false);
}
}
@@ -150,7 +151,7 @@ public bool CanSend()
if (contextID < 0 || m_isClosing)
return false;
- if (m_stream == null || m_sock == null || !m_sock.Connected)
+ if (m_stream is null || m_sock is null || !m_sock.Connected)
return false;
return true;
@@ -182,14 +183,14 @@ protected virtual void OnHeaderReceived(object sender, HeaderEventArgs e)
Respond("HTTP/1.1", HttpStatusCode.Continue, null);
}
}
- m_currentRequest.AddHeader(e.Name.ToString(), e.Value);
+ m_currentRequest.AddHeader(e.Name.ToString(), e.Value.ToString());
}
private void OnRequestLine(object sender, RequestLineEventArgs e)
{
- m_currentRequest.Method = e.HttpMethod;
- m_currentRequest.HttpVersion = e.HttpVersion;
- m_currentRequest.UriPath = e.UriPath;
+ m_currentRequest.Method = e.HttpMethod.ToString();
+ m_currentRequest.HttpVersion = e.HttpVersion.ToString();
+ m_currentRequest.UriPath = e.UriPath.ToString();
m_currentRequest.AddHeader("remote_addr", LocalIPEndPoint.Address.ToString());
m_currentRequest.AddHeader("remote_port", LocalIPEndPoint.Port.ToString());
m_currentRequest.ArrivalTS = ContextTimeoutManager.GetTimeStamp();
@@ -208,14 +209,7 @@ private void OnRequestLine(object sender, RequestLineEventArgs e)
///
public virtual void Start()
{
- try
- {
- m_stream.BeginRead(m_ReceiveBuffer, 0, m_ReceiveBuffer.Length, OnReceive, null);
- }
- catch (IOException err)
- {
- LogWriter.Write(this, LogPrio.Debug, err.ToString());
- }
+ Task.Run(ReceiveLoop).ConfigureAwait(false);
}
///
@@ -230,7 +224,7 @@ public virtual void Cleanup()
contextID = -100;
- if (m_stream != null)
+ if (m_stream is not null)
{
m_stream.Close();
m_stream = null;
@@ -322,7 +316,7 @@ public void Disconnect(SocketError error)
{
try
{
- if (m_stream != null)
+ if (m_stream is not null)
{
if (error == SocketError.Success)
{
@@ -348,63 +342,58 @@ public void Disconnect(SocketError error)
}
}
- private void OnReceive(IAsyncResult ar)
+ private async void ReceiveLoop()
{
try
{
- int bytesRead = 0;
- if (m_stream == null)
- return;
- try
+ while (true)
{
- bytesRead = m_stream.EndRead(ar);
- }
- catch (NullReferenceException)
- {
- Disconnect(SocketError.ConnectionReset);
- return;
- }
+ if (m_stream == null || !m_stream.CanRead)
+ return;
- if (bytesRead == 0)
- {
- Disconnect(SocketError.Success);
- return;
- }
+ int bytesRead =
+ await m_stream.ReadAsync(m_ReceiveBuffer, m_ReceiveBytesLeft, m_ReceiveBuffer.Length - m_ReceiveBytesLeft).ConfigureAwait(false);
- if (m_isClosing)
- return;
+ if (bytesRead == 0)
+ {
+ Disconnect(SocketError.Success);
+ return;
+ }
- m_ReceiveBytesLeft += bytesRead;
+ if (m_isClosing)
+ return;
- int offset = m_parser.Parse(m_ReceiveBuffer, 0, m_ReceiveBytesLeft);
- if (m_stream == null)
- return; // "Connection: Close" in effect.
+ m_ReceiveBytesLeft += bytesRead;
- while (offset != 0)
- {
- int nextBytesleft = m_ReceiveBytesLeft - offset;
- if (nextBytesleft <= 0)
- break;
+ int offset = m_parser.Parse(m_ReceiveBuffer, 0, m_ReceiveBytesLeft);
+ if (m_stream is null)
+ return; // "Connection: Close" in effect.
- int nextOffset = m_parser.Parse(m_ReceiveBuffer, offset, nextBytesleft);
+ if(offset > 0)
+ {
+ int nextBytesleft, nextOffset;
+ while ((nextBytesleft = m_ReceiveBytesLeft - offset) > 0)
+ {
+ nextOffset = m_parser.Parse(m_ReceiveBuffer, offset, nextBytesleft);
- if (m_stream == null)
- return; // "Connection: Close" in effect.
+ if (m_stream is null)
+ return; // "Connection: Close" in effect.
- if (nextOffset == 0)
- break;
+ if (nextOffset == 0)
+ break;
- offset = nextOffset;
- }
+ offset = nextOffset;
+ }
+ }
- // copy unused bytes to the beginning of the array
- if (offset > 0 && m_ReceiveBytesLeft > offset)
- Buffer.BlockCopy(m_ReceiveBuffer, offset, m_ReceiveBuffer, 0, m_ReceiveBytesLeft - offset);
+ // copy unused bytes to the beginning of the array
+ if (offset > 0 && m_ReceiveBytesLeft > offset)
+ Buffer.BlockCopy(m_ReceiveBuffer, offset, m_ReceiveBuffer, 0, m_ReceiveBytesLeft - offset);
- m_ReceiveBytesLeft -= offset;
- if (StreamPassedOff)
- return; //?
- m_stream.BeginRead(m_ReceiveBuffer, m_ReceiveBytesLeft, m_ReceiveBuffer.Length - m_ReceiveBytesLeft, OnReceive, null);
+ m_ReceiveBytesLeft -= offset;
+ if (StreamPassedOff)
+ return; //?
+ }
}
catch (BadRequestException err)
{
@@ -437,8 +426,8 @@ private void OnReceive(IAsyncResult ar)
catch (IOException err)
{
LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
- if (err.InnerException is SocketException)
- Disconnect((SocketError)((SocketException)err.InnerException).ErrorCode);
+ if (err.InnerException is SocketException exception)
+ Disconnect((SocketError)exception.ErrorCode);
else
Disconnect(SocketError.ConnectionReset);
}
@@ -466,18 +455,18 @@ private void OnRequestCompleted(object source, EventArgs args)
FullRequestReceived = true;
LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
- if (m_maxRequests <= 0 || RequestReceived == null)
+ if (m_maxRequests <= 0 || RequestReceived is null)
return;
if (--m_maxRequests == 0)
m_currentRequest.Connection = ConnectionType.Close;
- if(m_currentRequest.Uri == null)
+ if(m_currentRequest.Uri is null)
{
// should not happen
try
{
- Uri uri = new Uri(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath);
+ Uri uri = new(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath);
m_currentRequest.Uri = uri;
m_currentRequest.UriPath = uri.AbsolutePath;
}
@@ -488,7 +477,7 @@ private void OnRequestCompleted(object source, EventArgs args)
}
// load cookies if they exist
- if(m_currentRequest.Headers["cookie"] != null)
+ if(m_currentRequest.Headers["cookie"] is not null)
m_currentRequest.SetCookies(new RequestCookies(m_currentRequest.Headers["cookie"]));
m_currentRequest.Body.Seek(0, SeekOrigin.Begin);
@@ -519,7 +508,7 @@ public void StartSendResponse(HttpResponse response)
public bool TrySendResponse(int bytesLimit)
{
- if (m_currentResponse == null)
+ if (m_currentResponse is null)
return false;
try
{
@@ -540,7 +529,7 @@ public bool TrySendResponse(int bytesLimit)
public void ContinueSendResponse()
{
- if(m_currentResponse == null)
+ if(m_currentResponse is null)
return;
LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
ContextTimeoutManager.EnqueueSend(this, m_currentResponse.Priority);
@@ -566,16 +555,16 @@ public void EndSendResponse(uint requestID, ConnectionType ctype)
}
else
{
- if (Stream == null || !Stream.CanWrite)
+ if (Stream is null || !Stream.CanWrite)
return;
LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
HttpRequest nextRequest = null;
lock (m_requestsLock)
{
- if (m_requests != null && m_requests.Count > 0)
+ if (m_requests is not null && m_requests.Count > 0)
nextRequest = m_requests.Dequeue();
- if (nextRequest != null && RequestReceived != null)
+ if (nextRequest is not null && RequestReceived is not null)
{
m_waitingResponse = true;
TriggerKeepalive = false;
@@ -583,7 +572,7 @@ public void EndSendResponse(uint requestID, ConnectionType ctype)
else
TriggerKeepalive = true;
}
- if (nextRequest != null)
+ if (nextRequest is not null)
RequestReceived?.Invoke(this, new RequestEventArgs(nextRequest));
}
ContextTimeoutManager.PulseWaitSend();
@@ -641,7 +630,7 @@ public void Respond(string httpVersion, HttpStatusCode statusCode, string reason
///
public bool Send(byte[] buffer)
{
- if (buffer == null)
+ if (buffer is null)
throw new ArgumentNullException("buffer");
return Send(buffer, 0, buffer.Length);
}
@@ -655,11 +644,11 @@ public bool Send(byte[] buffer)
///
///
- private object sendLock = new object();
+ private readonly object sendLock = new();
public bool Send(byte[] buffer, int offset, int size)
{
- if (m_stream == null || m_sock == null || !m_sock.Connected)
+ if (m_stream is null || m_sock is null || !m_sock.Connected)
return false;
if (offset + size > buffer.Length)
@@ -682,7 +671,7 @@ public bool Send(byte[] buffer, int offset, int size)
}
ContextTimeoutManager.ContextLeaveActiveSend();
- if (!ok && m_stream != null)
+ if (!ok && m_stream is not null)
Disconnect(SocketError.NoRecovery);
return ok;
}
@@ -693,14 +682,15 @@ private void SendAsyncEnd(IAsyncResult res)
try
{
m_stream.EndWrite(res);
+
ContextTimeoutManager.ContextLeaveActiveSend();
- didleave = true;
m_currentResponse.CheckSendNextAsyncContinue();
+ didleave = true;
}
catch (Exception e)
{
e.GetHashCode();
- if (m_stream != null)
+ if (m_stream is not null)
Disconnect(SocketError.NoRecovery);
}
if(!didleave)
@@ -709,7 +699,7 @@ private void SendAsyncEnd(IAsyncResult res)
public bool SendAsyncStart(byte[] buffer, int offset, int size)
{
- if (m_stream == null || m_sock == null || !m_sock.Connected)
+ if (m_stream is null || m_sock is null || !m_sock.Connected)
return false;
if (offset + size > buffer.Length)
@@ -728,7 +718,7 @@ public bool SendAsyncStart(byte[] buffer, int offset, int size)
ok = false;
}
- if (!ok && m_stream != null)
+ if (!ok && m_stream is not null)
Disconnect(SocketError.NoRecovery);
return ok;
}
@@ -758,7 +748,7 @@ public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing()
m_currentRequest = null;
m_currentResponse?.Clear();
m_currentResponse = null;
- if (m_requests != null)
+ if (m_requests is not null)
{
while (m_requests.Count > 0)
{
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpContextFactory.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpContextFactory.cs
index e6f4bd7c9da..eed59510aaa 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpContextFactory.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpContextFactory.cs
@@ -15,7 +15,7 @@ namespace OSHttpServer
///
public class HttpContextFactory : IHttpContextFactory
{
- private readonly ConcurrentDictionary m_activeContexts = new ConcurrentDictionary();
+ private readonly ConcurrentDictionary m_activeContexts = new();
private readonly ILogWriter m_logWriter;
///
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInput.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInput.cs
index e4701903a3c..939377158bb 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInput.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInput.cs
@@ -11,8 +11,8 @@ namespace OSHttpServer
public class HttpInput : IHttpInput
{
/// Representation of a non-initialized class instance
- public static readonly HttpInput Empty = new HttpInput("Empty", true);
- private readonly IDictionary _items = new Dictionary();
+ public static readonly HttpInput Empty = new("Empty", true);
+ private readonly Dictionary _items = new();
private string _name;
/// Variable telling the class that it is non-initialized
@@ -70,7 +70,7 @@ public string Name
/// Cannot add stuff to .
public void Add(string name, string value)
{
- if (name == null)
+ if (name is null)
throw new ArgumentNullException("name");
if (_ignoreChanges)
throw new InvalidOperationException("Cannot add stuff to HttpInput.Empty.");
@@ -80,16 +80,19 @@ public void Add(string name, string value)
int pos = name.IndexOf('[');
if (pos != -1)
{
- string name1 = name.Substring(0, pos);
+ string name1 = name[..pos];
string name2 = ExtractOne(name);
- if (!_items.ContainsKey(name1))
- _items.Add(name1, new HttpInputItem(name1, null));
- _items[name1].Add(name2, value);
+ if (!_items.TryGetValue(name1, out HttpInputItem it))
+ {
+ it = new HttpInputItem(name1, null);
+ _items.Add(name1, it);
+ }
+ it.Add(name2, value);
}
else
{
- if (_items.ContainsKey(name))
- _items[name].Add(value);
+ if (_items.TryGetValue(name, out HttpInputItem it))
+ it.Add(value);
else
_items.Add(name, new HttpInputItem(name, value));
}
@@ -115,7 +118,7 @@ public HttpInputItem this[string name]
/// True if the value exists
public bool Contains(string name)
{
- return _items.ContainsKey(name) && _items[name].Value != null;
+ return _items.TryGetValue(name, out HttpInputItem it) && it.Value is not null;
}
///
@@ -134,10 +137,12 @@ public static HttpInputItem ParseItem(string name, string value)
int pos = name.IndexOf('[');
if (pos != -1)
{
- string name1 = name.Substring(0, pos);
+ string name1 = name[..pos];
string name2 = ExtractOne(name);
- item = new HttpInputItem(name1, null);
- item.Add(name2, value);
+ item = new HttpInputItem(name1, null)
+ {
+ { name2, value }
+ };
}
else
item = new HttpInputItem(name, value);
@@ -166,7 +171,7 @@ public string ToString(bool asQueryString)
foreach (KeyValuePair item in _items)
temp += item.Value.ToString(null, true) + '&';
- return temp.Length > 0 ? temp.Substring(0, temp.Length - 1) : string.Empty;
+ return temp.Length > 0 ? temp[..^1] : string.Empty;
}
///
@@ -190,7 +195,7 @@ public static string ExtractOne(string value)
++pos;
int gotMore = value.IndexOf('[', pos + 1);
if (gotMore != -1)
- value = value.Substring(pos, gotMore - pos - 1) + value.Substring(gotMore);
+ value = string.Concat(value.AsSpan(pos, gotMore - pos - 1), value.AsSpan(gotMore));
else
value = value.Substring(pos, value.Length - pos - 1);
}
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInputItem.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInputItem.cs
index 2172c7da520..8ca7cde52b8 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInputItem.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpInputItem.cs
@@ -18,9 +18,9 @@ namespace OSHttpServer
public class HttpInputItem : IHttpInput
{
/// Representation of a non-initialized .
- public static readonly HttpInputItem Empty = new HttpInputItem(string.Empty, true);
+ public static readonly HttpInputItem Empty = new(string.Empty, true);
private readonly IDictionary _items = new Dictionary();
- private readonly List _values = new List();
+ private readonly List _values = new();
private string _name;
private readonly bool _ignoreChanges;
@@ -71,8 +71,9 @@ public int Count
/// if no item was found.
public HttpInputItem this[string name]
{
- get {
- return _items.ContainsKey(name) ? _items[name] : Empty;
+ get
+ {
+ return _items.TryGetValue(name, out HttpInputItem hii) ? hii : Empty;
}
}
@@ -109,7 +110,7 @@ public string LastValue
{
get
{
- return _values.Count == 0 ? null : _values[_values.Count - 1];
+ return _values.Count == 0 ? null : _values[^1];
}
}
@@ -129,7 +130,7 @@ public IList Values
/// Cannot add stuff to .
public void Add(string value)
{
- if (value == null)
+ if (value is null)
return;
if (_ignoreChanges)
throw new InvalidOperationException("Cannot add stuff to HttpInput.Empty.");
@@ -144,7 +145,7 @@ public void Add(string value)
/// true if the sub-item exists and has a value; otherwise false.
public bool Contains(string name)
{
- return _items.ContainsKey(name) && _items[name].Value != null;
+ return _items.TryGetValue(name, out HttpInputItem hii) && hii.Value != null;
}
/// Returns a formatted representation of the instance with the values of all contained parameters
@@ -185,7 +186,7 @@ public string ToString(string prefix, bool asQuerySting)
foreach (KeyValuePair item in _items)
temp += item.Value.ToString(name, true) + '&';
- return _items.Count > 0 ? temp.Substring(0, temp.Length - 1) : temp;
+ return _items.Count > 0 ? temp[..^1] : temp;
}
else
{
@@ -216,7 +217,7 @@ HttpInputItem IHttpInput.this[string name]
{
get
{
- return _items.ContainsKey(name) ? _items[name] : Empty;
+ return _items.TryGetValue(name, out HttpInputItem hii) ? hii : Empty;
}
}
@@ -239,11 +240,15 @@ public void Add(string name, string value)
int pos = name.IndexOf('[');
if (pos != -1)
{
- string name1 = name.Substring(0, pos);
+ string name1 = name[..pos];
string name2 = HttpInput.ExtractOne(name);
- if (!_items.ContainsKey(name1))
- _items.Add(name1, new HttpInputItem(name1, null));
- _items[name1].Add(name2, value);
+ if (!_items.TryGetValue(name1, out HttpInputItem it))
+ {
+ it = new HttpInputItem(name1, null);
+ _items.Add(name1, it);
+ }
+ it.Add(name2, value);
+
/*
HttpInputItem item = HttpInput.ParseItem(name, value);
@@ -256,8 +261,8 @@ public void Add(string name, string value)
}
else
{
- if (_items.ContainsKey(name))
- _items[name].Add(value);
+ if (_items.TryGetValue(name, out HttpInputItem it2))
+ it2.Add(value);
else
_items.Add(name, new HttpInputItem(name, value));
}
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpListener.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpListener.cs
index f48dfdae857..4be06324c1d 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpListener.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpListener.cs
@@ -5,6 +5,8 @@
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
+using System.Threading.Tasks;
+using System.Runtime.CompilerServices;
namespace OSHttpServer
{
@@ -14,16 +16,13 @@ public class OSHttpListener: IDisposable
private readonly X509Certificate m_certificate;
private readonly IHttpContextFactory m_contextFactory;
private readonly int m_port;
- private readonly ManualResetEvent m_shutdownEvent = new ManualResetEvent(false);
-#if NET48
- private readonly SslProtocols m_sslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13 | SslProtocols.Ssl3 | SslProtocols.Ssl2;
-#else
- private readonly SslProtocols m_sslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Ssl3 | SslProtocols.Ssl2;
-#endif
+ private readonly ManualResetEvent m_shutdownEvent = new(false);
+ private readonly SslProtocols m_sslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
+
private TcpListener m_listener;
private ILogWriter m_logWriter = NullLogWriter.Instance;
- private int m_pendingAccepts;
private bool m_shutdown;
+ public readonly CancellationTokenSource m_CancellationSource = new();
protected RemoteCertificateValidationCallback m_clientCertValCallback = null;
public event EventHandler Accepted;
@@ -67,8 +66,7 @@ protected OSHttpListener(IPAddress address, int port, X509Certificate certificat
/// Factory used to create es.
/// Certificate to use
/// which HTTPS protocol to use, default is TLS.
- protected OSHttpListener(IPAddress address, int port, X509Certificate certificate,
- SslProtocols protocols)
+ protected OSHttpListener(IPAddress address, int port, X509Certificate certificate, SslProtocols protocols)
: this(address, port)
{
m_certificate = certificate;
@@ -90,6 +88,7 @@ public static OSHttpListener Create(IPAddress address, int port, X509Certificate
return new OSHttpListener(address, port, certificate, protocols);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
private void OnRequestReceived(object sender, RequestEventArgs e)
{
RequestReceived?.Invoke(sender, e);
@@ -112,11 +111,10 @@ public ILogWriter LogWriter
set
{
m_logWriter = value ?? NullLogWriter.Instance;
- if (m_certificate != null)
- m_logWriter.Write(this, LogPrio.Info,
- "HTTPS(" + m_sslProtocols + ") listening on " + m_address + ":" + m_port);
+ if (m_certificate is not null)
+ m_logWriter.Write(this, LogPrio.Info, $"HTTPS({m_sslProtocols}) listening on {m_address}:{m_port}");
else
- m_logWriter.Write(this, LogPrio.Info, "HTTP listening on " + m_address + ":" + m_port);
+ m_logWriter.Write(this, LogPrio.Info, $"HTTP listening on {m_address}:{m_port}");
}
}
@@ -125,76 +123,53 @@ public ILogWriter LogWriter
///
public bool UseTraceLogs { get; set; }
-
- /// Exception.
- private void OnAccept(IAsyncResult ar)
+ private async void AcceptLoop()
{
- bool beginAcceptCalled = false;
try
{
- int count = Interlocked.Decrement(ref m_pendingAccepts);
- if (m_shutdown)
+ while (true)
{
- if (count == 0)
+ if (m_shutdown)
+ {
m_shutdownEvent.Set();
- return;
- }
-
- Interlocked.Increment(ref m_pendingAccepts);
- m_listener.BeginAcceptSocket(OnAccept, null);
- beginAcceptCalled = true;
- Socket socket = m_listener.EndAcceptSocket(ar);
- if (!socket.Connected)
- {
- socket.Dispose();
- return;
- }
-
- socket.NoDelay = true;
-
- if (!OnAcceptingSocket(socket))
- {
- socket.Disconnect(true);
- return;
- }
-
- if(socket.Connected)
- {
- m_logWriter.Write(this, LogPrio.Debug, "Accepted connection from: " + socket.RemoteEndPoint);
-
- if (m_certificate != null)
- m_contextFactory.CreateSecureContext(socket, m_certificate, m_sslProtocols, m_clientCertValCallback);
+ break;
+ }
+
+ Socket socket = await m_listener.AcceptSocketAsync(m_CancellationSource.Token).ConfigureAwait(false); ;
+ if (!socket.Connected)
+ {
+ socket.Dispose();
+ continue;
+ }
+
+ socket.NoDelay = true;
+
+ if (!OnAcceptingSocket(socket))
+ {
+ socket.Disconnect(true);
+ continue;
+ }
+ if (socket.Connected)
+ {
+ m_logWriter.Write(this, LogPrio.Debug, $"Accepted connection from: {socket.RemoteEndPoint}");
+
+ if (m_certificate is not null)
+ m_contextFactory.CreateSecureContext(socket, m_certificate, m_sslProtocols, m_clientCertValCallback);
+ else
+ m_contextFactory.CreateContext(socket);
+ }
else
- m_contextFactory.CreateContext(socket);
+ socket.Dispose();
}
- else
- socket.Dispose();
- }
- catch (Exception err)
- {
- m_logWriter.Write(this, LogPrio.Debug, err.Message);
- ExceptionThrown?.Invoke(this, err);
-
- if (!beginAcceptCalled)
- RetryBeginAccept();
}
- }
-
- ///
- /// Will try to accept connections one more time.
- ///
- /// If any exceptions is thrown.
- private void RetryBeginAccept()
- {
- try
+ catch (OperationCanceledException)
{
- m_logWriter.Write(this, LogPrio.Error, "Trying to accept connections again.");
- m_listener.BeginAcceptSocket(OnAccept, null);
+ m_shutdownEvent.Set();
}
catch (Exception err)
{
- m_logWriter.Write(this, LogPrio.Fatal, err.Message);
- ExceptionThrown?.Invoke(this, err);
+ m_logWriter.Write(this, LogPrio.Debug, err.Message);
+ ExceptionThrown?.Invoke(this, err);
}
}
@@ -207,7 +182,7 @@ protected bool OnAcceptingSocket(Socket socket)
{
if(Accepted!=null)
{
- ClientAcceptedEventArgs args = new ClientAcceptedEventArgs(socket);
+ ClientAcceptedEventArgs args = new(socket);
Accepted?.Invoke(this, args);
return !args.Revoked;
}
@@ -226,8 +201,7 @@ public void Start(int backlog)
m_listener = new TcpListener(m_address, m_port);
m_listener.Start(backlog);
- Interlocked.Increment(ref m_pendingAccepts);
- m_listener.BeginAcceptSocket(OnAccept, null);
+ Task.Run(AcceptLoop).ConfigureAwait(false);
}
///
@@ -237,10 +211,11 @@ public void Start(int backlog)
public void Stop()
{
m_shutdown = true;
+ m_CancellationSource.Cancel();
m_contextFactory.Shutdown();
- m_listener.Stop();
if (!m_shutdownEvent.WaitOne())
m_logWriter.Write(this, LogPrio.Error, "Failed to shutdown listener properly.");
+ m_listener.Stop();
m_listener = null;
Dispose();
}
@@ -256,6 +231,7 @@ protected void Dispose(bool disposing)
if (m_shutdownEvent != null)
{
m_shutdownEvent.Dispose();
+ m_CancellationSource.Dispose();
}
}
}
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequest.cs
index a0bdaeceec0..39282af878c 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequest.cs
@@ -2,8 +2,8 @@
using System.Collections.Specialized;
using System.IO;
using System.Net;
-using System.Text;
using System.Web;
+using OpenSim.Framework;
using OSHttpServer.Exceptions;
@@ -21,8 +21,8 @@ public class HttpRequest : IHttpRequest
public static readonly char[] UriSplitters = new[] { '/' };
public static uint baseID = 0;
- private readonly NameValueCollection m_headers = new NameValueCollection();
- private readonly HttpParam m_param = new HttpParam(HttpInput.Empty, HttpInput.Empty);
+ private readonly NameValueCollection m_headers = new();
+ //private readonly HttpParam m_param = new(HttpInput.Empty, HttpInput.Empty);
private Stream m_body = new MemoryStream();
private int m_bodyBytesLeft;
private ConnectionType m_connection = ConnectionType.KeepAlive;
@@ -150,9 +150,9 @@ public NameValueCollection QueryString
{
get
{
- if(m_queryString == null)
+ if(m_queryString is null)
{
- if(m_uri == null || m_uri.Query.Length == 0)
+ if(m_uri is null || m_uri.Query.Length == 0)
m_queryString = new NameValueCollection();
else
{
@@ -168,7 +168,7 @@ public NameValueCollection QueryString
}
}
- public static readonly Uri EmptyUri = new Uri("http://localhost/");
+ public static readonly Uri EmptyUri = new("http://localhost/");
///
/// Gets or sets requested URI.
///
@@ -178,6 +178,7 @@ public Uri Uri
set { m_uri = value ?? EmptyUri; } // not safe
}
+ /*
///
/// Gets parameter from or .
///
@@ -185,6 +186,7 @@ public HttpParam Param
{
get { return m_param; }
}
+ */
///
/// Gets form parameters.
@@ -218,16 +220,18 @@ public object Clone()
{
// this method was mainly created for testing.
// dont use it that much...
- var request = new HttpRequest(Context);
- request.Method = m_method;
+ var request = new HttpRequest(Context)
+ {
+ Method = m_method,
+ m_httpVersion = m_httpVersion,
+ m_queryString = m_queryString,
+ Uri = m_uri
+ };
if (AcceptTypes != null)
{
request.AcceptTypes = new string[AcceptTypes.Length];
AcceptTypes.CopyTo(request.AcceptTypes, 0);
}
- request.m_httpVersion = m_httpVersion;
- request.m_queryString = m_queryString;
- request.Uri = m_uri;
var buffer = new byte[m_body.Length];
m_body.Read(buffer, 0, (int)m_body.Length);
@@ -295,8 +299,7 @@ public IPEndPoint RemoteIPEndPoint
}
}
}
- if (m_remoteIPEndPoint == null)
- m_remoteIPEndPoint = m_context.LocalIPEndPoint;
+ m_remoteIPEndPoint ??= m_context.LocalIPEndPoint;
return m_remoteIPEndPoint;
}
@@ -362,7 +365,7 @@ public void AddHeader(string name, string value)
break;
case "forwarded":
- string[] parts = value.Split(new char[]{';'});
+ string[] parts = value.Split(Util.SplitSemicolonArray);
string addr = string.Empty;
for(int i = 0; i < parts.Length; ++i)
{
@@ -374,7 +377,7 @@ public void AddHeader(string name, string value)
int indx = s.IndexOf("=", 3);
if(indx < 0 || indx >= s.Length - 1)
continue;
- s = s.Substring(indx);
+ s = s[indx..];
addr = s.Trim();
}
}
@@ -386,7 +389,7 @@ public void AddHeader(string name, string value)
case "x-forwarded-for":
if (value.Length > 7)
{
- string[] xparts = value.Split(new char[]{','});
+ string[] xparts = value.Split(Util.SplitCommaArray);
if(xparts.Length > 0)
{
string xs = xparts[0].Trim();
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequestParser.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequestParser.cs
index f63a30fb348..c5d7f6c2b22 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequestParser.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpRequestParser.cs
@@ -1,5 +1,4 @@
using System;
-using System.Text;
using OSHttpServer.Exceptions;
using OpenMetaverse;
@@ -11,11 +10,11 @@ namespace OSHttpServer.Parser
public class HttpRequestParser : IHttpRequestParser
{
private ILogWriter m_log;
- private readonly HeaderEventArgs m_headerArgs = new HeaderEventArgs();
- private readonly BodyEventArgs m_bodyEventArgs = new BodyEventArgs();
- private readonly RequestLineEventArgs m_requestLineArgs = new RequestLineEventArgs();
- private osUTF8Slice m_curHeaderName = new osUTF8Slice();
- private osUTF8Slice m_curHeaderValue = new osUTF8Slice();
+ private readonly HeaderEventArgs m_headerArgs = new();
+ private readonly BodyEventArgs m_bodyEventArgs = new();
+ private readonly RequestLineEventArgs m_requestLineArgs = new();
+ private osUTF8Slice m_curHeaderName = new();
+ private osUTF8Slice m_curHeaderValue = new();
private int m_bodyBytesLeft;
///
@@ -68,7 +67,7 @@ private int AddToBody(byte[] buffer, int offset, int count)
if (m_bodyBytesLeft == 0)
{
// got a complete request.
- m_log.Write(this, LogPrio.Trace, "Request parsed successfully.");
+ m_log.Write(this, LogPrio.Trace, "Request parsed successfully");
OnRequestCompleted();
Clear();
}
@@ -102,56 +101,60 @@ public ILogWriter LogWriter
///
/// If line is incorrect
/// Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF"
- protected void OnFirstLine(string value)
+ protected void OnFirstLine(osUTF8Slice value)
{
//
//todo: In the interest of robustness, servers SHOULD ignore any empty line(s) received where a Request-Line is expected.
// In other words, if the server is reading the protocol stream at the beginning of a message and receives a CRLF first, it should ignore the CRLF.
//
- m_log.Write(this, LogPrio.Debug, "Got request: " + value);
+ m_log.Write(this, LogPrio.Debug, $"Got request: {value}");
//Request-Line = Method SP Request-URI SP HTTP-Version CRLF
- int pos = value.IndexOf(' ');
- if (pos == -1 || pos + 1 >= value.Length)
+ int pos = value.IndexOf((byte)' ');
+ int oldPos = pos + 1;
+ if (pos == -1 || oldPos >= value.Length)
{
- m_log.Write(this, LogPrio.Warning, "Invalid request line, missing Method. Line: " + value);
- throw new BadRequestException("Invalid request line, missing Method. Line: " + value);
+ m_log.Write(this, LogPrio.Warning, $"Invalid request line, missing Method. Line: {value}");
+ throw new BadRequestException($"Invalid request line, missing Method. Line: {value}");
}
- string method = value.Substring(0, pos).ToUpper();
- int oldPos = pos + 1;
- pos = value.IndexOf(' ', oldPos);
+ osUTF8Slice method = value.SubUTF8(0, pos);
+ value.SubUTF8Self(oldPos);
+ pos = value.IndexOf((byte)' ');
if (pos == -1)
{
- m_log.Write(this, LogPrio.Warning, "Invalid request line, missing URI. Line: " + value);
- throw new BadRequestException("Invalid request line, missing URI. Line: " + value);
+ m_log.Write(this, LogPrio.Warning, "Invalid request line, missing URI");
+ throw new BadRequestException("Invalid request line, missing URI");
}
- string path = value.Substring(oldPos, pos - oldPos);
- if (path.Length > 4196)
- throw new BadRequestException("Too long URI.");
- if (path == "*")
- throw new BadRequestException("Not supported URI.");
+ if(pos > 4196)
+ throw new BadRequestException("URI too long");
- if (pos + 1 >= value.Length)
+ osUTF8Slice path = value.SubUTF8(0, pos);
+ if (path.ACSIILowerEquals("*"))
+ throw new BadRequestException("URI not supported");
+
+ oldPos = pos + 1;
+ if (oldPos >= value.Length)
{
- m_log.Write(this, LogPrio.Warning, "Invalid request line, missing HTTP-Version. Line: " + value);
- throw new BadRequestException("Invalid request line, missing HTTP-Version. Line: " + value);
+ m_log.Write(this, LogPrio.Warning, $"Invalid request line, missing HTTP-Version. Line: {value}");
+ throw new BadRequestException($"Invalid request line, missing HTTP-Version. Line: {value}");
}
- string version = value.Substring(pos + 1);
- if (version.Length < 4 || string.Compare(version.Substring(0, 4), "HTTP", true) != 0)
+ osUTF8Slice version = value.SubUTF8(oldPos);
+ if (version.Length < 4 || !version.SubUTF8(0,4).ACSIILowerEquals("http"))
{
- m_log.Write(this, LogPrio.Warning, "Invalid HTTP version in request line. Line: " + value);
- throw new BadRequestException("Invalid HTTP version in Request line. Line: " + value);
+ m_log.Write(this, LogPrio.Warning, $"Invalid HTTP version in request line. Line: {value}");
+ throw new BadRequestException($"Invalid HTTP version in Request line. Line: {value}");
}
- if(RequestLineReceived != null)
+ if(RequestLineReceived is not null)
{
+ method.ToASCIIUpperSelf();
m_requestLineArgs.HttpMethod = method;
m_requestLineArgs.HttpVersion = version;
m_requestLineArgs.UriPath = path;
RequestLineReceived?.Invoke(this, m_requestLineArgs);
- }
+ }
}
private static readonly byte[] OSUTF8contentlength = osUTF8.GetASCIIBytes("content-length");
@@ -174,7 +177,7 @@ protected void OnHeader()
if (HeaderReceived != null)
{
m_headerArgs.Name = m_curHeaderName;
- m_headerArgs.Value = m_curHeaderValue.ToString();
+ m_headerArgs.Value = m_curHeaderValue;
HeaderReceived?.Invoke(this, m_headerArgs);
}
@@ -255,7 +258,7 @@ public int Parse(byte[] buffer, int offset, int count)
else if(ch == '\r' || ch == '\n')
{
int size = GetLineBreakSize(buffer, currentPos);
- OnFirstLine(Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos));
+ OnFirstLine(new osUTF8Slice(buffer, startPos, currentPos - startPos));
currentPos += size - 1;
handledBytes = currentPos + 1;
startPos = -1;
@@ -269,7 +272,7 @@ public int Parse(byte[] buffer, int offset, int count)
if (m_bodyBytesLeft == 0)
{
CurrentState = RequestParserState.FirstLine;
- m_log.Write(this, LogPrio.Trace, "Request parsed successfully (no content).");
+ m_log.Write(this, LogPrio.Trace, "Request parsed successfully (no content)");
OnRequestCompleted();
Clear();
return currentPos;
@@ -288,9 +291,8 @@ public int Parse(byte[] buffer, int offset, int count)
{
if (startPos == -1)
{
- m_log.Write(this, LogPrio.Warning,
- "Expected header name, got colon on line " + currentLine);
- throw new BadRequestException("Expected header name, got colon on line " + currentLine);
+ m_log.Write(this, LogPrio.Warning, $"Expected header name, got colon on line {currentLine}");
+ throw new BadRequestException($"Expected header name, got colon on line {currentLine}");
}
m_curHeaderName = new osUTF8Slice(buffer, startPos, currentPos - startPos);
handledBytes = currentPos + 1;
@@ -302,15 +304,15 @@ public int Parse(byte[] buffer, int offset, int count)
}
else if (!char.IsLetterOrDigit(ch) && ch != '-')
{
- m_log.Write(this, LogPrio.Warning, "Invalid character in header name on line " + currentLine);
- throw new BadRequestException("Invalid character in header name on line " + currentLine);
+ m_log.Write(this, LogPrio.Warning, $"Invalid character in header name on line {currentLine}");
+ throw new BadRequestException($"Invalid character in header name on line {currentLine}");
}
if (startPos == -1)
startPos = currentPos;
else if (currentPos - startPos > 200)
{
- m_log.Write(this, LogPrio.Warning, "Invalid header name on line " + currentLine);
- throw new BadRequestException("Invalid header name on line " + currentLine);
+ m_log.Write(this, LogPrio.Warning, $"Invalid header name on line {currentLine}");
+ throw new BadRequestException($"Invalid header name on line {currentLine}");
}
break;
case RequestParserState.AfterName:
@@ -332,21 +334,22 @@ public int Parse(byte[] buffer, int offset, int count)
{
if (currentPos - startPos > 256)
{
- m_log.Write(this, LogPrio.Warning, "header value too far" + currentLine);
- throw new BadRequestException("header value too far" + currentLine);
+ m_log.Write(this, LogPrio.Warning, $"header value too far {currentLine}");
+ throw new BadRequestException($"header value too far {currentLine}");
}
}
else
{
int newLineSize = GetLineBreakSize(buffer, currentPos);
- if (newLineSize > 0 && currentPos + newLineSize < endOfBufferPos &&
- char.IsWhiteSpace((char)buffer[currentPos + newLineSize]))
+ int tsize = currentPos + newLineSize;
+ if (newLineSize > 0 && tsize < endOfBufferPos &&
+ char.IsWhiteSpace((char)buffer[tsize]))
{
if (currentPos - startPos > 256)
{
- m_log.Write(this, LogPrio.Warning, "header value too" + currentLine);
- throw new BadRequestException("header value too far" + currentLine);
- }
+ m_log.Write(this, LogPrio.Warning, $"header value too far {currentLine}");
+ throw new BadRequestException($"header value too far {currentLine}");
+ }
++currentPos;
}
else
@@ -363,23 +366,23 @@ public int Parse(byte[] buffer, int offset, int count)
if (ch == '\r' || ch == '\n')
{
if (m_curHeaderName.Length == 0)
- throw new BadRequestException("Missing header on line " + currentLine);
-
+ throw new BadRequestException($"Missing header on line {currentLine}");
+
if (currentPos - startPos > 8190)
{
- m_log.Write(this, LogPrio.Warning, "Too large header value on line " + currentLine);
- throw new BadRequestException("Too large header value on line " + currentLine);
+ m_log.Write(this, LogPrio.Warning, $"Too large header value on line {currentLine}");
+ throw new BadRequestException($"Too large header value on line {currentLine}");
}
// Header fields can be extended over multiple lines by preceding each extra line with at
// least one SP or HT.
int newLineSize = GetLineBreakSize(buffer, currentPos);
- if (endOfBufferPos > currentPos + newLineSize
- && (buffer[currentPos + newLineSize] == ' ' || buffer[currentPos + newLineSize] == '\t'))
+ int tnext = currentPos + newLineSize;
+ if (endOfBufferPos > tnext && (buffer[tnext] == ' ' || buffer[tnext] == '\t'))
{
if (startPos != -1)
{
- osUTF8Slice osUTF8SliceTmp = new osUTF8Slice(buffer, startPos, currentPos - startPos);
+ osUTF8Slice osUTF8SliceTmp = new(buffer, startPos, currentPos - startPos);
if (m_curHeaderValue.Length == 0)
m_curHeaderValue = osUTF8SliceTmp.Clone();
else
@@ -393,13 +396,13 @@ public int Parse(byte[] buffer, int offset, int count)
}
else
{
- osUTF8Slice osUTF8SliceTmp = new osUTF8Slice(buffer, startPos, currentPos - startPos);
+ osUTF8Slice osUTF8SliceTmp = new(buffer, startPos, currentPos - startPos);
if (m_curHeaderValue.Length == 0)
m_curHeaderValue = osUTF8SliceTmp.Clone();
else
m_curHeaderValue.Append(osUTF8SliceTmp);
- m_log.Write(this, LogPrio.Trace, "Header [" + m_curHeaderName + ": " + m_curHeaderValue + "]");
+ m_log.Write(this, LogPrio.Trace, $"Header [{m_curHeaderName}:{m_curHeaderValue}]");
OnHeader();
@@ -432,23 +435,23 @@ public int Parse(byte[] buffer, int offset, int count)
return handledBytes;
}
- int GetLineBreakSize(byte[] buffer, int offset)
+ static int GetLineBreakSize(byte[] buffer, int offset)
{
- if (buffer[offset] == '\r')
+ byte c = buffer[offset];
+ if (c == '\r')
{
- if (buffer.Length > offset + 1 && buffer[offset + 1] == '\n')
+ ++offset;
+ if (buffer.Length > offset && buffer[offset] == '\n')
return 2;
else
throw new BadRequestException("Got invalid linefeed.");
}
- else if (buffer[offset] == '\n')
+ else if (c == '\n')
{
- if (buffer.Length == offset + 1)
+ ++offset;
+ if (buffer.Length == offset)
return 1; // linux line feed
- if (buffer[offset + 1] != '\r')
- return 1; // linux line feed
- else
- return 2; // win line feed
+ return buffer[offset] == '\r' ? 2 : 1;
}
else
return 0;
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpResponse.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpResponse.cs
index 73f87998f69..e1c5f6eac98 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpResponse.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/HttpResponse.cs
@@ -11,8 +11,8 @@ public class HttpResponse : IHttpResponse
{
private const string DefaultContentType = "text/html;charset=UTF-8";
private readonly IHttpClientContext m_context;
- private readonly ResponseCookies m_cookies = new ResponseCookies();
- private readonly NameValueCollection m_headers = new NameValueCollection();
+ private readonly ResponseCookies m_cookies = new();
+ private readonly NameValueCollection m_headers = new();
private string m_httpVersion;
private Stream m_body;
private long m_contentLength;
@@ -25,7 +25,7 @@ public class HttpResponse : IHttpResponse
public int RawBufferLen { get; set; }
public double RequestTS { get; private set; }
- internal byte[] m_headerBytes = null;
+ internal osUTF8 m_headerBytes = null;
///
/// Initializes a new instance of the class.
@@ -86,8 +86,7 @@ public Stream Body
{
get
{
- if(m_body == null)
- m_body = new MemoryStream();
+ m_body ??= new MemoryStream();
return m_body;
}
}
@@ -229,55 +228,65 @@ public void AddHeader(string name, string value)
m_headers[name] = value;
}
- public byte[] GetHeaders()
+ public void GetHeaders()
{
HeadersSent = true;
- var sb = osStringBuilderCache.Acquire();
+ osUTF8 osu = OSUTF8Cached.Acquire(8 * 1024);
- if(string.IsNullOrWhiteSpace(m_httpVersion))
- sb.AppendFormat("HTTP/1.1 {0} {1}\r\n", (int)Status,
- string.IsNullOrEmpty(Reason) ? Status.ToString() : Reason);
+ if (string.IsNullOrWhiteSpace(m_httpVersion))
+ {
+ osu.AppendASCII($"HTTP/1.1 {(int)Status} ");
+ if (string.IsNullOrEmpty(Reason))
+ osu.AppendASCII($"{Status}");
+ else
+ osu.Append($"{Reason}");
+ osu.AppendASCII("\r\n");
+ }
else
- sb.AppendFormat("{0} {1} {2}\r\n", m_httpVersion, (int)Status,
- string.IsNullOrEmpty(Reason) ? Status.ToString() : Reason);
+ {
+ osu.AppendASCII($"{m_httpVersion} {(int)Status} ");
+ if (string.IsNullOrEmpty(Reason))
+ osu.AppendASCII($"{Status}");
+ else
+ osu.Append($"{Reason}");
+ osu.AppendASCII("\r\n");
+ }
- sb.AppendFormat("Date: {0}\r\n", DateTime.Now.ToString("r"));
+ osu.AppendASCII($"Date: {DateTime.Now:r}\r\n");
- long len = 0;
- if(m_body!= null)
- len = m_body.Length;
- if (RawBuffer != null && RawBufferLen > 0)
+ long len = m_body is null ? 0 : m_body.Length;
+ if (RawBuffer is not null)
len += RawBufferLen;
- sb.AppendFormat("Content-Length: {0}\r\n", len);
+ osu.AppendASCII($"Content-Length: {len}\r\n");
- if (m_headers["Content-Type"] == null)
- sb.AppendFormat("Content-Type: {0}\r\n", m_contentType ?? DefaultContentType);
+ if (m_headers["Content-Type"] is null)
+ osu.AppendASCII($"Content-Type: {m_contentType ?? DefaultContentType}\r\n");
- switch(Status)
+ switch (Status)
{
case HttpStatusCode.OK:
case HttpStatusCode.PartialContent:
case HttpStatusCode.Accepted:
case HttpStatusCode.Continue:
case HttpStatusCode.Found:
- {
- int keepaliveS = m_context.TimeoutKeepAlive / 1000;
- if (Connection == ConnectionType.KeepAlive && keepaliveS > 0 && m_context.MaxRequests > 0)
{
- sb.AppendFormat("Keep-Alive:timeout={0}, max={1}\r\n", keepaliveS, m_context.MaxRequests);
- sb.Append("Connection: Keep-Alive\r\n");
- }
- else
- {
- sb.Append("Connection: close\r\n");
- Connection = ConnectionType.Close;
+ int keepaliveS = m_context.TimeoutKeepAlive / 1000;
+ if (Connection == ConnectionType.KeepAlive && keepaliveS > 0 && m_context.MaxRequests > 0)
+ {
+ osu.AppendASCII($"Keep-Alive:timeout={keepaliveS}, max={m_context.MaxRequests}\r\n");
+ osu.AppendASCII("Connection: Keep-Alive\r\n");
+ }
+ else
+ {
+ osu.AppendASCII("Connection: close\r\n");
+ Connection = ConnectionType.Close;
+ }
+ break;
}
- break;
- }
default:
- sb.Append("Connection: close\r\n");
+ osu.AppendASCII("Connection: close\r\n");
Connection = ConnectionType.Close;
break;
}
@@ -285,7 +294,7 @@ public byte[] GetHeaders()
for (int i = 0; i < m_headers.Count; ++i)
{
string headerName = m_headers.AllKeys[i];
- switch(headerName)
+ switch (headerName)
{
case "Connection":
case "Content-Length":
@@ -295,21 +304,27 @@ public byte[] GetHeaders()
continue;
}
string[] values = m_headers.GetValues(i);
- if (values == null) continue;
- foreach (string value in values)
- sb.AppendFormat("{0}: {1}\r\n", headerName, value);
+ if (values is not null)
+ {
+ foreach (string value in values)
+ {
+ osu.AppendASCII($"{headerName}: ");
+ osu.Append($"{value}");
+ osu.AppendASCII("\r\n");
+ }
+ }
}
- sb.Append("Server: OSWebServer\r\n");
+ osu.AppendASCII("Server: OSWebServer\r\n");
foreach (ResponseCookie cookie in Cookies)
- sb.AppendFormat("Set-Cookie: {0}\r\n", cookie);
+ osu.Append($"Set-Cookie: {cookie}\r\n");
- sb.Append("\r\n");
+ osu.AppendASCII("\r\n");
m_headers.Clear();
- return Encoding.GetBytes(osStringBuilderCache.GetStringAndRelease(sb));
+ m_headerBytes = osu;
}
public void Send()
@@ -331,7 +346,7 @@ public void Send()
m_context.TimeoutKeepAlive = m_keepAlive * 1000;
}
- if (RawBuffer != null)
+ if (RawBuffer is not null)
{
if (RawBufferStart > RawBuffer.Length)
return;
@@ -346,33 +361,29 @@ public void Send()
RawBufferLen = RawBuffer.Length - RawBufferStart;
}
- m_headerBytes = GetHeaders();
+ if (RawBufferLen == 0)
+ RawBuffer = null;
- if (RawBuffer != null && RawBufferLen > 0)
+ GetHeaders();
+
+ if (RawBuffer is not null && RawBufferLen > 0)
{
int tlen = m_headerBytes.Length + RawBufferLen;
if(tlen < 8 * 1024)
{
- byte[] tmp = new byte[tlen];
- Buffer.BlockCopy(m_headerBytes, 0, tmp, 0, m_headerBytes.Length);
- Buffer.BlockCopy(RawBuffer, RawBufferStart, tmp, m_headerBytes.Length, RawBufferLen);
- m_headerBytes = null;
- RawBuffer = tmp;
- RawBufferStart = 0;
- RawBufferLen = tlen;
- }
-
- if (RawBufferLen == 0)
+ m_headerBytes.Append(RawBuffer, RawBufferStart, RawBufferLen);
RawBuffer = null;
+ RawBufferLen = 0;
+ }
}
- if (m_body != null && m_body.Length == 0)
+ if (m_body is not null && m_body.Length == 0)
{
m_body.Dispose();
m_body = null;
}
- if (m_headerBytes == null && RawBuffer == null && m_body == null)
+ if (m_headerBytes is null && RawBuffer is null && m_body is null)
{
Sent = true;
m_context.EndSendResponse(requestID, Connection);
@@ -383,14 +394,17 @@ public void Send()
public bool SendNextAsync(int bytesLimit)
{
- if (m_headerBytes != null)
+ if (m_headerBytes is not null)
{
- byte[] b = m_headerBytes;
- m_headerBytes = null;
-
- if (!m_context.SendAsyncStart(b, 0, b.Length))
+ if (!m_context.SendAsyncStart(m_headerBytes.GetArray(), 0, m_headerBytes.Length))
{
- if (m_body != null)
+ if(m_headerBytes is not null)
+ {
+ OSUTF8Cached.Release(m_headerBytes);
+ m_headerBytes = null;
+ }
+
+ if (m_body is not null)
{
m_body.Dispose();
m_body = null;
@@ -403,7 +417,7 @@ public bool SendNextAsync(int bytesLimit)
}
bool sendRes;
- if (RawBuffer != null)
+ if (RawBuffer is not null)
{
if(RawBufferLen > 0)
{
@@ -429,7 +443,7 @@ public bool SendNextAsync(int bytesLimit)
if (!sendRes)
{
RawBuffer = null;
- if(m_body != null)
+ if(m_body is not null)
{
m_body.Dispose();
m_body = null;
@@ -443,7 +457,7 @@ public bool SendNextAsync(int bytesLimit)
RawBuffer = null;
}
- if (m_body != null)
+ if (m_body is not null)
{
if(m_body.Length != 0)
{
@@ -500,7 +514,13 @@ public bool SendNextAsync(int bytesLimit)
public void CheckSendNextAsyncContinue()
{
- if(m_headerBytes == null && RawBuffer == null && m_body == null)
+ if (m_headerBytes is not null)
+ {
+ OSUTF8Cached.Release(m_headerBytes);
+ m_headerBytes = null;
+ }
+
+ if (m_headerBytes is null && RawBuffer is null && m_body is null)
{
Sent = true;
m_context.EndSendResponse(requestID, Connection);
@@ -513,8 +533,18 @@ public void CheckSendNextAsyncContinue()
public void Clear()
{
- if(m_body != null && m_body.CanRead)
+ if(m_headerBytes is not null)
+ {
+ OSUTF8Cached.Release(m_headerBytes);
+ m_headerBytes = null;
+ }
+
+ if(m_body is not null && m_body.CanRead)
+ {
m_body.Dispose();
+ m_body = null;
+ }
+ RawBuffer = null;
}
#endregion
}
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/IHttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/IHttpRequest.cs
index 2ca5f4e1bec..8a12febc58b 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/IHttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/IHttpRequest.cs
@@ -72,10 +72,12 @@ public interface IHttpRequest
///
string Method { get; set; }
+ /*
///
/// Gets parameter from or .
///
HttpParam Param { get; }
+ */
///
/// Gets variables sent in the query string
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ILogWriter.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ILogWriter.cs
index 790c9a500de..03093d0afdf 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ILogWriter.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/ILogWriter.cs
@@ -1,6 +1,4 @@
-using System;
-using System.Diagnostics;
-using System.Text;
+using System.Runtime.CompilerServices;
namespace OSHttpServer
{
@@ -68,7 +66,7 @@ public sealed class NullLogWriter : ILogWriter
///
/// The logging instance.
///
- public static readonly NullLogWriter Instance = new NullLogWriter();
+ public static readonly NullLogWriter Instance = new();
///
/// Writes everything to null
@@ -76,6 +74,7 @@ public sealed class NullLogWriter : ILogWriter
/// object that wrote the log entry.
/// Importance of the log message
/// The message.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(object source, LogPrio prio, string message) {}
}
}
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/RequestLineEventArgs.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/RequestLineEventArgs.cs
index 1b9b8dc69be..e2b72e3df84 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpServer/RequestLineEventArgs.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpServer/RequestLineEventArgs.cs
@@ -1,4 +1,5 @@
-using System;
+using OpenMetaverse;
+using System;
namespace OSHttpServer.Parser
{
@@ -8,41 +9,18 @@ namespace OSHttpServer.Parser
public class RequestLineEventArgs : EventArgs
{
///
- /// Initializes a new instance of the class.
+ /// http method.
///
- /// The HTTP method.
- /// The URI path.
- /// The HTTP version.
- public RequestLineEventArgs(string httpMethod, string uriPath, string httpVersion)
- {
- HttpMethod = httpMethod;
- UriPath = uriPath;
- HttpVersion = httpVersion;
- }
+ public osUTF8Slice HttpMethod;
///
- /// Initializes a new instance of the class.
+ /// version of the HTTP protocol that the client want to use.
///
- public RequestLineEventArgs()
- {
- }
+ public osUTF8Slice HttpVersion;
///
- /// Gets or sets http method.
+ /// requested URI path.
///
- ///
- /// Should be one of the methods declared in .
- ///
- public string HttpMethod { get; set; }
-
- ///
- /// Gets or sets the version of the HTTP protocol that the client want to use.
- ///
- public string HttpVersion { get; set; }
-
- ///
- /// Gets or sets requested URI path.
- ///
- public string UriPath { get; set; }
+ public osUTF8Slice UriPath;
}
}
\ No newline at end of file
diff --git a/OpenSim/Framework/Servers/HttpServer/OpenSim.Framework.Servers.HttpServer.csproj b/OpenSim/Framework/Servers/HttpServer/OpenSim.Framework.Servers.HttpServer.csproj
index 94d2cdfd242..14c11c8b996 100644
--- a/OpenSim/Framework/Servers/HttpServer/OpenSim.Framework.Servers.HttpServer.csproj
+++ b/OpenSim/Framework/Servers/HttpServer/OpenSim.Framework.Servers.HttpServer.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Framework.Servers.HttpServer
http://opensimulator.org
OpenSim
@@ -18,9 +18,6 @@
..\..\..\..\bin\OpenMetaverseTypes.dll
False
-
- False
-
..\..\..\..\bin\XMLRPC.dll
False
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
index e7b44b2936e..e35e067761a 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
@@ -33,7 +33,6 @@ namespace OpenSim.Framework.Servers.HttpServer
{
public delegate OSHttpResponse RequestMethod(UUID ID, OSHttpRequest request);
public delegate bool HasEventsMethod(UUID requestID, UUID pId);
-
public delegate Hashtable GetEventsMethod(UUID requestID, UUID pId);
public delegate Hashtable NoEventsMethod(UUID requestID, UUID pId);
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
index 784e84fa05d..10ad3530700 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
@@ -73,14 +73,14 @@ internal void DoHTTPGruntWork(Hashtable responsedata)
OSHttpResponse response = new OSHttpResponse(new HttpResponse(Request));
- if (responsedata == null)
+ if (responsedata is null)
{
SendNoContentError(response);
return;
}
int responsecode = 200;
- string responseString = String.Empty;
+ string responseString = null;
string contentType;
byte[] buffer = null;
int rangeStart = 0;
@@ -105,10 +105,7 @@ internal void DoHTTPGruntWork(Hashtable responsedata)
}
else
responseString = (string)responsedata["str_response_string"];
-
contentType = (string)responsedata["content_type"];
- if (responseString == null)
- responseString = String.Empty;
}
catch
{
@@ -158,7 +155,9 @@ internal void DoHTTPGruntWork(Hashtable responsedata)
if(buffer == null)
{
- if (contentType != null && (!(contentType.Contains("image")
+ if(string.IsNullOrEmpty(responseString))
+ buffer = Array.Empty();
+ else if (contentType != null && (!(contentType.Contains("image")
|| contentType.Contains("x-shockwave-flash")
|| contentType.Contains("application/x-oar")
|| contentType.Contains("application/vnd.ll.mesh"))))
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
index a84df2a28a5..beb8d88ac20 100755
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
@@ -41,16 +41,14 @@ public class PollServiceRequestManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- private ConcurrentQueue m_retryRequests = new ConcurrentQueue();
-
- private int m_WorkerThreadCount = 0;
+ private readonly ConcurrentQueue m_retryRequests = new();
+ private readonly int m_WorkerThreadCount = 0;
private ObjectJobEngine m_workerPool;
private Thread m_retrysThread;
private bool m_running = false;
- public PollServiceRequestManager(
- bool performResponsesAsync, uint pWorkerThreadCount, int pTimeout)
+ public PollServiceRequestManager(bool performResponsesAsync, uint pWorkerThreadCount, int pTimeout)
{
m_WorkerThreadCount = (int)pWorkerThreadCount;
}
@@ -59,6 +57,7 @@ public void Start()
{
if(m_running)
return;
+
m_running = true;
m_workerPool = new ObjectJobEngine(PoolWorkerJob, "PollServiceWorker", 4000, m_WorkerThreadCount);
@@ -86,12 +85,11 @@ public void Enqueue(PollServiceHttpRequest req)
private void CheckRetries()
{
- PollServiceHttpRequest preq;
while (m_running)
{
Thread.Sleep(100);
Watchdog.UpdateThread();
- while (m_running && m_retryRequests.TryDequeue(out preq))
+ while (m_running && m_retryRequests.TryDequeue(out PollServiceHttpRequest preq))
m_workerPool.Enqueue(preq);
}
}
@@ -126,8 +124,7 @@ public void Stop()
private void PoolWorkerJob(object o)
{
- PollServiceHttpRequest req = o as PollServiceHttpRequest;
- if(req == null)
+ if (o is not PollServiceHttpRequest req)
return;
try
{
@@ -176,7 +173,7 @@ private void PoolWorkerJob(object o)
}
catch (Exception e)
{
- m_log.ErrorFormat("Exception in poll service thread: " + e.ToString());
+ m_log.Error($"Exception in poll service thread: {e}");
}
}
}
diff --git a/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj b/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj
index b3d234901fc..0a6fba9b3ca 100644
--- a/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj
+++ b/OpenSim/Framework/Servers/OpenSim.Framework.Servers.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
OpenSim.Framework.Servers
http://opensimulator.org
OpenSim
diff --git a/OpenSim/Framework/Servers/ServerBase.cs b/OpenSim/Framework/Servers/ServerBase.cs
index 1def987169b..87eeb136b09 100755
--- a/OpenSim/Framework/Servers/ServerBase.cs
+++ b/OpenSim/Framework/Servers/ServerBase.cs
@@ -82,9 +82,7 @@ public ServerBase()
protected void CreatePIDFile(string path)
{
if (File.Exists(path))
- m_log.ErrorFormat(
- "[SERVER BASE]: Previous pid file {0} still exists on startup. Possibly previously unclean shutdown.",
- path);
+ m_log.Error($"[SERVER BASE]: Previous pid file {path} still exists on startup. Possibly previously unclean shutdown.");
try
{
@@ -108,7 +106,7 @@ protected void CreatePIDFile(string path)
protected void RemovePIDFile()
{
- if (m_pidFile != String.Empty)
+ if (!string.IsNullOrEmpty(m_pidFile))
{
try
{
@@ -116,7 +114,7 @@ protected void RemovePIDFile()
}
catch (Exception e)
{
- m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e);
+ m_log.Error($"[SERVER BASE]: Error whilst removing {m_pidFile}", e);
}
m_pidFile = String.Empty;
@@ -131,16 +129,15 @@ public void LogEnvironmentInformation()
{
// FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net
// XmlConfigurator calls first accross servers.
- m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory);
+ m_log.Info($"[SERVER BASE]: Starting in {m_startupDirectory}");
- m_log.InfoFormat("[SERVER BASE]: OpenSimulator version: {0}", m_version);
+ m_log.Info($"[SERVER BASE]: OpenSimulator version: {m_version}");
// clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
// the clr version number doesn't match the project version number under Mono.
//m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
- m_log.InfoFormat(
- "[SERVER BASE]: Operating system version: {0}, .NET platform {1}, {2}-bit",
- Environment.OSVersion, Environment.OSVersion.Platform, Environment.Is64BitProcess ? "64" : "32");
+ m_log.Info(
+ $"[SERVER BASE]: Operating system version: {Environment.OSVersion}, .NET platform {Util.RuntimePlatformStr}, {(Environment.Is64BitProcess ? "64" : "32")}-bit");
}
public void RegisterCommonAppenders(IConfig startupConfig)
@@ -174,10 +171,10 @@ public void RegisterCommonAppenders(IConfig startupConfig)
m_consoleAppender.Console = (ConsoleBase)m_console;
// If there is no threshold set then the threshold is effectively everything.
- if (null == m_consoleAppender.Threshold)
+ if (m_consoleAppender.Threshold is null)
m_consoleAppender.Threshold = Level.All;
- Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
+ //Notice($"Console log level is {m_consoleAppender.Threshold}");
}
if (m_logFileAppender != null && startupConfig != null)
@@ -298,11 +295,11 @@ public void RegisterCommonCommands()
+ " 3 = full stack trace, including common threads\n",
HandleDebugThreadpoolLevel);
-// m_console.Commands.AddCommand(
-// "Debug", false, "show threadpool calls active",
-// "show threadpool calls active",
-// "Show details about threadpool calls that are still active (currently waiting or in progress)",
-// HandleShowThreadpoolCallsActive);
+ //m_console.Commands.AddCommand(
+ // "Debug", false, "show threadpool calls active",
+ // "show threadpool calls active",
+ // "Show details about threadpool calls that are still active (currently waiting or in progress)",
+ // HandleShowThreadpoolCallsActive);
m_console.Commands.AddCommand(
"Debug", false, "show threadpool calls complete",
@@ -334,7 +331,7 @@ public void RegisterCommonCommands()
public void RegisterCommonComponents(IConfigSource configSource)
{
-// IConfig networkConfig = configSource.Configs["Network"];
+ //IConfig networkConfig = configSource.Configs["Network"];
m_serverStatsCollector = new ServerStatsCollector();
m_serverStatsCollector.Initialise(configSource);
@@ -417,9 +414,7 @@ private void HandleDebugThreadpoolSet(string module, string[] args)
return;
}
- int newThreads;
-
- if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
+ if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out int newThreads))
return;
string poolType = args[3];
@@ -469,10 +464,8 @@ private void HandleDebugThreadpoolSet(string module, string[] args)
}
else
{
- int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;
-
- ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
- ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);
+ ThreadPool.GetMinThreads(out int minWorkerThreads, out int minIocpThreads);
+ ThreadPool.GetMaxThreads(out int maxWorkerThreads, out int maxIocpThreads);
Notice("Min worker threads now {0}", minWorkerThreads);
Notice("Min IOCP threads now {0}", minIocpThreads);
@@ -756,48 +749,50 @@ protected void ShowInfo()
///
protected void EnhanceVersionInformation()
{
+ const string manualVersionFileName = ".version";
string buildVersion = string.Empty;
- string manualVersionFileName = ".version";
-
- string gitDir = "../.git/";
- string gitRefPointerPath = gitDir + "HEAD";
-
if (File.Exists(manualVersionFileName))
{
using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
buildVersion = CommitFile.ReadLine();
- m_version += buildVersion ?? "";
+ if (!string.IsNullOrEmpty(buildVersion))
+ {
+ m_version += buildVersion;
+ return;
+ }
}
- else if (File.Exists(gitRefPointerPath))
+
+ string gitDir = Path.Combine("..", ".git");
+ string gitRefPointerPath = Path.Combine(gitDir, "HEAD");
+ if (File.Exists(gitRefPointerPath))
{
-// m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
+ //m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
string rawPointer = "";
using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
rawPointer = pointerFile.ReadLine();
-// m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
+ //m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
Match m = Regex.Match(rawPointer, "^ref: (.+)$");
if (m.Success)
{
-// m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
+ //m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
string gitRef = m.Groups[1].Value;
- string gitRefPath = gitDir + gitRef;
+ string gitRefPath = Path.Combine(gitDir, gitRef);
if (File.Exists(gitRefPath))
{
-// m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
-
+ //m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
using (StreamReader refFile = File.OpenText(gitRefPath))
- {
- string gitHash = refFile.ReadLine();
- m_version += gitHash.Substring(0, 7);
- }
+ buildVersion = refFile.ReadLine();
+
+ if (!string.IsNullOrEmpty(buildVersion))
+ m_version += buildVersion[..7];
}
}
}
@@ -805,8 +800,7 @@ protected void EnhanceVersionInformation()
public string GetVersionText()
{
- return String.Format("Version: {0} (SIMULATION/{1} - SIMULATION/{2})",
- m_version, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax);
+ return $"Version: {m_version} (SIM-{VersionInfo.SimulationServiceVersionSupportedMin}/{VersionInfo.SimulationServiceVersionSupportedMax})";
}
///
diff --git a/OpenSim/Framework/Servers/Tests/OpenSim.Framework.Servers.Tests.csproj b/OpenSim/Framework/Servers/Tests/OpenSim.Framework.Servers.Tests.csproj
deleted file mode 100644
index 4a51ecd08c7..00000000000
--- a/OpenSim/Framework/Servers/Tests/OpenSim.Framework.Servers.Tests.csproj
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
- net48
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs b/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs
deleted file mode 100644
index 68a1c78aa4b..00000000000
--- a/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using NUnit.Framework;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Servers.Tests
-{
- [TestFixture]
- public class VersionInfoTests : OpenSimTestCase
- {
- [Test]
- public void TestVersionLength()
- {
- Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.Version.Length," VersionInfo.Version string not " + VersionInfo.VERSIONINFO_VERSION_LENGTH + " chars.");
- }
- }
-}
diff --git a/OpenSim/Framework/ServiceAuth/BasicHttpAuthentication.cs b/OpenSim/Framework/ServiceAuth/BasicHttpAuthentication.cs
index 9126cfb5f44..c1c94e16458 100644
--- a/OpenSim/Framework/ServiceAuth/BasicHttpAuthentication.cs
+++ b/OpenSim/Framework/ServiceAuth/BasicHttpAuthentication.cs
@@ -33,6 +33,7 @@
using Nini.Config;
using log4net;
+using System.Net.Http.Headers;
namespace OpenSim.Framework.ServiceAuth
{
@@ -54,14 +55,13 @@ public string Credentials
public BasicHttpAuthentication(IConfigSource config, string section)
{
-// remove_me = section;
m_Username = Util.GetConfigVarFromSections(config, "HttpAuthUsername", new string[] { "Network", section }, string.Empty);
m_Password = Util.GetConfigVarFromSections(config, "HttpAuthPassword", new string[] { "Network", section }, string.Empty);
string str = m_Username + ":" + m_Password;
byte[] encData_byte = Util.UTF8.GetBytes(str);
m_CredentialsB64 = Convert.ToBase64String(encData_byte);
-// m_log.DebugFormat("[HTTP BASIC AUTH]: {0} {1} [{2}]", m_Username, m_Password, section);
+ //m_log.DebugFormat("[HTTP BASIC AUTH]: {0} {1} [{2}]", m_Username, m_Password, section);
}
public void AddAuthorization(NameValueCollection headers)
@@ -70,12 +70,18 @@ public void AddAuthorization(NameValueCollection headers)
headers["Authorization"] = "Basic " + m_CredentialsB64;
}
+ public void AddAuthorization(HttpRequestHeaders headers)
+ {
+ //m_log.DebugFormat("[HTTP BASIC AUTH]: Adding authorization for {0}", remove_me);
+ headers.TryAddWithoutValidation("Authorization","Basic " + m_CredentialsB64);
+ }
+
public bool Authenticate(string data)
{
string recovered = Util.Base64ToString(data);
if (!String.IsNullOrEmpty(recovered))
{
- string[] parts = recovered.Split(new char[] { ':' });
+ string[] parts = recovered.Split(Util.SplitColonArray);
if (parts.Length >= 2)
{
return m_Username.Equals(parts[0]) && m_Password.Equals(parts[1]);
diff --git a/OpenSim/Framework/ServiceAuth/CompoundAuthentication.cs b/OpenSim/Framework/ServiceAuth/CompoundAuthentication.cs
index 79d6ff429b7..4b13a80b5b4 100644
--- a/OpenSim/Framework/ServiceAuth/CompoundAuthentication.cs
+++ b/OpenSim/Framework/ServiceAuth/CompoundAuthentication.cs
@@ -30,6 +30,7 @@
using System.Collections.Specialized;
using System.Linq;
using System.Net;
+using System.Net.Http.Headers;
namespace OpenSim.Framework.ServiceAuth
{
@@ -62,6 +63,12 @@ public void AddAuthorization(NameValueCollection headers)
auth.AddAuthorization(headers);
}
+ public void AddAuthorization(HttpRequestHeaders headers)
+ {
+ foreach (IServiceAuth auth in m_authentications)
+ auth.AddAuthorization(headers);
+ }
+
public bool Authenticate(string data)
{
return m_authentications.TrueForAll(a => a.Authenticate(data));
diff --git a/OpenSim/Framework/ServiceAuth/DisallowLlHttpRequest.cs b/OpenSim/Framework/ServiceAuth/DisallowLlHttpRequest.cs
index e0c413bac90..e2f64ce99fb 100644
--- a/OpenSim/Framework/ServiceAuth/DisallowLlHttpRequest.cs
+++ b/OpenSim/Framework/ServiceAuth/DisallowLlHttpRequest.cs
@@ -28,6 +28,7 @@
using System;
using System.Collections.Specialized;
using System.Net;
+using System.Net.Http.Headers;
namespace OpenSim.Framework.ServiceAuth
{
@@ -35,7 +36,8 @@ public class DisallowLlHttpRequest : IServiceAuth
{
public string Name { get { return "DisallowllHTTPRequest"; } }
- public void AddAuthorization(NameValueCollection headers) {}
+ public void AddAuthorization(NameValueCollection headers) { }
+ public void AddAuthorization(HttpRequestHeaders headers) { }
public bool Authenticate(string data)
{
diff --git a/OpenSim/Framework/ServiceAuth/IServiceAuth.cs b/OpenSim/Framework/ServiceAuth/IServiceAuth.cs
index 5f744cbe102..4fe309dd794 100644
--- a/OpenSim/Framework/ServiceAuth/IServiceAuth.cs
+++ b/OpenSim/Framework/ServiceAuth/IServiceAuth.cs
@@ -29,6 +29,7 @@
using System.Net;
using System.Collections.Generic;
using System.Collections.Specialized;
+using System.Net.Http.Headers;
namespace OpenSim.Framework.ServiceAuth
{
@@ -44,5 +45,6 @@ public interface IServiceAuth
bool Authenticate(string data);
bool Authenticate(NameValueCollection headers, AddHeaderDelegate d, out HttpStatusCode statusCode);
void AddAuthorization(NameValueCollection headers);
+ void AddAuthorization(HttpRequestHeaders headers);
}
}
diff --git a/OpenSim/Framework/TaskInventoryItem.cs b/OpenSim/Framework/TaskInventoryItem.cs
index 217b8b2849d..68e2babe2d0 100644
--- a/OpenSim/Framework/TaskInventoryItem.cs
+++ b/OpenSim/Framework/TaskInventoryItem.cs
@@ -38,78 +38,19 @@ namespace OpenSim.Framework
public class TaskInventoryItem : ICloneable
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
- ///
- /// XXX This should really be factored out into some constants class.
- ///
private const uint FULL_MASK_PERMISSIONS_GENERAL = 2147483647;
- private UUID _assetID = UUID.Zero;
-
- private uint _baseMask = FULL_MASK_PERMISSIONS_GENERAL;
- private uint _creationDate = 0;
- private UUID _creatorID = UUID.Zero;
- private string _creatorData = String.Empty;
- private string _description = String.Empty;
- private uint _everyoneMask = FULL_MASK_PERMISSIONS_GENERAL;
- private uint _flags = 0;
- private UUID _groupID = UUID.Zero;
- private uint _groupMask = FULL_MASK_PERMISSIONS_GENERAL;
-
- private int _invType = 0;
- private UUID _itemID = UUID.Zero;
- private UUID _lastOwnerID = UUID.Zero;
- private UUID _rezzerID = UUID.Zero;
- private string _name = String.Empty;
- private uint _nextOwnerMask = FULL_MASK_PERMISSIONS_GENERAL;
- private UUID _ownerID = UUID.Zero;
- private uint _ownerMask = FULL_MASK_PERMISSIONS_GENERAL;
- private UUID _parentID = UUID.Zero; //parent folder id
- private UUID _parentPartID = UUID.Zero; // SceneObjectPart this is inside
- private UUID _permsGranter;
- private int _permsMask;
- private int _type = 0;
- private UUID _oldID;
- private UUID _loadedID = UUID.Zero;
-
- private bool _ownerChanged = false;
-
- public UUID AssetID {
- get {
- return _assetID;
- }
- set {
- _assetID = value;
- }
- }
+ public UUID AssetID { get; set; }
+ public uint CreationDate { get; set; }
- public uint BasePermissions {
- get {
- return _baseMask;
- }
- set {
- _baseMask = value;
- }
- }
-
- public uint CreationDate {
- get {
- return _creationDate;
- }
- set {
- _creationDate = value;
- }
- }
-
- public UUID CreatorID {
- get {
- return _creatorID;
- }
- set {
- _creatorID = value;
- }
+ UUID _creatorID = UUID.Zero;
+ public UUID CreatorID
+ {
+ get { return _creatorID; }
+ set { _creatorID = value; }
}
+ private string _creatorData = string.Empty;
public string CreatorData // = ;
{
get { return _creatorData; }
@@ -138,11 +79,9 @@ public string CreatorIdentification
return;
}
- if (!value.Contains(";")) // plain UUID
+ if (!value.Contains(';')) // plain UUID
{
- UUID uuid = UUID.Zero;
- UUID.TryParse(value, out uuid);
- _creatorID = uuid;
+ _= UUID.TryParse(value, out _creatorID);
}
else // [;[;name]]
{
@@ -150,9 +89,7 @@ public string CreatorIdentification
string[] parts = value.Split(';');
if (parts.Length >= 1)
{
- UUID uuid = UUID.Zero;
- UUID.TryParse(parts[0], out uuid);
- _creatorID = uuid;
+ _ = UUID.TryParse(parts[0], out _creatorID);
}
if (parts.Length >= 2)
_creatorData = parts[1];
@@ -165,199 +102,38 @@ public string CreatorIdentification
}
}
- public string Description {
- get {
- return _description;
- }
- set {
- _description = value;
- }
- }
-
- public uint EveryonePermissions {
- get {
- return _everyoneMask;
- }
- set {
- _everyoneMask = value;
- }
- }
-
- public uint Flags {
- get {
- return _flags;
- }
- set {
- _flags = value;
- }
- }
-
- public UUID GroupID {
- get {
- return _groupID;
- }
- set {
- _groupID = value;
- }
- }
-
- public uint GroupPermissions {
- get {
- return _groupMask;
- }
- set {
- _groupMask = value;
- }
- }
-
- public int InvType {
- get {
- return _invType;
- }
- set {
- _invType = value;
- }
- }
-
- public UUID ItemID {
- get {
- return _itemID;
- }
- set {
- _itemID = value;
- }
- }
-
- public UUID OldItemID {
- get {
- return _oldID;
- }
- set {
- _oldID = value;
- }
- }
-
- public UUID LoadedItemID {
- get {
- return _loadedID;
- }
- set {
- _loadedID = value;
- }
- }
-
- public UUID LastOwnerID {
- get {
- return _lastOwnerID;
- }
- set {
- _lastOwnerID = value;
- }
- }
-
- public UUID RezzerID
- {
- get {
- return _rezzerID;
- }
- set {
- _rezzerID = value;
- }
- }
-
- public string Name {
- get {
- return _name;
- }
- set {
- _name = value;
- }
- }
-
- public uint NextPermissions {
- get {
- return _nextOwnerMask;
- }
- set {
- _nextOwnerMask = value;
- }
- }
-
- public UUID OwnerID {
- get {
- return _ownerID;
- }
- set {
- _ownerID = value;
- }
- }
-
- public uint CurrentPermissions {
- get {
- return _ownerMask;
- }
- set {
- _ownerMask = value;
- }
- }
-
- public UUID ParentID {
- get {
- return _parentID;
- }
- set {
- _parentID = value;
- }
- }
-
- public UUID ParentPartID {
- get {
- return _parentPartID;
- }
- set {
- _parentPartID = value;
- }
- }
-
- public UUID PermsGranter {
- get {
- return _permsGranter;
- }
- set {
- _permsGranter = value;
- }
- }
-
- public int PermsMask {
- get {
- return _permsMask;
- }
- set {
- _permsMask = value;
- }
- }
-
- public int Type {
- get {
- return _type;
- }
- set {
- _type = value;
- }
- }
+ public uint Flags { get; set; }
+ public int Type { get; set; }
+ public int InvType { get; set; }
+ public UUID ItemID { get; set; }
+ public UUID OldItemID { get; set; }
+ public UUID LoadedItemID { get; set; }
+ public UUID RezzerID { get; set; }
+ public string Name { get; set; }
+ public string Description { get; set; }
+ public UUID OwnerID { get; set; }
+ public UUID LastOwnerID { get; set; }
+ public UUID GroupID { get; set; }
+ public UUID ParentID { get; set; }
+ public UUID ParentPartID { get; set; }
+ public uint BasePermissions { get; set; } = FULL_MASK_PERMISSIONS_GENERAL;
+ public uint CurrentPermissions { get; set; } = FULL_MASK_PERMISSIONS_GENERAL;
+ public uint EveryonePermissions { get; set; } = FULL_MASK_PERMISSIONS_GENERAL;
+ public uint GroupPermissions { get; set; } = FULL_MASK_PERMISSIONS_GENERAL;
+ public uint NextPermissions { get; set; } = FULL_MASK_PERMISSIONS_GENERAL;
+ public UUID PermsGranter { get; set; }
+ public int PermsMask { get; set; }
+ private bool _ownerChanged = false;
public bool OwnerChanged
{
- get
- {
- return _ownerChanged;
- }
+ get { return _ownerChanged; }
set
{
_ownerChanged = value;
-// m_log.DebugFormat(
-// "[TASK INVENTORY ITEM]: Owner changed set {0} for {1} {2} owned by {3}",
-// _ownerChanged, Name, ItemID, OwnerID);
+ //m_log.DebugFormat(
+ // "[TASK INVENTORY ITEM]: Owner changed set {0} for {1} {2} owned by {3}",
+ // _ownerChanged, Name, ItemID, OwnerID);
}
}
diff --git a/OpenSim/Framework/TerrainData.cs b/OpenSim/Framework/TerrainData.cs
index 7b4905ac2b4..bbaebb838c0 100644
--- a/OpenSim/Framework/TerrainData.cs
+++ b/OpenSim/Framework/TerrainData.cs
@@ -86,7 +86,7 @@ public class TerrainData
public int SizeX { get; protected set; }
public int SizeY { get; protected set; }
- public int SizeZ { get; protected set; }
+ public const int SizeZ = 0;
// A height used when the user doesn't specify anything
public const float DefaultTerrainHeight = 21f;
@@ -121,6 +121,97 @@ public static TerrainData CreateFromDatabaseBlobFactory(int pSizeX, int pSizeY,
set { this[x, y] = value; }
}
+ public float GetHeight(float x, float y)
+ {
+ // integer indexs
+ int ix, mix;
+ int iy, miy;
+ // interpolators offset
+ float dx;
+ float dy;
+
+ if (x <= 0)
+ {
+ if(y <= 0)
+ return m_heightmap[0, 0];
+
+ iy = (int)y;
+ miy = SizeY - 1;
+ if (iy >= miy)
+ return m_heightmap[0, miy];
+
+ dy = y - iy;
+
+ float h = m_heightmap[0, iy];
+ ++iy;
+ return h + (m_heightmap[0, iy] - h) * dy;
+ }
+
+ ix = (int)x;
+ mix = SizeX - 1;
+
+ if (ix >= mix)
+ {
+ if(y <= 0)
+ return m_heightmap[mix, 0];
+
+ iy = (int)y;
+ miy = SizeY - 1;
+
+ if (y >= miy)
+ return m_heightmap[mix, miy];
+
+ dy = y - iy;
+
+ float h = m_heightmap[mix, iy];
+ ++iy;
+ return h + (m_heightmap[mix, iy] - h) * dy;
+ }
+
+ dx = x - ix;
+
+ if (y <= 0)
+ {
+ float h = m_heightmap[ix, 0];
+ ++ix;
+ return h + (m_heightmap[ix, 0] - h) * dx;
+ }
+
+ iy = (int)y;
+ miy = SizeY - 1;
+
+ if (iy >= miy)
+ {
+ float h = m_heightmap[ix, miy];
+ ++ix;
+ return h + (m_heightmap[ix, miy] - h) * dx;
+ }
+
+ dy = y - iy;
+
+ float h0 = m_heightmap[ix, iy]; // 0,0 vertice
+ float h1;
+ float h2;
+
+ if (dy > dx)
+ {
+ ++iy;
+ h2 = m_heightmap[ix, iy]; // 0,1 vertice
+ h1 = (h2 - h0) * dy; // 0,1 vertice minus 0,0
+ ++ix;
+ h2 = (m_heightmap[ix, iy] - h2) * dx; // 1,1 vertice minus 0,1
+ }
+ else
+ {
+ ++ix;
+ h2 = m_heightmap[ix, iy]; // vertice 1,0
+ h1 = (h2 - h0) * dx; // 1,0 vertice minus 0,0
+ ++iy;
+ h2 = (m_heightmap[ix, iy] - h2) * dy; // 1,1 vertice minus 1,0
+ }
+ return h0 + h1 + h2;
+ }
+
public TerrainTaintsArray GetTaints()
{
return m_taints;
@@ -367,7 +458,6 @@ public TerrainData(double[,] pTerrain)
m_mapStride = SizeY;
m_mapPatchsStride = m_mapStride * Constants.TerrainPatchSize;
- SizeZ = (int)Constants.RegionHeight;
CompressionFactor = 100.0f;
@@ -390,7 +480,6 @@ public TerrainData(int pX, int pY, int pZ)
{
SizeX = pX;
SizeY = pY;
- SizeZ = pZ;
m_taintSizeX = SizeX / Constants.TerrainPatchSize;
m_taintSizeY = SizeY / Constants.TerrainPatchSize;
m_mapStride = SizeY;
@@ -519,7 +608,7 @@ public Array ToCompressedTerrainSerializationV2D()
for (int xx = 0; xx < SizeX; xx++)
{
// reduce to 1mm resolution
- float val = (float)Math.Round(m_heightmap[xx, yy],3,MidpointRounding.AwayFromZero);
+ float val = MathF.Round(m_heightmap[xx, yy],3,MidpointRounding.AwayFromZero);
bw.Write(val);
}
}
@@ -549,7 +638,7 @@ public Array ToCompressedTerrainSerializationV2DGzip()
for (int xx = 0; xx < SizeX; xx++)
{
//bw.Write((float)m_heightmap[xx, yy]);
- bw.Write((float)Math.Round(m_heightmap[xx, yy], 3, MidpointRounding.AwayFromZero));
+ bw.Write(MathF.Round(m_heightmap[xx, yy], 3, MidpointRounding.AwayFromZero));
}
bw.Flush();
diff --git a/OpenSim/Framework/Tests/AgentCircuitDataTest.cs b/OpenSim/Framework/Tests/AgentCircuitDataTest.cs
deleted file mode 100644
index c8eb57dd591..00000000000
--- a/OpenSim/Framework/Tests/AgentCircuitDataTest.cs
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System.Collections.Generic;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using NUnit.Framework;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class AgentCircuitDataTest : OpenSimTestCase
- {
- private UUID AgentId;
- private AvatarAppearance AvAppearance;
- private byte[] VisualParams;
- private UUID BaseFolder;
- private string CapsPath;
- private Dictionary ChildrenCapsPaths;
- private uint circuitcode = 0949030;
- private string firstname;
- private string lastname;
- private UUID SecureSessionId;
- private UUID SessionId;
- private Vector3 StartPos;
-
-
- [SetUp]
- public void setup()
- {
- AgentId = UUID.Random();
- BaseFolder = UUID.Random();
- CapsPath = "http://www.opensimulator.org/Caps/Foo";
- ChildrenCapsPaths = new Dictionary();
- ChildrenCapsPaths.Add(ulong.MaxValue, "http://www.opensimulator.org/Caps/Foo2");
- firstname = "CoolAvatarTest";
- lastname = "test";
- StartPos = new Vector3(5,23,125);
-
- SecureSessionId = UUID.Random();
- SessionId = UUID.Random();
-
- AvAppearance = new AvatarAppearance();
- VisualParams = new byte[218];
-
- //body
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HEIGHT] = 155;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_THICKNESS] = 00;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BODY_FAT] = 0;
-
- //Torso
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_TORSO_MUSCLES] = 48;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_NECK_THICKNESS] = 43;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_NECK_LENGTH] = 255;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_SHOULDERS] = 94;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_CHEST_MALE_NO_PECS] = 199;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_ARM_LENGTH] = 255;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HAND_SIZE] = 33;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_TORSO_LENGTH] = 240;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LOVE_HANDLES] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BELLY_SIZE] = 0;
-
- // legs
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LEG_MUSCLES] = 82;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LEG_LENGTH] = 255;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HIP_WIDTH] = 84;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HIP_LENGTH] = 166;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BUTT_SIZE] = 64;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_SADDLEBAGS] = 89;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BOWED_LEGS] = 127;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_FOOT_SIZE] = 45;
-
-
- // head
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HEAD_SIZE] = 255;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_SQUASH_STRETCH_HEAD] = 0; // head stretch
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HEAD_SHAPE] = 155;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EGG_HEAD] = 127;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_POINTY_EARS] = 255;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HEAD_LENGTH] = 45;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_FACE_SHEAR] = 127;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_FOREHEAD_ANGLE] = 104;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BIG_BROW] = 94;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_PUFFY_UPPER_CHEEKS] = 0; // upper cheeks
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_DOUBLE_CHIN] = 122; // lower cheeks
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_HIGH_CHEEK_BONES] = 130;
-
-
-
- // eyes
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EYE_SIZE] = 105;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_WIDE_EYES] = 135;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EYE_SPACING] = 184;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EYELID_CORNER_UP] = 230;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EYELID_INNER_CORNER_UP] = 120;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EYE_DEPTH] = 158;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_UPPER_EYELID_FOLD] = 69;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BAGGY_EYES] = 38;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EYELASHES_LONG] = 127;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_POP_EYE] = 127;
-
- VisualParams[(int)AvatarAppearance.VPElement.EYES_EYE_COLOR] = 25;
- VisualParams[(int)AvatarAppearance.VPElement.EYES_EYE_LIGHTNESS] = 127;
-
- // ears
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BIG_EARS] = 255;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_EARS_OUT] = 127;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_ATTACHED_EARLOBES] = 127;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_POINTY_EARS] = 255;
-
- // nose
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_NOSE_BIG_OUT] = 79;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_WIDE_NOSE] = 35;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BROAD_NOSTRILS] = 86;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LOW_SEPTUM_NOSE] = 112; // nostril division
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BULBOUS_NOSE] = 25;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_NOBLE_NOSE_BRIDGE] = 25; // upper bridge
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LOWER_BRIDGE_NOSE] = 25; // lower bridge
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_WIDE_NOSE_BRIDGE] = 25;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_UPTURNED_NOSE_TIP] = 107;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_BULBOUS_NOSE_TIP] = 25;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_CROOKED_NOSE] = 127;
-
-
- // Mouth
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LIP_WIDTH] = 122;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_TALL_LIPS] = 10; // lip fullness
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LIP_THICKNESS] = 112;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LIP_RATIO] = 137;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_MOUTH_HEIGHT] = 176;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_MOUTH_CORNER] = 140; // Sad --> happy
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_LIP_CLEFT_DEEP] = 84;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_WIDE_LIP_CLEFT] = 84;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_SHIFT_MOUTH] = 127;
-
-
- // chin
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_WEAK_CHIN] = 119;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_SQUARE_JAW] = 5;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_DEEP_CHIN] = 132;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_JAW_ANGLE] = 153;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_JAW_JUT] = 100;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_JOWLS] = 38;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_CLEFT_CHIN] = 89;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_CLEFT_CHIN_UPPER] = 89;
- VisualParams[(int)AvatarAppearance.VPElement.SHAPE_DOUBLE_CHIN] = 0;
-
-
- // hair color
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_WHITE_HAIR] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_RAINBOW_COLOR_39] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_BLONDE_HAIR] = 24;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_RED_HAIR] = 0;
-
- // hair style
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_VOLUME] = 160;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_FRONT] = 153;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_SIDES] = 153;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_BACK] = 170;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_BIG_FRONT] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_BIG_TOP] = 117;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_BIG_BACK] = 170;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_FRONT_FRINGE] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_SIDE_FRINGE] = 142;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_BACK_FRINGE] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_SIDES_FULL] = 146;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_SWEEP] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_SHEAR_FRONT] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_SHEAR_BACK] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_TAPER_FRONT] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_TAPER_BACK] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_RUMPLED] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_PIGTAILS] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_PONYTAIL] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_SPIKED] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_TILT] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_PART_MIDDLE] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_PART_RIGHT] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_PART_LEFT] = 0;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_BANGS_PART_MIDDLE] = 155;
-
- //Eyebrows
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_EYEBROW_SIZE] = 20;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_EYEBROW_DENSITY] = 140;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_LOWER_EYEBROWS] = 200; // eyebrow height
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_ARCED_EYEBROWS] = 124;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_POINTY_EYEBROWS] = 65;
-
- //Facial hair
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_HAIR_THICKNESS] = 65;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_SIDEBURNS] = 235;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_MOUSTACHE] = 75;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_CHIN_CURTAINS] = 140;
- VisualParams[(int)AvatarAppearance.VPElement.HAIR_SOULPATCH] = 0;
-
- AvAppearance.VisualParams = VisualParams;
-
- AvAppearance.SetAppearance(AvAppearance.Texture, (byte[])VisualParams.Clone());
- }
-
- ///
- /// Test to ensure that the serialization format is the same and the underlying types don't change without notice
- /// oldSerialization is just a json serialization of the OSDMap packed for the AgentCircuitData.
- /// The idea is that if the current json serializer cannot parse the old serialization, then the underlying types
- /// have changed and are incompatible.
- ///
- [Test]
- public void HistoricalAgentCircuitDataOSDConversion()
- {
- string oldSerialization = "{\"agent_id\":\"522675bd-8214-40c1-b3ca-9c7f7fd170be\",\"base_folder\":\"c40b5f5f-476f-496b-bd69-b5a539c434d8\",\"caps_path\":\"http://www.opensimulator.org/Caps/Foo\",\"children_seeds\":[{\"handle\":\"18446744073709551615\",\"seed\":\"http://www.opensimulator.org/Caps/Foo2\"}],\"child\":false,\"circuit_code\":\"949030\",\"first_name\":\"CoolAvatarTest\",\"last_name\":\"test\",\"inventory_folder\":\"c40b5f5f-476f-496b-bd69-b5a539c434d8\",\"secure_session_id\":\"1e608e2b-0ddb-41f6-be0f-926f61cd3e0a\",\"session_id\":\"aa06f798-9d70-4bdb-9bbf-012a02ee2baf\",\"start_pos\":\"<5, 23, 125>\"}";
- AgentCircuitData Agent1Data = new AgentCircuitData();
- Agent1Data.AgentID = new UUID("522675bd-8214-40c1-b3ca-9c7f7fd170be");
- Agent1Data.Appearance = AvAppearance;
- Agent1Data.BaseFolder = new UUID("c40b5f5f-476f-496b-bd69-b5a539c434d8");
- Agent1Data.CapsPath = CapsPath;
- Agent1Data.child = false;
- Agent1Data.ChildrenCapSeeds = ChildrenCapsPaths;
- Agent1Data.circuitcode = circuitcode;
- Agent1Data.firstname = firstname;
- Agent1Data.InventoryFolder = new UUID("c40b5f5f-476f-496b-bd69-b5a539c434d8");
- Agent1Data.lastname = lastname;
- Agent1Data.SecureSessionID = new UUID("1e608e2b-0ddb-41f6-be0f-926f61cd3e0a");
- Agent1Data.SessionID = new UUID("aa06f798-9d70-4bdb-9bbf-012a02ee2baf");
- Agent1Data.startpos = StartPos;
-
-
- OSDMap map2;
- try
- {
- map2 = (OSDMap) OSDParser.DeserializeJson(oldSerialization);
-
-
- AgentCircuitData Agent2Data = new AgentCircuitData();
- Agent2Data.UnpackAgentCircuitData(map2);
-
- Assert.That((Agent1Data.AgentID == Agent2Data.AgentID));
- Assert.That((Agent1Data.BaseFolder == Agent2Data.BaseFolder));
-
- Assert.That((Agent1Data.CapsPath == Agent2Data.CapsPath));
- Assert.That((Agent1Data.child == Agent2Data.child));
- Assert.That((Agent1Data.ChildrenCapSeeds.Count == Agent2Data.ChildrenCapSeeds.Count));
- Assert.That((Agent1Data.circuitcode == Agent2Data.circuitcode));
- Assert.That((Agent1Data.firstname == Agent2Data.firstname));
- Assert.That((Agent1Data.InventoryFolder == Agent2Data.InventoryFolder));
- Assert.That((Agent1Data.lastname == Agent2Data.lastname));
- Assert.That((Agent1Data.SecureSessionID == Agent2Data.SecureSessionID));
- Assert.That((Agent1Data.SessionID == Agent2Data.SessionID));
- Assert.That((Agent1Data.startpos == Agent2Data.startpos));
- }
- catch (LitJson.JsonException)
- {
- //intermittant litjson errors :P
- Assert.That(1 == 1);
- }
- /*
- Enable this once VisualParams go in the packing method
- for (int i=0;i<208;i++)
- Assert.That((Agent1Data.Appearance.VisualParams[i] == Agent2Data.Appearance.VisualParams[i]));
- */
- }
-
- ///
- /// Test to ensure that the packing and unpacking methods work.
- ///
- [Test]
- public void TestAgentCircuitDataOSDConversion()
- {
- AgentCircuitData Agent1Data = new AgentCircuitData();
- Agent1Data.AgentID = AgentId;
- Agent1Data.Appearance = AvAppearance;
- Agent1Data.BaseFolder = BaseFolder;
- Agent1Data.CapsPath = CapsPath;
- Agent1Data.child = false;
- Agent1Data.ChildrenCapSeeds = ChildrenCapsPaths;
- Agent1Data.circuitcode = circuitcode;
- Agent1Data.firstname = firstname;
- Agent1Data.InventoryFolder = BaseFolder;
- Agent1Data.lastname = lastname;
- Agent1Data.SecureSessionID = SecureSessionId;
- Agent1Data.SessionID = SessionId;
- Agent1Data.startpos = StartPos;
-
- EntityTransferContext ctx = new EntityTransferContext();
- OSDMap map2;
- OSDMap map = Agent1Data.PackAgentCircuitData(ctx);
- try
- {
- string str = OSDParser.SerializeJsonString(map);
- //System.Console.WriteLine(str);
- map2 = (OSDMap) OSDParser.DeserializeJson(str);
- }
- catch (System.NullReferenceException)
- {
- //spurious litjson errors :P
- map2 = map;
- Assert.That(1==1);
- return;
- }
-
- AgentCircuitData Agent2Data = new AgentCircuitData();
- Agent2Data.UnpackAgentCircuitData(map2);
-
- Assert.That((Agent1Data.AgentID == Agent2Data.AgentID));
- Assert.That((Agent1Data.BaseFolder == Agent2Data.BaseFolder));
-
- Assert.That((Agent1Data.CapsPath == Agent2Data.CapsPath));
- Assert.That((Agent1Data.child == Agent2Data.child));
- Assert.That((Agent1Data.ChildrenCapSeeds.Count == Agent2Data.ChildrenCapSeeds.Count));
- Assert.That((Agent1Data.circuitcode == Agent2Data.circuitcode));
- Assert.That((Agent1Data.firstname == Agent2Data.firstname));
- Assert.That((Agent1Data.InventoryFolder == Agent2Data.InventoryFolder));
- Assert.That((Agent1Data.lastname == Agent2Data.lastname));
- Assert.That((Agent1Data.SecureSessionID == Agent2Data.SecureSessionID));
- Assert.That((Agent1Data.SessionID == Agent2Data.SessionID));
- Assert.That((Agent1Data.startpos == Agent2Data.startpos));
-
- /*
- Enable this once VisualParams go in the packing method
- for (int i = 0; i < 208; i++)
- Assert.That((Agent1Data.Appearance.VisualParams[i] == Agent2Data.Appearance.VisualParams[i]));
- */
-
-
- }
- }
-}
diff --git a/OpenSim/Framework/Tests/AgentCircuitManagerTests.cs b/OpenSim/Framework/Tests/AgentCircuitManagerTests.cs
deleted file mode 100644
index 2558f300385..00000000000
--- a/OpenSim/Framework/Tests/AgentCircuitManagerTests.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-using System.Collections.Generic;
-using OpenMetaverse;
-using NUnit.Framework;
-using System;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class AgentCircuitManagerTests
- {
- private AgentCircuitData m_agentCircuitData1;
- private AgentCircuitData m_agentCircuitData2;
- private UUID AgentId1;
- private UUID AgentId2;
- private uint circuitcode1;
- private uint circuitcode2;
-
- private UUID SessionId1;
- private UUID SessionId2;
- private Random rnd = new Random(Environment.TickCount);
-
- [SetUp]
- public void setup()
- {
-
- AgentId1 = UUID.Random();
- AgentId2 = UUID.Random();
- circuitcode1 = (uint) rnd.Next((int)uint.MinValue, int.MaxValue);
- circuitcode2 = (uint) rnd.Next((int)uint.MinValue, int.MaxValue);
- SessionId1 = UUID.Random();
- SessionId2 = UUID.Random();
- UUID BaseFolder = UUID.Random();
- string CapsPath = "http://www.opensimulator.org/Caps/Foo";
- Dictionary ChildrenCapsPaths = new Dictionary();
- ChildrenCapsPaths.Add(ulong.MaxValue, "http://www.opensimulator.org/Caps/Foo2");
- string firstname = "CoolAvatarTest";
- string lastname = "test";
- Vector3 StartPos = new Vector3(5, 23, 125);
-
- UUID SecureSessionId = UUID.Random();
- // TODO: unused: UUID SessionId = UUID.Random();
-
- m_agentCircuitData1 = new AgentCircuitData();
- m_agentCircuitData1.AgentID = AgentId1;
- m_agentCircuitData1.Appearance = new AvatarAppearance();
- m_agentCircuitData1.BaseFolder = BaseFolder;
- m_agentCircuitData1.CapsPath = CapsPath;
- m_agentCircuitData1.child = false;
- m_agentCircuitData1.ChildrenCapSeeds = ChildrenCapsPaths;
- m_agentCircuitData1.circuitcode = circuitcode1;
- m_agentCircuitData1.firstname = firstname;
- m_agentCircuitData1.InventoryFolder = BaseFolder;
- m_agentCircuitData1.lastname = lastname;
- m_agentCircuitData1.SecureSessionID = SecureSessionId;
- m_agentCircuitData1.SessionID = SessionId1;
- m_agentCircuitData1.startpos = StartPos;
-
- m_agentCircuitData2 = new AgentCircuitData();
- m_agentCircuitData2.AgentID = AgentId2;
- m_agentCircuitData2.Appearance = new AvatarAppearance();
- m_agentCircuitData2.BaseFolder = BaseFolder;
- m_agentCircuitData2.CapsPath = CapsPath;
- m_agentCircuitData2.child = false;
- m_agentCircuitData2.ChildrenCapSeeds = ChildrenCapsPaths;
- m_agentCircuitData2.circuitcode = circuitcode2;
- m_agentCircuitData2.firstname = firstname;
- m_agentCircuitData2.InventoryFolder = BaseFolder;
- m_agentCircuitData2.lastname = lastname;
- m_agentCircuitData2.SecureSessionID = SecureSessionId;
- m_agentCircuitData2.SessionID = SessionId2;
- m_agentCircuitData2.startpos = StartPos;
- }
-
- ///
- /// Validate that adding the circuit works appropriately
- ///
- [Test]
- public void AddAgentCircuitTest()
- {
- AgentCircuitManager agentCircuitManager = new AgentCircuitManager();
- agentCircuitManager.AddNewCircuit(circuitcode1,m_agentCircuitData1);
- agentCircuitManager.AddNewCircuit(circuitcode2, m_agentCircuitData2);
- AgentCircuitData agent = agentCircuitManager.GetAgentCircuitData(circuitcode1);
-
- Assert.That((m_agentCircuitData1.AgentID == agent.AgentID));
- Assert.That((m_agentCircuitData1.BaseFolder == agent.BaseFolder));
-
- Assert.That((m_agentCircuitData1.CapsPath == agent.CapsPath));
- Assert.That((m_agentCircuitData1.child == agent.child));
- Assert.That((m_agentCircuitData1.ChildrenCapSeeds.Count == agent.ChildrenCapSeeds.Count));
- Assert.That((m_agentCircuitData1.circuitcode == agent.circuitcode));
- Assert.That((m_agentCircuitData1.firstname == agent.firstname));
- Assert.That((m_agentCircuitData1.InventoryFolder == agent.InventoryFolder));
- Assert.That((m_agentCircuitData1.lastname == agent.lastname));
- Assert.That((m_agentCircuitData1.SecureSessionID == agent.SecureSessionID));
- Assert.That((m_agentCircuitData1.SessionID == agent.SessionID));
- Assert.That((m_agentCircuitData1.startpos == agent.startpos));
- }
-
- ///
- /// Validate that removing the circuit code removes it appropriately
- ///
- [Test]
- public void RemoveAgentCircuitTest()
- {
- AgentCircuitManager agentCircuitManager = new AgentCircuitManager();
- agentCircuitManager.AddNewCircuit(circuitcode1, m_agentCircuitData1);
- agentCircuitManager.AddNewCircuit(circuitcode2, m_agentCircuitData2);
- agentCircuitManager.RemoveCircuit(circuitcode2);
-
- AgentCircuitData agent = agentCircuitManager.GetAgentCircuitData(circuitcode2);
- Assert.That(agent == null);
-
- }
-
- ///
- /// Validate that changing the circuit code works
- ///
- [Test]
- public void ChangeAgentCircuitCodeTest()
- {
- AgentCircuitManager agentCircuitManager = new AgentCircuitManager();
- agentCircuitManager.AddNewCircuit(circuitcode1, m_agentCircuitData1);
- agentCircuitManager.AddNewCircuit(circuitcode2, m_agentCircuitData2);
- bool result = false;
-
- result = agentCircuitManager.TryChangeCircuitCode(circuitcode1, 393930);
-
- AgentCircuitData agent = agentCircuitManager.GetAgentCircuitData(393930);
- AgentCircuitData agent2 = agentCircuitManager.GetAgentCircuitData(circuitcode1);
- Assert.That(agent != null);
- Assert.That(agent2 == null);
- Assert.That(result);
-
- }
-
- ///
- /// Validates that the login authentication scheme is working
- /// First one should be authorized
- /// Rest should not be authorized
- ///
- [Test]
- public void ValidateLoginTest()
- {
- AgentCircuitManager agentCircuitManager = new AgentCircuitManager();
- agentCircuitManager.AddNewCircuit(circuitcode1, m_agentCircuitData1);
- agentCircuitManager.AddNewCircuit(circuitcode2, m_agentCircuitData2);
-
- // should be authorized
- AuthenticateResponse resp = agentCircuitManager.AuthenticateSession(SessionId1, AgentId1, circuitcode1);
- Assert.That(resp.Authorised);
-
-
- //should not be authorized
- resp = agentCircuitManager.AuthenticateSession(SessionId1, UUID.Random(), circuitcode1);
- Assert.That(!resp.Authorised);
-
- resp = agentCircuitManager.AuthenticateSession(UUID.Random(), AgentId1, circuitcode1);
- Assert.That(!resp.Authorised);
-
- resp = agentCircuitManager.AuthenticateSession(SessionId1, AgentId1, circuitcode2);
- Assert.That(!resp.Authorised);
-
- resp = agentCircuitManager.AuthenticateSession(SessionId2, AgentId1, circuitcode2);
- Assert.That(!resp.Authorised);
-
- agentCircuitManager.RemoveCircuit(circuitcode2);
-
- resp = agentCircuitManager.AuthenticateSession(SessionId2, AgentId2, circuitcode2);
- Assert.That(!resp.Authorised);
- }
- }
-}
diff --git a/OpenSim/Framework/Tests/AnimationTests.cs b/OpenSim/Framework/Tests/AnimationTests.cs
deleted file mode 100644
index daf86118755..00000000000
--- a/OpenSim/Framework/Tests/AnimationTests.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Reflection;
-using NUnit.Framework;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using OpenSim.Framework;
-using OpenSim.Tests.Common;
-using Animation = OpenSim.Framework.Animation;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class AnimationTests : OpenSimTestCase
- {
- private Animation anim1 = null;
- private Animation anim2 = null;
- private UUID animUUID1 = UUID.Zero;
- private UUID objUUID1 = UUID.Zero;
- private UUID animUUID2 = UUID.Zero;
- private UUID objUUID2 = UUID.Zero;
-
- [SetUp]
- public void Setup()
- {
- animUUID1 = UUID.Random();
- animUUID2 = UUID.Random();
- objUUID1 = UUID.Random();
- objUUID2 = UUID.Random();
-
- anim1 = new Animation(animUUID1, 1, objUUID1);
- anim2 = new Animation(animUUID2, 1, objUUID2);
- }
-
- [Test]
- public void AnimationOSDTest()
- {
- Assert.That(anim1.AnimID==animUUID1 && anim1.ObjectID == objUUID1 && anim1.SequenceNum ==1, "The Animation Constructor didn't set the fields correctly");
- OSD updateMessage = anim1.PackUpdateMessage();
- Assert.That(updateMessage is OSDMap, "Packed UpdateMessage isn't an OSDMap");
- OSDMap updateMap = (OSDMap) updateMessage;
- Assert.That(updateMap.ContainsKey("animation"), "Packed Message doesn't contain an animation element");
- Assert.That(updateMap.ContainsKey("object_id"), "Packed Message doesn't contain an object_id element");
- Assert.That(updateMap.ContainsKey("seq_num"), "Packed Message doesn't contain a seq_num element");
- Assert.That(updateMap["animation"].AsUUID() == animUUID1);
- Assert.That(updateMap["object_id"].AsUUID() == objUUID1);
- Assert.That(updateMap["seq_num"].AsInteger() == 1);
-
- Animation anim3 = new Animation(updateMap);
-
- Assert.That(anim3.ObjectID == anim1.ObjectID && anim3.AnimID == anim1.AnimID && anim3.SequenceNum == anim1.SequenceNum, "OSDMap Constructor failed to set the properties correctly.");
-
- anim3.UnpackUpdateMessage(anim2.PackUpdateMessage());
-
- Assert.That(anim3.ObjectID == objUUID2 && anim3.AnimID == animUUID2 && anim3.SequenceNum == 1, "Animation.UnpackUpdateMessage failed to set the properties correctly.");
-
- Animation anim4 = new Animation();
- anim4.AnimID = anim2.AnimID;
- anim4.ObjectID = anim2.ObjectID;
- anim4.SequenceNum = anim2.SequenceNum;
-
- Assert.That(anim4.ObjectID == objUUID2 && anim4.AnimID == animUUID2 && anim4.SequenceNum == 1, "void constructor and manual field population failed to set the properties correctly.");
- }
- }
-}
\ No newline at end of file
diff --git a/OpenSim/Framework/Tests/AssetBaseTest.cs b/OpenSim/Framework/Tests/AssetBaseTest.cs
deleted file mode 100644
index 1975a4df7e5..00000000000
--- a/OpenSim/Framework/Tests/AssetBaseTest.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using NUnit.Framework;
-using OpenMetaverse;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class AssetBaseTest : OpenSimTestCase
- {
- [Test]
- public void TestContainsReferences()
- {
- CheckContainsReferences(AssetType.Bodypart, true);
- CheckContainsReferences(AssetType.Clothing, true);
-
- CheckContainsReferences(AssetType.Animation, false);
- CheckContainsReferences(AssetType.CallingCard, false);
- CheckContainsReferences(AssetType.Folder , false);
- CheckContainsReferences(AssetType.Gesture , false);
- CheckContainsReferences(AssetType.ImageJPEG , false);
- CheckContainsReferences(AssetType.ImageTGA , false);
- CheckContainsReferences(AssetType.Landmark , false);
- CheckContainsReferences(AssetType.LSLBytecode, false);
- CheckContainsReferences(AssetType.LSLText, false);
- CheckContainsReferences(AssetType.Notecard, false);
- CheckContainsReferences(AssetType.Object, false);
- CheckContainsReferences(AssetType.Simstate, false);
- CheckContainsReferences(AssetType.Sound, false);
- CheckContainsReferences(AssetType.SoundWAV, false);
- CheckContainsReferences(AssetType.Texture, false);
- CheckContainsReferences(AssetType.TextureTGA, false);
- CheckContainsReferences(AssetType.Unknown, false);
- }
-
- private void CheckContainsReferences(AssetType assetType, bool expected)
- {
- AssetBase asset = new AssetBase(UUID.Zero, String.Empty, (sbyte)assetType, UUID.Zero.ToString());
- bool actual = asset.ContainsReferences;
- Assert.AreEqual(expected, actual, "Expected "+assetType+".ContainsReferences to be "+expected+" but was "+actual+".");
- }
- }
-}
diff --git a/OpenSim/Framework/Tests/CacheTests.cs b/OpenSim/Framework/Tests/CacheTests.cs
deleted file mode 100644
index fc7df692b97..00000000000
--- a/OpenSim/Framework/Tests/CacheTests.cs
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using NUnit.Framework;
-using OpenMetaverse;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class CacheTests : OpenSimTestCase
- {
- private Cache cache;
- private UUID cacheItemUUID;
- [SetUp]
- public void Build()
- {
- cache = new Cache();
- cache = new Cache(CacheMedium.Memory,CacheStrategy.Aggressive,CacheFlags.AllowUpdate);
- cacheItemUUID = UUID.Random();
- MemoryCacheItem cachedItem = new MemoryCacheItem(cacheItemUUID.ToString(),DateTime.Now + TimeSpan.FromDays(1));
- byte[] foo = new byte[1];
- foo[0] = 255;
- cachedItem.Store(foo);
- cache.Store(cacheItemUUID.ToString(), cachedItem);
- }
- [Test]
- public void TestRetreive()
- {
- CacheItemBase citem = (CacheItemBase)cache.Get(cacheItemUUID.ToString());
- byte[] data = (byte[]) citem.Retrieve();
- Assert.That(data.Length == 1, "Cached Item should have one byte element");
- Assert.That(data[0] == 255, "Cached Item element should be 255");
- }
-
- [Test]
- public void TestNotInCache()
- {
- UUID randomNotIn = UUID.Random();
- while (randomNotIn == cacheItemUUID)
- {
- randomNotIn = UUID.Random();
- }
- object citem = cache.Get(randomNotIn.ToString());
- Assert.That(citem == null, "Item should not be in Cache");
- }
-
-
- [Test]
- public void ExpireItemManually()
- {
- UUID ImmediateExpiryUUID = UUID.Random();
- MemoryCacheItem cachedItem = new MemoryCacheItem(ImmediateExpiryUUID.ToString(), TimeSpan.FromDays(1));
- byte[] foo = new byte[1];
- foo[0] = 1;
- cachedItem.Store(foo);
- cache.Store(cacheItemUUID.ToString(), cachedItem);
- cache.Invalidate(cacheItemUUID.ToString());
- cache.Get(cacheItemUUID.ToString());
- object citem = cache.Get(cacheItemUUID.ToString());
- Assert.That(citem == null, "Item should not be in Cache because we manually invalidated it");
- }
-
- [Test]
- public void ClearCacheTest()
- {
- UUID ImmediateExpiryUUID = UUID.Random();
- MemoryCacheItem cachedItem = new MemoryCacheItem(ImmediateExpiryUUID.ToString(), DateTime.Now - TimeSpan.FromDays(1));
- byte[] foo = new byte[1];
- foo[0] = 1;
- cachedItem.Store(foo);
- cache.Store(cacheItemUUID.ToString(), cachedItem);
- cache.Clear();
-
- object citem = cache.Get(cacheItemUUID.ToString());
- Assert.That(citem == null, "Item should not be in Cache because we manually invalidated it");
- }
-
- [Test]
- public void CacheItemMundane()
- {
- UUID Random1 = UUID.Random();
- UUID Random2 = UUID.Random();
- byte[] data = Array.Empty();
- CacheItemBase cb1 = new CacheItemBase(Random1.ToString(), DateTime.Now + TimeSpan.FromDays(1));
- CacheItemBase cb2 = new CacheItemBase(Random2.ToString(), DateTime.Now + TimeSpan.FromDays(1));
- CacheItemBase cb3 = new CacheItemBase(Random1.ToString(), DateTime.Now + TimeSpan.FromDays(1));
-
- cb1.Store(data);
-
- Assert.That(cb1.Equals(cb3), "cb1 should equal cb3, their uuids are the same");
- Assert.That(!cb2.Equals(cb1), "cb2 should not equal cb1, their uuids are NOT the same");
- Assert.That(cb1.IsLocked() == false, "CacheItemBase default is false");
- Assert.That(cb1.Retrieve() == null, "Virtual Retrieve method should return null");
-
-
- }
-
- }
-}
diff --git a/OpenSim/Framework/Tests/LocationTest.cs b/OpenSim/Framework/Tests/LocationTest.cs
deleted file mode 100644
index 5e84026708a..00000000000
--- a/OpenSim/Framework/Tests/LocationTest.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using NUnit.Framework;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class LocationTest : OpenSimTestCase
- {
- [Test]
- public void locationRegionHandleRegionHandle()
- {
- //1099511628032000
- // 256000
- // 256000
- Location TestLocation1 = new Location(1099511628032000);
- Location TestLocation2 = new Location(1099511628032000);
- Assert.That(TestLocation1 == TestLocation2);
-
- TestLocation1 = new Location(1099511628032001);
- TestLocation2 = new Location(1099511628032000);
- Assert.That(TestLocation1 != TestLocation2);
- }
-
- [Test]
- public void locationXYRegionHandle()
- {
- Location TestLocation1 = new Location(255000,256000);
- Location TestLocation2 = new Location(1095216660736000);
- Assert.That(TestLocation1 == TestLocation2);
-
- Assert.That(TestLocation1.X == 255000 && TestLocation1.Y == 256000, "Test xy location doesn't match position in the constructor");
- Assert.That(TestLocation2.X == 255000 && TestLocation2.Y == 256000, "Test xy location doesn't match regionhandle provided");
-
- Assert.That(TestLocation2.RegionHandle == 1095216660736000,
- "Location RegionHandle Property didn't match regionhandle provided in constructor");
-
- ulong RegionHandle = TestLocation1.RegionHandle;
- Assert.That(RegionHandle.Equals(1095216660736000), "Equals(regionhandle) failed to match the position in the constructor");
-
- TestLocation2 = new Location(RegionHandle);
- Assert.That(TestLocation2.Equals(255000, 256000), "Decoded regionhandle failed to match the original position in the constructor");
-
-
- TestLocation1 = new Location(255001, 256001);
- TestLocation2 = new Location(1095216660736000);
- Assert.That(TestLocation1 != TestLocation2);
-
- Assert.That(TestLocation1.Equals(255001, 256001), "Equals(x,y) failed to match the position in the constructor");
-
- Assert.That(TestLocation2.GetHashCode() == (TestLocation2.X.GetHashCode() ^ TestLocation2.Y.GetHashCode()), "GetHashCode failed to produce the expected hashcode");
-
- Location TestLocation3;
- object cln = TestLocation2.Clone();
- TestLocation3 = (Location) cln;
- Assert.That(TestLocation3.X == TestLocation2.X && TestLocation3.Y == TestLocation2.Y,
- "Cloned Location values do not match");
-
- Assert.That(TestLocation2.Equals(cln), "Cloned object failed .Equals(obj) Test");
-
- }
-
- }
-}
diff --git a/OpenSim/Framework/Tests/MundaneFrameworkTests.cs b/OpenSim/Framework/Tests/MundaneFrameworkTests.cs
deleted file mode 100644
index 3d99c412246..00000000000
--- a/OpenSim/Framework/Tests/MundaneFrameworkTests.cs
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using NUnit.Framework;
-using OpenSim.Framework;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using System;
-using System.Globalization;
-using System.Threading;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class MundaneFrameworkTests : OpenSimTestCase
- {
- private bool m_RegionSettingsOnSaveEventFired;
-
- [Test]
- public void ChildAgentDataUpdate01()
- {
- // code coverage
- ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
- Assert.IsFalse(cadu.alwaysrun, "Default is false");
- }
-
- [Test]
- public void AgentPositionTest01()
- {
- UUID AgentId1 = UUID.Random();
- UUID SessionId1 = UUID.Random();
- uint CircuitCode1 = uint.MinValue;
- Vector3 Size1 = Vector3.UnitZ;
- Vector3 Position1 = Vector3.UnitX;
- Vector3 LeftAxis1 = Vector3.UnitY;
- Vector3 UpAxis1 = Vector3.UnitZ;
- Vector3 AtAxis1 = Vector3.UnitX;
-
- ulong RegionHandle1 = ulong.MinValue;
- byte[] Throttles1 = new byte[] {0, 1, 0};
-
- Vector3 Velocity1 = Vector3.Zero;
- float Far1 = 256;
-
- bool ChangedGrid1 = false;
- Vector3 Center1 = Vector3.Zero;
-
- AgentPosition position1 = new AgentPosition();
- position1.AgentID = AgentId1;
- position1.SessionID = SessionId1;
- position1.CircuitCode = CircuitCode1;
- position1.Size = Size1;
- position1.Position = Position1;
- position1.LeftAxis = LeftAxis1;
- position1.UpAxis = UpAxis1;
- position1.AtAxis = AtAxis1;
- position1.RegionHandle = RegionHandle1;
- position1.Throttles = Throttles1;
- position1.Velocity = Velocity1;
- position1.Far = Far1;
- position1.ChangedGrid = ChangedGrid1;
- position1.Center = Center1;
-
- ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
- cadu.AgentID = AgentId1.Guid;
- cadu.ActiveGroupID = UUID.Zero.Guid;
- cadu.throttles = Throttles1;
- cadu.drawdistance = Far1;
- cadu.Position = Position1;
- cadu.Velocity = Velocity1;
- cadu.regionHandle = RegionHandle1;
- cadu.cameraPosition = Center1;
- cadu.AVHeight = Size1.Z;
-
- AgentPosition position2 = new AgentPosition();
- position2.CopyFrom(cadu, position1.SessionID);
-
- Assert.IsTrue(
- position2.AgentID == position1.AgentID
- && position2.Size == position1.Size
- && position2.Position == position1.Position
- && position2.Velocity == position1.Velocity
- && position2.Center == position1.Center
- && position2.RegionHandle == position1.RegionHandle
- && position2.Far == position1.Far
-
- ,"Copy From ChildAgentDataUpdate failed");
-
- position2 = new AgentPosition();
-
- Assert.IsFalse(position2.AgentID == position1.AgentID, "Test Error, position2 should be a blank uninitialized AgentPosition");
- EntityTransferContext ctx = new EntityTransferContext();
- position2.Unpack(position1.Pack(ctx), null, ctx);
-
- Assert.IsTrue(position2.AgentID == position1.AgentID, "Agent ID didn't unpack the same way it packed");
- Assert.IsTrue(position2.Position == position1.Position, "Position didn't unpack the same way it packed");
- Assert.IsTrue(position2.Velocity == position1.Velocity, "Velocity didn't unpack the same way it packed");
- Assert.IsTrue(position2.SessionID == position1.SessionID, "SessionID didn't unpack the same way it packed");
- Assert.IsTrue(position2.CircuitCode == position1.CircuitCode, "CircuitCode didn't unpack the same way it packed");
- Assert.IsTrue(position2.LeftAxis == position1.LeftAxis, "LeftAxis didn't unpack the same way it packed");
- Assert.IsTrue(position2.UpAxis == position1.UpAxis, "UpAxis didn't unpack the same way it packed");
- Assert.IsTrue(position2.AtAxis == position1.AtAxis, "AtAxis didn't unpack the same way it packed");
- Assert.IsTrue(position2.RegionHandle == position1.RegionHandle, "RegionHandle didn't unpack the same way it packed");
- Assert.IsTrue(position2.ChangedGrid == position1.ChangedGrid, "ChangedGrid didn't unpack the same way it packed");
- Assert.IsTrue(position2.Center == position1.Center, "Center didn't unpack the same way it packed");
- Assert.IsTrue(position2.Size == position1.Size, "Size didn't unpack the same way it packed");
-
- }
-
- [Test]
- public void RegionSettingsTest01()
- {
- RegionSettings settings = new RegionSettings();
- settings.OnSave += RegionSaveFired;
- settings.Save();
- settings.OnSave -= RegionSaveFired;
-
-// string str = settings.LoadedCreationDate;
-// int dt = settings.LoadedCreationDateTime;
-// string id = settings.LoadedCreationID;
-// string time = settings.LoadedCreationTime;
-
- Assert.That(m_RegionSettingsOnSaveEventFired, "RegionSettings Save Event didn't Fire");
-
- }
- public void RegionSaveFired(RegionSettings settings)
- {
- m_RegionSettingsOnSaveEventFired = true;
- }
-
- [Test]
- public void InventoryItemBaseConstructorTest01()
- {
- InventoryItemBase b1 = new InventoryItemBase();
- Assert.That(b1.ID == UUID.Zero, "void constructor should create an inventory item with ID = UUID.Zero");
- Assert.That(b1.Owner == UUID.Zero, "void constructor should create an inventory item with Owner = UUID.Zero");
-
- UUID ItemID = UUID.Random();
- UUID OwnerID = UUID.Random();
-
- InventoryItemBase b2 = new InventoryItemBase(ItemID);
- Assert.That(b2.ID == ItemID, "ID constructor should create an inventory item with ID = ItemID");
- Assert.That(b2.Owner == UUID.Zero, "ID constructor should create an inventory item with Owner = UUID.Zero");
-
- InventoryItemBase b3 = new InventoryItemBase(ItemID,OwnerID);
- Assert.That(b3.ID == ItemID, "ID,OwnerID constructor should create an inventory item with ID = ItemID");
- Assert.That(b3.Owner == OwnerID, "ID,OwnerID constructor should create an inventory item with Owner = OwnerID");
-
- }
-
- [Test]
- public void AssetMetaDataNonNullContentTypeTest01()
- {
- AssetMetadata assetMetadata = new AssetMetadata();
- assetMetadata.ContentType = "image/jp2";
- Assert.That(assetMetadata.Type == (sbyte)AssetType.Texture, "Content type should be AssetType.Texture");
- Assert.That(assetMetadata.ContentType == "image/jp2", "Text of content type should be image/jp2");
- UUID rndID = UUID.Random();
- assetMetadata.ID = rndID.ToString();
- Assert.That(assetMetadata.ID.ToLower() == rndID.ToString().ToLower(), "assetMetadata.ID Setter/Getter not Consistent");
- DateTime fixedTime = DateTime.Now;
- assetMetadata.CreationDate = fixedTime;
- }
-
- [Test]
- public void EstateSettingsMundateTests()
- {
- EstateSettings es = new EstateSettings();
- es.AddBan(null);
- UUID bannedUserId = UUID.Random();
- es.AddBan(new EstateBan()
- { BannedHostAddress = string.Empty,
- BannedHostIPMask = string.Empty,
- BannedHostNameMask = string.Empty,
- BannedUserID = bannedUserId}
- );
- Assert.IsTrue(es.IsBanned(bannedUserId, 32), "User Should be banned but is not.");
- Assert.IsFalse(es.IsBanned(UUID.Zero, 32), "User Should not be banned but is.");
-
- es.RemoveBan(bannedUserId);
-
- Assert.IsFalse(es.IsBanned(bannedUserId, 32), "User Should not be banned but is.");
-
- es.AddEstateManager(UUID.Zero);
-
- es.AddEstateManager(bannedUserId);
- Assert.IsTrue(es.IsEstateManagerOrOwner(bannedUserId), "bannedUserId should be EstateManager but isn't.");
-
- es.RemoveEstateManager(bannedUserId);
- Assert.IsFalse(es.IsEstateManagerOrOwner(bannedUserId), "bannedUserID is estateManager but shouldn't be");
-
- Assert.IsFalse(es.HasAccess(bannedUserId), "bannedUserID has access but shouldn't");
-
- es.AddEstateUser(bannedUserId);
-
- Assert.IsTrue(es.HasAccess(bannedUserId), "bannedUserID doesn't have access but should");
- es.RemoveEstateUser(bannedUserId);
-
- es.AddEstateManager(bannedUserId);
-
- Assert.IsTrue(es.HasAccess(bannedUserId), "bannedUserID doesn't have access but should");
-
- Assert.That(es.EstateGroups.Length == 0, "No Estate Groups Added.. so the array should be 0 length");
-
- es.AddEstateGroup(bannedUserId);
-
- Assert.That(es.EstateGroups.Length == 1, "1 Estate Groups Added.. so the array should be 1 length");
-
- Assert.That(es.EstateGroups[0] == bannedUserId,"User ID should be in EstateGroups");
-
- }
-
- [Test]
- public void InventoryFolderBaseConstructorTest01()
- {
- UUID uuid1 = UUID.Random();
- UUID uuid2 = UUID.Random();
-
- InventoryFolderBase fld = new InventoryFolderBase(uuid1);
- Assert.That(fld.ID == uuid1, "ID constructor failed to save value in ID field.");
-
- fld = new InventoryFolderBase(uuid1, uuid2);
- Assert.That(fld.ID == uuid1, "ID,Owner constructor failed to save value in ID field.");
- Assert.That(fld.Owner == uuid2, "ID,Owner constructor failed to save value in ID field.");
- }
-
- [Test]
- public void AsssetBaseConstructorTest01()
- {
- AssetBase abase = new AssetBase();
- Assert.IsNotNull(abase.Metadata, "void constructor of AssetBase should have created a MetaData element but didn't.");
- UUID itemID = UUID.Random();
- UUID creatorID = UUID.Random();
- abase = new AssetBase(itemID.ToString(), "test item", (sbyte) AssetType.Texture, creatorID.ToString());
-
- Assert.IsNotNull(abase.Metadata, "string,string,sbyte,string constructor of AssetBase should have created a MetaData element but didn't.");
- Assert.That(abase.ID == itemID.ToString(), "string,string,sbyte,string constructor failed to set ID property");
- Assert.That(abase.Metadata.CreatorID == creatorID.ToString(), "string,string,sbyte,string constructor failed to set Creator ID");
-
-
- abase = new AssetBase(itemID.ToString(), "test item", -1, creatorID.ToString());
- Assert.IsNotNull(abase.Metadata, "string,string,sbyte,string constructor of AssetBase with unknown type should have created a MetaData element but didn't.");
- Assert.That(abase.Metadata.Type == -1, "Unknown Type passed to string,string,sbyte,string constructor and was a known type when it came out again");
-
- AssetMetadata metts = new AssetMetadata();
- metts.FullID = itemID;
- metts.ID = string.Empty;
- metts.Name = "test item";
- abase.Metadata = metts;
-
- Assert.That(abase.ToString() == itemID.ToString(), "ToString is overriden to be fullID.ToString()");
- Assert.That(abase.ID == itemID.ToString(),"ID should be MetaData.FullID.ToString() when string.empty or null is provided to the ID property");
- }
-
- [Test]
- public void CultureSetCultureTest01()
- {
- CultureInfo ci = new CultureInfo("en-US", false);
- Culture.SetCurrentCulture();
- Assert.That(Thread.CurrentThread.CurrentCulture.Name == ci.Name, "SetCurrentCulture failed to set thread culture to en-US");
-
- }
- }
-}
diff --git a/OpenSim/Framework/Tests/OpenSim.Framework.Tests.csproj b/OpenSim/Framework/Tests/OpenSim.Framework.Tests.csproj
deleted file mode 100644
index 9a85b9f3921..00000000000
--- a/OpenSim/Framework/Tests/OpenSim.Framework.Tests.csproj
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
- net48
-
-
-
-
-
-
-
-
-
- ..\..\..\bin\Nini.dll
- False
-
-
- ..\..\..\bin\OpenMetaverse.dll
- False
-
-
- ..\..\..\bin\OpenMetaverse.StructuredData.dll
- False
-
-
- ..\..\..\bin\OpenMetaverseTypes.dll
- False
-
-
- ..\..\..\bin\XMLRPC.dll
- False
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs b/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs
deleted file mode 100644
index cc30fb97d6a..00000000000
--- a/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Reflection;
-using NUnit.Framework;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using OpenSim.Framework;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class PrimeNumberHelperTests : OpenSimTestCase
- {
- [Test]
- public void TestGetPrime()
- {
- int prime1 = PrimeNumberHelper.GetPrime(7919);
- Assert.That(prime1 == 8419, "Prime Number Get Prime Failed, 7919 is prime");
- Assert.That(PrimeNumberHelper.IsPrime(prime1),"Prime1 should be prime");
- Assert.That(PrimeNumberHelper.IsPrime(7919), "7919 is prime but is falsely failing the prime test");
- prime1 = PrimeNumberHelper.GetPrime(Int32.MaxValue - 1);
- Assert.That(prime1 == -1, "prime1 should have been -1 since there are no primes between Int32.MaxValue-1 and Int32.MaxValue");
-
- }
-
- [Test]
- public void Test1000SmallPrimeNumbers()
- {
- int[] primes = {
- 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
- 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191
- , 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283,
- 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401,
- 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
- 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631,
- 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751,
- 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877,
- 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009,
- 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
- 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217,
- 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
- 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447,
- 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549,
- 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637,
- 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759,
- 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879,
- 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003,
- 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113,
- 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
- 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351,
- 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459,
- 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609,
- 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707,
- 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803,
- 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939,
- 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067,
- 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
- 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329,
- 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461,
- 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559,
- 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677,
- 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803,
- 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923,
- 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051,
- 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
- 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289,
- 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447,
- 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567,
- 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691,
- 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817,
- 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967,
- 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081,
- 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227,
- 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381,
- 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479,
- 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623,
- 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737,
- 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851,
- 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007,
- 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131,
- 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263,
- 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361,
- 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529,
- 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661,
- 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791,
- 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911,
- 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027,
- 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193,
- 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331,
- 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489,
- 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589,
- 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717,
- 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873,
- 7877, 7879, 7883, 7901, 7907, 7919
- };
- for (int i = 0; i < primes.Length; i++)
- {
- Assert.That(PrimeNumberHelper.IsPrime(primes[i]),primes[i] + " is prime but is erroniously failing the prime test");
- }
-
- int[] nonprimes = {
- 4, 6, 8, 10, 14, 16, 18, 22, 28, 30, 36, 40, 42, 46, 52, 58, 60, 66, 70, 72, 78, 82, 88,
- 96, 366, 372, 378, 382, 388, 396, 400, 408, 418, 420, 430, 432, 438, 442, 448, 456, 460, 462,
- 466, 478, 486, 490, 498, 502, 508, 856, 858, 862, 876, 880, 882, 886, 906, 910, 918, 928, 936,
- 940, 946, 952, 966, 970, 976, 982, 990, 996, 1008, 1740, 1746, 1752, 1758, 4650, 4656, 4662,
- 4672, 4678, 4690, 7740, 7752, 7756, 7758, 7788, 7792, 7816, 7822, 7828, 7840, 7852, 7866, 7872,
- 7876, 7878, 7882, 7900, 7906, 7918
- };
- for (int i = 0; i < nonprimes.Length; i++)
- {
- Assert.That(!PrimeNumberHelper.IsPrime(nonprimes[i]), nonprimes[i] + " is not prime but is erroniously passing the prime test");
- }
-
- Assert.That(PrimeNumberHelper.IsPrime(3));
- }
- }
-}
\ No newline at end of file
diff --git a/OpenSim/Framework/Tests/UtilTest.cs b/OpenSim/Framework/Tests/UtilTest.cs
deleted file mode 100644
index b3d79eec971..00000000000
--- a/OpenSim/Framework/Tests/UtilTest.cs
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using NUnit.Framework;
-using OpenMetaverse;
-using OpenSim.Tests.Common;
-
-namespace OpenSim.Framework.Tests
-{
- [TestFixture]
- public class UtilTests : OpenSimTestCase
- {
- [Test]
- public void VectorOperationTests()
- {
- Vector3 v1, v2;
- double expectedDistance;
- double expectedMagnitude;
- double lowPrecisionTolerance = 0.001;
-
- //Lets test a simple case of <0,0,0> and <5,5,5>
- {
- v1 = new Vector3(0, 0, 0);
- v2 = new Vector3(5, 5, 5);
- expectedDistance = 8.66;
- Assert.That(Util.GetDistanceTo(v1, v2),
- new DoubleToleranceConstraint(expectedDistance, lowPrecisionTolerance),
- "Calculated distance between two vectors was not within tolerances.");
-
- expectedMagnitude = 0;
- Assert.That(Util.GetMagnitude(v1), Is.EqualTo(0), "Magnitude of null vector was not zero.");
-
- expectedMagnitude = 8.66;
- Assert.That(Util.GetMagnitude(v2),
- new DoubleToleranceConstraint(expectedMagnitude, lowPrecisionTolerance),
- "Magnitude of vector was incorrect.");
-/*
- TestDelegate d = delegate() { Util.GetNormalizedVector(v1); };
- bool causesArgumentException = TestHelpers.AssertThisDelegateCausesArgumentException(d);
- Assert.That(causesArgumentException, Is.True,
- "Getting magnitude of null vector did not cause argument exception.");
-*/
- Vector3 expectedNormalizedVector = new Vector3(.577f, .577f, .577f);
- double expectedNormalizedMagnitude = 1;
- Vector3 normalizedVector = Util.GetNormalizedVector(v2);
- Assert.That(normalizedVector,
- new VectorToleranceConstraint(expectedNormalizedVector, lowPrecisionTolerance),
- "Normalized vector generated from vector was not what was expected.");
- Assert.That(Util.GetMagnitude(normalizedVector),
- new DoubleToleranceConstraint(expectedNormalizedMagnitude, lowPrecisionTolerance),
- "Normalized vector generated from vector does not have magnitude of 1.");
- }
-
- //Lets test a simple case of <0,0,0> and <0,0,0>
- {
- v1 = new Vector3(0, 0, 0);
- v2 = new Vector3(0, 0, 0);
- expectedDistance = 0;
- Assert.That(Util.GetDistanceTo(v1, v2),
- new DoubleToleranceConstraint(expectedDistance, lowPrecisionTolerance),
- "Calculated distance between two vectors was not within tolerances.");
-
- expectedMagnitude = 0;
- Assert.That(Util.GetMagnitude(v1), Is.EqualTo(0), "Magnitude of null vector was not zero.");
-
- expectedMagnitude = 0;
- Assert.That(Util.GetMagnitude(v2),
- new DoubleToleranceConstraint(expectedMagnitude, lowPrecisionTolerance),
- "Magnitude of vector was incorrect.");
-/*
- TestDelegate d = delegate() { Util.GetNormalizedVector(v1); };
- bool causesArgumentException = TestHelpers.AssertThisDelegateCausesArgumentException(d);
- Assert.That(causesArgumentException, Is.True,
- "Getting magnitude of null vector did not cause argument exception.");
-
- d = delegate() { Util.GetNormalizedVector(v2); };
- causesArgumentException = TestHelpers.AssertThisDelegateCausesArgumentException(d);
- Assert.That(causesArgumentException, Is.True,
- "Getting magnitude of null vector did not cause argument exception.");
-*/
- }
-
- //Lets test a simple case of <0,0,0> and <-5,-5,-5>
- {
- v1 = new Vector3(0, 0, 0);
- v2 = new Vector3(-5, -5, -5);
- expectedDistance = 8.66;
- Assert.That(Util.GetDistanceTo(v1, v2),
- new DoubleToleranceConstraint(expectedDistance, lowPrecisionTolerance),
- "Calculated distance between two vectors was not within tolerances.");
-
- expectedMagnitude = 0;
- Assert.That(Util.GetMagnitude(v1), Is.EqualTo(0), "Magnitude of null vector was not zero.");
-
- expectedMagnitude = 8.66;
- Assert.That(Util.GetMagnitude(v2),
- new DoubleToleranceConstraint(expectedMagnitude, lowPrecisionTolerance),
- "Magnitude of vector was incorrect.");
-/*
- TestDelegate d = delegate() { Util.GetNormalizedVector(v1); };
- bool causesArgumentException = TestHelpers.AssertThisDelegateCausesArgumentException(d);
- Assert.That(causesArgumentException, Is.True,
- "Getting magnitude of null vector did not cause argument exception.");
-*/
- Vector3 expectedNormalizedVector = new Vector3(-.577f, -.577f, -.577f);
- double expectedNormalizedMagnitude = 1;
- Vector3 normalizedVector = Util.GetNormalizedVector(v2);
- Assert.That(normalizedVector,
- new VectorToleranceConstraint(expectedNormalizedVector, lowPrecisionTolerance),
- "Normalized vector generated from vector was not what was expected.");
- Assert.That(Util.GetMagnitude(normalizedVector),
- new DoubleToleranceConstraint(expectedNormalizedMagnitude, lowPrecisionTolerance),
- "Normalized vector generated from vector does not have magnitude of 1.");
- }
- }
-
- [Test]
- public void UUIDTests()
- {
- Assert.IsTrue(Util.isUUID("01234567-89ab-Cdef-0123-456789AbCdEf"),
- "A correct UUID wasn't recognized.");
- Assert.IsFalse(Util.isUUID("FOOBAR67-89ab-Cdef-0123-456789AbCdEf"),
- "UUIDs with non-hex characters are recognized as correct UUIDs.");
- Assert.IsFalse(Util.isUUID("01234567"),
- "Too short UUIDs are recognized as correct UUIDs.");
- Assert.IsFalse(Util.isUUID("01234567-89ab-Cdef-0123-456789AbCdEf0"),
- "Too long UUIDs are recognized as correct UUIDs.");
- Assert.IsFalse(Util.isUUID("01234567-89ab-Cdef-0123+456789AbCdEf"),
- "UUIDs with wrong format are recognized as correct UUIDs.");
- }
-
- [Test]
- public void GetHashGuidTests()
- {
- string string1 = "This is one string";
- string string2 = "This is another";
-
- // Two consecutive runs should equal the same
- Assert.AreEqual(Util.GetHashGuid(string1, "secret1"), Util.GetHashGuid(string1, "secret1"));
- Assert.AreEqual(Util.GetHashGuid(string2, "secret1"), Util.GetHashGuid(string2, "secret1"));
-
- // Varying data should not eqal the same
- Assert.AreNotEqual(Util.GetHashGuid(string1, "secret1"), Util.GetHashGuid(string2, "secret1"));
-
- // Varying secrets should not eqal the same
- Assert.AreNotEqual(Util.GetHashGuid(string1, "secret1"), Util.GetHashGuid(string1, "secret2"));
- }
-
- [Test]
- public void SLUtilTypeConvertTests()
- {
- int[] assettypes = new int[]{-1,0,1,2,3,5,6,7,8,10,11,12,13,17,18,19,20,21,22
- ,24,25};
- string[] contenttypes = new string[]
- {
- "application/octet-stream",
- "image/x-j2c",
- "audio/ogg",
- "application/vnd.ll.callingcard",
- "application/vnd.ll.landmark",
- "application/vnd.ll.clothing",
- "application/vnd.ll.primitive",
- "application/vnd.ll.notecard",
- "application/vnd.ll.folder",
- "application/vnd.ll.lsltext",
- "application/vnd.ll.lslbyte",
- "image/tga",
- "application/vnd.ll.bodypart",
- "audio/x-wav",
- "image/tga",
- "image/jpeg",
- "application/vnd.ll.animation",
- "application/vnd.ll.gesture",
- "application/x-metaverse-simstate",
- "application/vnd.ll.link",
- "application/vnd.ll.linkfolder",
- };
- for (int i=0;i
public class ThreadSafeRandom : Random
{
+ private readonly object mainLock = new();
public ThreadSafeRandom() : base() {}
public ThreadSafeRandom(int seed): base (seed) {}
public override int Next()
{
- lock (this)
+ lock (mainLock)
return base.Next();
}
public override int Next(int maxValue)
{
- lock (this)
+ lock (mainLock)
return base.Next(maxValue);
}
public override int Next(int minValue, int maxValue)
{
- lock (this)
+ lock (mainLock)
return base.Next(minValue, maxValue);
}
public override void NextBytes(byte[] buffer)
{
- lock (this)
+ lock (mainLock)
base.NextBytes(buffer);
}
public override double NextDouble()
{
- lock (this)
+ lock (mainLock)
return base.NextDouble();
}
}
diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs
index af8b4c18aac..bc4b00f3ee1 100644
--- a/OpenSim/Framework/Util.cs
+++ b/OpenSim/Framework/Util.cs
@@ -55,8 +55,7 @@
using OpenMetaverse.StructuredData;
using Amib.Threading;
using System.Collections.Concurrent;
-using System.Collections.Specialized;
-using System.Web;
+using System.Net.Http;
namespace OpenSim.Framework
{
@@ -164,16 +163,29 @@ static Util()
LogOverloads = true;
TimeStampClockPeriod = 1.0D / (double)Stopwatch.Frequency;
TimeStampClockPeriodMS = 1e3 * TimeStampClockPeriod;
- m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS, 6, MidpointRounding.AwayFromZero));
+ m_log.Info($"[UTIL] TimeStamp clock with period of {Math.Round(TimeStampClockPeriodMS, 6, MidpointRounding.AwayFromZero)}ms");
}
private static uint nextXferID = 5000;
- private static readonly Random randomClass = new ThreadSafeRandom();
// Get a list of invalid file characters (OS dependent)
- private static readonly string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
- private static readonly string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
- private static readonly object XferLock = new object();
+ private static readonly string regexInvalidFileChars = $"[{new String(Path.GetInvalidFileNameChars())}]";
+ private static readonly string regexInvalidPathChars = $"[{new String(Path.GetInvalidPathChars())}]";
+ private static readonly object XferLock = new();
+
+ public static readonly char[] SplitCommaArray = new char[] { ',' };
+ public static readonly char[] SplitDotArray = new char[] { '.' };
+ public static readonly char[] SplitColonArray = new char[] { ':' };
+ public static readonly char[] SplitSemicolonArray = new char[] { ';' };
+ public static readonly char[] SplitSlashArray = new char[] { '/' };
+
+ public static readonly XmlReaderSettings SharedXmlReaderSettings = new()
+ {
+ IgnoreWhitespace = true,
+ ConformanceLevel = ConformanceLevel.Fragment,
+ DtdProcessing = DtdProcessing.Ignore,
+ MaxCharactersInDocument = 10_000_000
+ };
///
/// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
@@ -189,18 +201,15 @@ static Util()
private static readonly string rawUUIDPattern
= "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
- public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
- public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
+ public static readonly Regex PermissiveUUIDPattern = new(rawUUIDPattern);
+ public static readonly Regex UUIDPattern = new(string.Format("^{0}$", rawUUIDPattern));
public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
public static readonly string UUIDZeroString = UUID.Zero.ToString();
- public static bool IsPlatformMono
- {
- get { return Type.GetType("Mono.Runtime") != null; }
- }
+ public const bool IsPlatformMono = false;
///
/// Gets the name of the directory where the current running executable
@@ -213,38 +222,16 @@ public static string ExecutingDirectory()
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
- // next should be replaced using .net5 system numerics bitoperations log2
- // this is just log2 + 1
- private static byte[] nBitsLookup =
- {
- 01, 10, 02, 11, 14, 22, 03, 30, 12, 15, 17, 19, 23, 26, 04, 31,
- 09, 13, 21, 29, 16, 18, 25, 08, 20, 28, 24, 07, 27, 06, 05, 32
- };
-
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int NumberBits(uint n)
{
- n |= (n >> 1);
- n |= (n >> 2);
- n |= (n >> 4);
- n |= (n >> 8);
- n |= (n >> 16);
- return nBitsLookup[(n * 0x07C4ACDDu) >> 27];
+ return System.Numerics.BitOperations.Log2(n) + 1;
}
- private static byte[] intLog2Lookup =
- {
- 00, 09, 01, 10, 13, 21, 02, 29, 11, 14, 16, 18, 22, 25, 03, 30,
- 08, 12, 20, 28, 15, 17, 24, 07, 19, 27, 23, 06, 26, 05, 04, 31
- };
-
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int intLog2(uint n)
{
- n |= (n >> 1);
- n |= (n >> 2);
- n |= (n >> 4);
- n |= (n >> 8);
- n |= (n >> 16);
- return intLog2Lookup[(n * 0x07C4ACDDu) >> 27];
+ return System.Numerics.BitOperations.Log2(n);
}
///
@@ -297,7 +284,7 @@ public static byte[] UTF8NBGetbytes(string s)
///
/// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
///
- public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
+ public static UUID BLANK_TEXTURE_UUID = new("5748decc-f629-461c-9a36-a35a221fe21f");
#region Vector Equations
@@ -342,7 +329,7 @@ public static double GetMagnitude(Vector3 a)
public static Vector3 GetNormalizedVector(Vector3 a)
{
- Vector3 v = new Vector3(a.X, a.Y, a.Z);
+ Vector3 v = new(a.X, a.Y, a.Z);
v.Normalize();
return v;
}
@@ -366,11 +353,11 @@ public static bool IsZeroVector(Vector3 v)
public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
{
float s;
- float tr = (float)(fwd.X + left.Y + up.Z + 1.0);
+ float tr = (fwd.X + left.Y + up.Z + 1.0f);
if (tr >= 1.0)
{
- s = (float)(0.5 / Math.Sqrt(tr));
+ s = 0.5f / MathF.Sqrt(tr);
return new Quaternion(
(left.Z - up.Y) * s,
(up.X - fwd.Z) * s,
@@ -383,9 +370,9 @@ public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
if (max < fwd.X)
{
- s = (float)(Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
- float x = (float)(s * 0.5);
- s = (float)(0.5 / s);
+ s = MathF.Sqrt(fwd.X - (left.Y + up.Z) + 1.0f);
+ float x = s * 0.5f;
+ s = 0.5f / s;
return new Quaternion(
x,
(fwd.Y + left.X) * s,
@@ -394,9 +381,9 @@ public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
}
else if (max == left.Y)
{
- s = (float)(Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
- float y = (float)(s * 0.5);
- s = (float)(0.5 / s);
+ s = MathF.Sqrt(left.Y - (up.Z + fwd.X) + 1.0f);
+ float y = s * 0.5f;
+ s = 0.5f / s;
return new Quaternion(
(fwd.Y + left.X) * s,
y,
@@ -405,9 +392,9 @@ public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
}
else
{
- s = (float)(Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
- float z = (float)(s * 0.5);
- s = (float)(0.5 / s);
+ s = MathF.Sqrt(up.Z - (fwd.X + left.Y) + 1.0f);
+ float z = s * 0.5f;
+ s = 0.5f / s;
return new Quaternion(
(up.X + fwd.Z) * s,
(left.Z + up.Y) * s,
@@ -417,9 +404,10 @@ public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
}
}
+ // legacy, do not use
public static Random RandomClass
{
- get { return randomClass; }
+ get { return Random.Shared;}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -435,7 +423,7 @@ public static ulong UIntsToLong(uint X, uint Y)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong RegionWorldLocToHandle(uint X, uint Y)
{
- ulong handle = X & 0xffffff00; // make sure it matchs grid coord points.
+ ulong handle = X & 0xffffff00; // make sure it matches grid coord points.
handle <<= 32; // to higher half
handle |= (Y & 0xffffff00);
return handle;
@@ -525,17 +513,16 @@ public static bool CompareRegionHandles(ulong handle, Vector3 handleOffset, int
public static bool checkServiceURI(string uristr, out string serviceURI, out string serviceHost, out string serviceIPstr)
{
- serviceURI = string.Empty;
serviceHost = string.Empty;
serviceIPstr = string.Empty;
try
{
- Uri uri = new Uri(uristr);
+ Uri uri = new(uristr);
serviceURI = uri.AbsoluteUri;
if (uri.Port == 80)
- serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) + ":80/";
+ serviceURI = $"{serviceURI.Trim(new char[] { '/', ' ' })}:80/";
else if (uri.Port == 443)
- serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) + ":443/";
+ serviceURI = $"{serviceURI.Trim(new char[] { '/', ' ' })}:443/";
serviceHost = uri.Host;
IPEndPoint ep = Util.getEndPoint(serviceHost, uri.Port);
@@ -571,7 +558,7 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
string host;
int port = 80;
- string[] parts = inputName.Split(new char[] { ':' });
+ string[] parts = inputName.Split(Util.SplitColonArray);
int indx;
if (parts.Length == 0)
return false;
@@ -579,12 +566,12 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
{
indx = inputName.IndexOf('/');
if (indx < 0)
- serverURI = "http://" + inputName + "/";
+ serverURI = $"http://{inputName}/";
else
{
- serverURI = "http://" + inputName.Substring(0, indx + 1);
+ serverURI = $"http://{inputName[..(indx + 1)]}";
if (indx + 2 < inputName.Length)
- regionName = inputName.Substring(indx + 1);
+ regionName = inputName[(indx + 1)..];
}
}
else
@@ -605,9 +592,9 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
}
else
{
- string portstr = parts[1].Substring(0, indx);
+ string portstr = parts[1][..indx];
if (indx + 2 < parts[1].Length)
- regionName = parts[1].Substring(indx + 1);
+ regionName = parts[1][(indx + 1)..];
if (!int.TryParse(portstr, out port))
port = 80;
}
@@ -618,7 +605,7 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
regionName = parts[2];
}
- serverURI = "http://" + host + ":" + port.ToString() + "/";
+ serverURI = $"http://{host}:{port}/";
}
}
else
@@ -627,7 +614,7 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
// http://grid.example.com "region name"
// http://grid.example.com
- string[] parts = inputName.Split(new char[] { ' ' });
+ string[] parts = inputName.Split();
if (parts.Length == 0)
return false;
@@ -638,12 +625,12 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
if (indx > 10)
{
if (indx + 2 < inputName.Length)
- regionName = inputName.Substring(indx + 1);
- serverURI = inputName.Substring(0, indx + 1);
+ regionName = inputName[(indx + 1)..];
+ serverURI = inputName[..(indx + 1)];
}
else if (parts.Length >= 2)
{
- regionName = inputName.Substring(serverURI.Length);
+ regionName = inputName[serverURI.Length..];
}
}
@@ -662,9 +649,9 @@ public static bool buildHGRegionURI(string inputName, out string serverURI, out
regionName = regionName.Trim(new char[] { '"', ' ' });
serverURI = uri.AbsoluteUri;
if (uri.Port == 80)
- serverURI = serverURI.Trim(new char[] { '/', ' ' }) + ":80/";
+ serverURI = $"{serverURI.Trim(new char[] { '/', ' ' })}:80/";
else if (uri.Port == 443)
- serverURI = serverURI.Trim(new char[] { '/', ' ' }) + ":443/";
+ serverURI = $"{serverURI.Trim(new char[] { '/', ' ' })}:443/";
return true;
}
@@ -687,8 +674,8 @@ public static Vector3 ClampV(Vector3 x, float max)
float lenSq = x.LengthSquared();
if (lenSq > (max * max))
{
- lenSq = max / (float)Math.Sqrt(lenSq);
- x = x * lenSq;
+ lenSq = max / MathF.Sqrt(lenSq);
+ x *= lenSq;
}
return x;
}
@@ -777,14 +764,14 @@ public static string GetFormattedXml(OSD osd)
///
public static string GetFormattedXml(string rawXml)
{
- XmlDocument xd = new XmlDocument();
+ XmlDocument xd = new();
xd.LoadXml(rawXml);
- StringBuilder sb = new StringBuilder();
- StringWriter sw = new StringWriter(sb);
+ StringBuilder sb = new();
+ StringWriter sw = new(sb);
- XmlTextWriter xtw = new XmlTextWriter(sw)
+ XmlTextWriter xtw = new(sw)
{
Formatting = Formatting.Indented
};
@@ -809,7 +796,7 @@ public static string GetFormattedXml(string rawXml)
public static byte[] ResultFailureMessageEnd = osUTF8.GetASCIIBytes("");
public static byte[] ResultFailureMessage(string message)
{
- osUTF8 res = new osUTF8(ResultFailureMessageStart.Length + ResultFailureMessageEnd.Length + message.Length);
+ osUTF8 res = new(ResultFailureMessageStart.Length + ResultFailureMessageEnd.Length + message.Length);
res.Append(ResultFailureMessageStart);
res.Append(message);
res.Append(ResultFailureMessageEnd);
@@ -818,15 +805,13 @@ public static byte[] ResultFailureMessage(string message)
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();
+ using MemoryStream ms = new();
+ using XmlTextWriter xw = new(ms, null);
+ xw.Formatting = Formatting.Indented;
+ doc.WriteTo(xw);
+ xw.Flush();
- return ms.ToArray();
- }
+ return ms.ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -932,7 +917,7 @@ public static List GetUUIDsOnString(ref string s, int indx, int len)
continue;
}
++indx;
- retry = indx;
+ //retry = indx;
next = indx + 12;
for (; indx < next; ++indx)
@@ -943,7 +928,7 @@ public static List GetUUIDsOnString(ref string s, int indx, int len)
if (indx != next)
continue;
- if (UUID.TryParse(s.Substring(idbase, 36), out UUID u))
+ if (UUID.TryParse(s.AsSpan(idbase, 36), out UUID u))
{
ids.Add(u);
}
@@ -952,7 +937,33 @@ public static List GetUUIDsOnString(ref string s, int indx, int len)
return ids;
}
+ public static List GetUUIDsOnString(ReadOnlySpan s)
+ {
+ var ids = new List();
+ if (s.Length < 36)
+ return ids;
+
+ int indx = 8;
+ while (indx < s.Length - 28)
+ {
+ if (s[indx] == '-')
+ {
+ if (UUID.TryParse(s.Slice(indx - 8, 36), out UUID id))
+ {
+ if (id.IsNotZero())
+ ids.Add(id);
+ indx += 37;
+ }
+ else
+ indx += 9;
+ }
+ else
+ indx++;
+ }
+ return ids;
+ }
+ /*
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsHexa(byte c)
{
@@ -1056,7 +1067,7 @@ public static List GetUUIDsOnData(byte[] s, int indx, int len)
continue;
}
++indx;
- retry = indx;
+ //retry = indx;
next = indx + 12;
for (; indx < next; ++indx)
@@ -1076,6 +1087,7 @@ public static List GetUUIDsOnData(byte[] s, int indx, int len)
return ids;
}
+ */
///
/// Is the platform Windows?
@@ -1111,12 +1123,11 @@ public static bool LoadArchSpecificWindowsDll(string libraryName, string path)
else
nativeLibraryPath = Path.Combine(Path.Combine(path, "lib32"), libraryName);
- m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
+ m_log.Debug($"[UTIL]: Loading native Windows library at {nativeLibraryPath}");
- if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
+ if (!NativeLibrary.TryLoad(nativeLibraryPath, out _))
{
- m_log.ErrorFormat(
- "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
+ m_log.Error($"[UTIL]: Couldn't find native Windows library at {nativeLibraryPath}");
return false;
}
return true;
@@ -1124,29 +1135,11 @@ public static bool LoadArchSpecificWindowsDll(string libraryName, string path)
public static bool IsEnvironmentSupported(ref string reason)
{
- // Must have .NET 2.0 (Generics / libsl)
- if (Environment.Version.Major < 2)
- {
- reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
- return false;
- }
-
- // Windows 95/98/ME are unsupported
- if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
- Environment.OSVersion.Platform != PlatformID.Win32NT)
- {
- reason = "Windows 95/98/ME will not run OpenSim";
- return false;
- }
-
- // Windows 2000 / Pre-SP2 XP
- if (Environment.OSVersion.Version.Major == 5 &&
- Environment.OSVersion.Version.Minor == 0)
+ if (Environment.Version.Major < 6)
{
- reason = "Please update to Windows XP Service Pack 2 or Server2003";
+ reason = "Dotnet 6.0 is required";
return false;
}
-
return true;
}
@@ -1204,7 +1197,7 @@ public static string Md5Hash(string data)
public static string Md5Hash(string data, Encoding encoding)
{
byte[] dataMd5 = ComputeMD5Hash(data, encoding);
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
for (int i = 0; i < dataMd5.Length; i++)
sb.AppendFormat("{0:x2}", dataMd5[i]);
return sb.ToString();
@@ -1213,8 +1206,22 @@ public static string Md5Hash(string data, Encoding encoding)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte[] ComputeMD5Hash(string data, Encoding encoding)
{
- using (MD5 md5 = MD5.Create())
- return md5.ComputeHash(encoding.GetBytes(data));
+ using MD5 md5 = MD5.Create();
+ return md5.ComputeHash(encoding.GetBytes(data));
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static UUID ComputeASCIIMD5UUID(string data)
+ {
+ using MD5 md5 = MD5.Create();
+ byte[] bytes = md5.ComputeHash(Encoding.ASCII.GetBytes(data));
+ UUID uuid = new(bytes,2);
+ uuid.c &= 0x0fff;
+ uuid.c |= 0x3000;
+ uuid.d &= 0x3f;
+ uuid.d |= 0x80;
+
+ return uuid;
}
///
@@ -1251,31 +1258,58 @@ public static char HighNibbleToHexByteCharHighcaps(byte b)
return (char)(b > 9 ? b + 0x37 : b + '0');
}
- public static string bytesToHexString(byte[] bytes, bool lowerCaps)
+ public static unsafe string bytesToHexString(byte[] bytes, bool lowerCaps)
{
if (bytes == null || bytes.Length == 0)
return string.Empty;
- char[] chars = new char[2 * bytes.Length];
- if (lowerCaps)
+ return string.Create(2 * bytes.Length, bytes, (chars, bytes) =>
{
- for (int i = 0, j = 0; i < bytes.Length; ++i)
+ fixed (char* dstb = chars)
+ fixed (byte* srcb = bytes)
{
- byte b = bytes[i];
- chars[j++] = HighNibbleToHexByteCharLowcaps(b);
- chars[j++] = LowNibbleToHexByteCharLowcaps(b);
+ char* dst = dstb;
+ if (lowerCaps)
+ {
+ for (int i = 0; i < bytes.Length; ++i)
+ {
+ byte b = srcb[i];
+ *dst++ = HighNibbleToHexByteCharLowcaps(b);
+ *dst++ = LowNibbleToHexByteCharLowcaps(b);
+ }
+ }
+ else
+ {
+ for (int i = 0; i < bytes.Length; ++i)
+ {
+ byte b = srcb[i];
+ *dst++ = HighNibbleToHexByteCharLowcaps(b);
+ *dst++ = LowNibbleToHexByteCharLowcaps(b);
+ }
+ }
}
- }
- else
+ });
+ }
+
+ public static unsafe string bytesToLowcaseHexString(byte[] bytes)
+ {
+ if (bytes == null || bytes.Length == 0)
+ return string.Empty;
+
+ return string.Create(2 * bytes.Length, bytes, (chars, bytes) =>
{
- for (int i = 0, j = 0; i < bytes.Length; ++i)
+ fixed (char* dstb = chars)
+ fixed (byte* srcb = bytes)
{
- byte b = bytes[i];
- chars[j++] = HighNibbleToHexByteCharHighcaps(b);
- chars[j++] = LowNibbleToHexByteCharHighcaps(b);
+ char* dst = dstb;
+ for (int i = 0; i < bytes.Length; ++i)
+ {
+ byte b = srcb[i];
+ *dst++ = HighNibbleToHexByteCharLowcaps(b);
+ *dst++ = LowNibbleToHexByteCharLowcaps(b);
+ }
}
- }
- return new string(chars);
+ });
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -1303,8 +1337,8 @@ public static string SHA1Hash(byte[] data)
private static byte[] ComputeSHA1Hash(byte[] src)
{
- using (SHA1 sha = SHA1.Create())
- return sha.ComputeHash(src);
+ using SHA1 sha = SHA1.Create();
+ return sha.ComputeHash(src);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -1313,12 +1347,137 @@ public static UUID ComputeSHA1UUID(string src)
return ComputeSHA1UUID(Encoding.Default.GetBytes(src));
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static UUID ComputeASCIISHA1UUID(string src)
+ {
+ return ComputeSHA1UUID(Encoding.ASCII.GetBytes(src));
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static UUID ComputeSHA1UUID(byte[] src)
{
byte[] ret;
using (SHA1 sha = SHA1.Create())
ret = sha.ComputeHash(src);
- return new UUID(ret, 2);
+ UUID uuid = new(ret, 2);
+ uuid.c &= 0x0fff;
+ uuid.c |= 0x5000;
+ uuid.d &= 0x3f;
+ uuid.d |= 0x80;
+ return uuid;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static string AESEncrypt(ReadOnlySpan secret, ReadOnlySpan plainText)
+ {
+ return AESEncryptString(secret, plainText, string.Empty);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static string AESEncryptTo(ReadOnlySpan secret, ReadOnlySpan plainText, ReadOnlySpan ivString)
+ {
+ return AESEncryptString(secret, plainText, ivString);
+ }
+ ///
+ /// AES Encrypt a string using a password and a random or custom Initialization
+ /// Vector
+ ///
+ /// The secret encryption password or key.
+ /// The string or text to encrypt.
+ /// (optional) A string used to generate the Initialization Vector eg; an avatarID, a SecureSessionID, an object or script
+ /// ID...
+ /// A string composed by the Initialization Vector bytes and the
+ /// encrypted text bytes converted to lower case HexString and separated by " : "
+ private static string AESEncryptString(ReadOnlySpan secret, ReadOnlySpan plainText, ReadOnlySpan ivString)
+ {
+ if(secret.Length == 0 || plainText.Length == 0)
+ return string.Empty;
+
+ byte[] iv = ivString.Length == 0 ?
+ MD5.Create().ComputeHash(UUID.Random().GetBytes()) :
+ MD5.Create().ComputeHash(Utils.StringToBytesNoTerm(ivString));
+ byte[] aesKey = SHA256.Create().ComputeHash(Utils.StringToBytesNoTerm(secret));
+ byte[] encryptedText;
+
+ using (Aes aes = Aes.Create())
+ {
+ aes.Key = aesKey;
+ aes.IV = iv;
+ aes.Mode = CipherMode.CBC;
+ aes.Padding = PaddingMode.PKCS7;
+
+ ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
+ using (MemoryStream memoryStream = new())
+ {
+ using (CryptoStream cryptoStream = new(memoryStream, encryptor, CryptoStreamMode.Write))
+ using (StreamWriter streamWriter = new(cryptoStream))
+ streamWriter.Write(plainText);
+ encryptedText = memoryStream.ToArray();
+ }
+ }
+
+ return $"{Convert.ToHexString(iv)}:{Convert.ToHexString(encryptedText).ToLower()}";
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadOnlySpan AESDecrypt(ReadOnlySpan secret, ReadOnlySpan encryptedText)
+ {
+ return AESDecryptString(secret, encryptedText, new ReadOnlySpan());
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadOnlySpan AESDecryptFrom(ReadOnlySpan secret, ReadOnlySpan encryptedText, ReadOnlySpan ivString)
+ {
+ return AESDecryptString(secret, encryptedText, ivString);
+ }
+
+ ///
+ /// AES Decrypt the string encrypted by AESEncryptString with the same password
+ /// and ivString used in the encryption.
+ ///
+ /// The secret decryption password or key.
+ /// The encrypted string or text.
+ /// The string used to generate the Initialization Vector
+ /// if used in the encription. eg; an avatarID, a SecureSessionID, an object or
+ /// script ID...
+ /// The decrypted string.
+ private static ReadOnlySpan AESDecryptString(ReadOnlySpan secret, ReadOnlySpan encryptedText, ReadOnlySpan ivString)
+ {
+ if(secret.Length == 0 || encryptedText.Length == 0)
+ return string.Empty;
+
+ int sep = encryptedText.IndexOf(':');
+ if(sep < 0)
+ return string.Empty;
+
+ byte[] iv;
+ byte[] buffer;
+ try
+ {
+ iv = ivString.Length == 0 ?
+ Convert.FromHexString(encryptedText[..sep]):
+ MD5.Create().ComputeHash(Utils.StringToBytesNoTerm(ivString));
+ buffer = Convert.FromHexString(encryptedText[(sep + 1)..]);
+ }
+ catch
+ {
+ return string.Empty;
+ }
+
+ byte[] aesKey = SHA256.Create().ComputeHash(Utils.StringToBytesNoTerm(secret));
+
+ using Aes aes = Aes.Create();
+ aes.Key = aesKey;
+ aes.IV = iv;
+ aes.Mode = CipherMode.CBC;
+ aes.Padding = PaddingMode.PKCS7;
+
+ ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
+ using MemoryStream memoryStream = new(buffer);
+ using CryptoStream cryptoStream = new(memoryStream, decryptor, CryptoStreamMode.Read);
+ using StreamReader streamReader = new(cryptoStream);
+
+ return streamReader.ReadToEnd();
}
public static int fast_distance2d(int x, int y)
@@ -1401,7 +1560,7 @@ public static string FieldToString(byte[] bytes, string fieldName)
// Check for a common case
if (bytes.Length == 0) return String.Empty;
- StringBuilder output = new StringBuilder();
+ StringBuilder output = new();
bool printable = true;
for (int i = 0; i < bytes.Length; ++i)
@@ -1440,7 +1599,7 @@ public static string FieldToString(byte[] bytes, string fieldName)
for (int j = 0; j < 16; j++)
{
if ((i + j) < bytes.Length)
- output.Append(String.Format("{0:X2} ", bytes[i + j]));
+ output.Append($"{bytes[i + j]:X2} ");
else
output.Append(" ");
}
@@ -1450,7 +1609,7 @@ public static string FieldToString(byte[] bytes, string fieldName)
if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
output.Append((char)bytes[i + j]);
else
- output.Append(".");
+ output.Append('.');
}
}
}
@@ -1458,7 +1617,21 @@ public static string FieldToString(byte[] bytes, string fieldName)
return output.ToString();
}
- private static ExpiringCacheOS dnscache = new ExpiringCacheOS(10000);
+ private static IPEndPoint dummyIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
+ private static readonly ExpiringCacheOS dnscache = new(30000);
+ private static readonly ExpiringCacheOS EndpointsCache = new(300000);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static EndPoint GetEndPoint(SocketAddress sckaddr)
+ {
+ if (!EndpointsCache.TryGetValue(sckaddr, 300000, out EndPoint ep))
+ {
+ ep = dummyIPEndPoint.Create(sckaddr);
+ EndpointsCache.AddOrUpdate(sckaddr, ep, 300);
+ }
+ return ep;
+ }
+
///
/// Converts a URL to a IPAddress
@@ -1484,7 +1657,6 @@ public static IPAddress GetHostFromDNS(string dnsAddress)
if (dnscache.TryGetValue(dnsAddress, 300000, out IPAddress ia) && ia != null)
return ia;
- ia = null;
// If it is already an IP, don't let GetHostEntry see it
if (IPAddress.TryParse(dnsAddress, out ia) && ia != null)
{
@@ -1510,8 +1682,7 @@ public static IPAddress GetHostFromDNS(string dnsAddress)
ia = null;
foreach (IPAddress Adr in IPH.AddressList)
{
- if (ia == null)
- ia = Adr;
+ ia ??= Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
@@ -1529,16 +1700,14 @@ public static IPEndPoint getEndPoint(IPAddress ia, int port)
if (ia == null)
return null;
- IPEndPoint newEP = null;
try
{
- newEP = new IPEndPoint(ia, port);
+ return new IPEndPoint(ia, port);
}
catch
{
- newEP = null;
+ return null;
}
- return newEP;
}
public static IPEndPoint getEndPoint(string hostname, int port)
@@ -1549,8 +1718,6 @@ public static IPEndPoint getEndPoint(string hostname, int port)
if (dnscache.TryGetValue(hostname, 300000, out IPAddress ia) && ia != null)
return getEndPoint(ia, port);
- ia = null;
-
// If it is already an IP, don't let GetHostEntry see it
if (IPAddress.TryParse(hostname, out ia) && ia != null)
{
@@ -1578,8 +1745,7 @@ public static IPEndPoint getEndPoint(string hostname, int port)
ia = null;
foreach (IPAddress Adr in IPH.AddressList)
{
- if (ia == null)
- ia = Adr;
+ ia ??= Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
@@ -1661,7 +1827,7 @@ public static int ParseForeignAssetID(string id, out string url, out string asse
if (id[0] != 'h' && id[0] != 'H')
{
- if (UUID.TryParse(id, out UUID luuid))
+ if (UUID.TryParse(id, out _))
{
assetID = id;
return 0;
@@ -1669,7 +1835,7 @@ public static int ParseForeignAssetID(string id, out string url, out string asse
return -1;
}
- OSHTTPURI uri = new OSHTTPURI(id, true);
+ OSHTTPURI uri = new(id, true);
if (uri.IsResolvedHost)
{
url = uri.URL;
@@ -1677,8 +1843,8 @@ public static int ParseForeignAssetID(string id, out string url, out string asse
if (tmp.Length < 36)
return -3;
if (tmp[0] == '/')
- tmp = tmp.Substring(1);
- if (UUID.TryParse(tmp, out UUID uuid))
+ tmp = tmp[1..];
+ if (UUID.TryParse(tmp, out _))
{
assetID = tmp;
return 1;
@@ -1751,9 +1917,9 @@ public static string logFile()
{
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
- if (appender is FileAppender && appender.Name == "LogFileAppender")
+ if (appender is FileAppender appender1 && appender1.Name == "LogFileAppender")
{
- return ((FileAppender)appender).File;
+ return appender1.File;
}
}
@@ -1764,9 +1930,9 @@ public static string StatsLogFile()
{
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
- if (appender is FileAppender && appender.Name == "StatsLogFileAppender")
+ if (appender is FileAppender appender1 && appender1.Name == "StatsLogFileAppender")
{
- return ((FileAppender)appender).File;
+ return appender1.File;
}
}
@@ -1787,11 +1953,11 @@ public static string GetUniqueFilename(string FileName)
if (File.Exists(FileName))
{
- FileInfo f = new FileInfo(FileName);
+ FileInfo f = new(FileName);
if (!String.IsNullOrEmpty(f.Extension))
{
- Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
+ Name = f.FullName[..f.FullName.LastIndexOf('.')];
}
else
{
@@ -1815,7 +1981,7 @@ public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileNa
{
// create new file
}
- XmlConfigSource config = new XmlConfigSource(fileName);
+ XmlConfigSource config = new(fileName);
AddDataRowToConfig(config, row);
config.Save();
@@ -1881,7 +2047,7 @@ public static T GetConfigVarFromSections(IConfigSource config, string varname
///
public static T GetConfigVarFromSections(IConfigSource config, string varname, string[] sections, object val)
{
- foreach (string section in sections)
+ foreach (string section in sections.AsSpan())
{
IConfig cnf = config.Configs[section];
if (cnf == null)
@@ -1898,7 +2064,6 @@ public static T GetConfigVarFromSections(IConfigSource config, string varname
else
m_log.ErrorFormat("[UTIL]: Unhandled type {0}", typeof(T));
}
-
return (T)val;
}
@@ -1909,7 +2074,7 @@ public static void MergeEnvironmentToConfig(IConfigSource ConfigSource)
if (enVars != null)
{
// load the values from the environment
- EnvConfigSource envConfigSource = new EnvConfigSource();
+ EnvConfigSource envConfigSource = new();
// add the requested keys
string[] env_keys = enVars.GetKeys();
foreach (string key in env_keys)
@@ -2006,7 +2171,7 @@ public static bool MergeConfigurationFile(IConfigSource config, string configFil
IConfig cnf = config.Configs["Startup"];
if (cnf == null)
{
- m_log.WarnFormat("[UTILS]: Startup section doesn't exist");
+ m_log.Warn("[UTILS]: Startup section doesn't exist");
return false;
}
@@ -2027,7 +2192,7 @@ public static bool MergeConfigurationFile(IConfigSource config, string configFil
}
catch (Exception e)
{
- m_log.WarnFormat("[UTILS]: Exception copying configuration file {0} to {1}: {2}", configFile, exampleConfigFile, e.Message);
+ m_log.Warn($"[UTILS]: Exception copying configuration file {configFile} to {exampleConfigFile}: {e.Message}");
return false;
}
}
@@ -2061,7 +2226,7 @@ public static string CleanString(string input)
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '\0' || input[i] == '\r' || input[i] == '\n')
- return input.Substring(0, i);
+ return input[..i];
}
return input;
}
@@ -2075,12 +2240,11 @@ public static string ReadEtcIssue()
{
try
{
- StreamReader sr = new StreamReader("/etc/issue.net");
+ using StreamReader sr = new("/etc/issue.net");
string issue = sr.ReadToEnd();
- sr.Close();
return issue;
}
- catch (Exception)
+ catch
{
return "";
}
@@ -2089,69 +2253,41 @@ public static string ReadEtcIssue()
public static void SerializeToFile(string filename, Object obj)
{
IFormatter formatter = new BinaryFormatter();
- Stream stream = null;
-
try
{
- stream = new FileStream(
- filename, FileMode.Create,
- FileAccess.Write, FileShare.None);
-
+ using Stream stream = new FileStream(filename, FileMode.Create,FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
- finally
- {
- if (stream != null)
- {
- stream.Close();
- }
- }
}
public static Object DeserializeFromFile(string filename)
{
- IFormatter formatter = new BinaryFormatter();
- Stream stream = null;
- Object ret = null;
-
try
{
- stream = new FileStream(
- filename, FileMode.Open,
- FileAccess.Read, FileShare.None);
-
- ret = formatter.Deserialize(stream);
+ using Stream stream = new FileStream(filename, FileMode.Open,FileAccess.Read, FileShare.None);
+ IFormatter formatter = new BinaryFormatter();
+ return formatter.Deserialize(stream);
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
- finally
- {
- if (stream != null)
- {
- stream.Close();
- }
- }
-
- return ret;
+ return null;
}
public static string Compress(string text)
{
+ using MemoryStream memory = new();
+ using GZipStream compressor = new(memory, CompressionMode.Compress, true);
+
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);
- }
+ compressor.Write(buffer, 0, buffer.Length);
memory.Position = 0;
-
byte[] compressed = new byte[memory.Length];
memory.Read(compressed, 0, compressed.Length);
@@ -2164,21 +2300,18 @@ public static string Compress(string text)
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);
+ int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
- byte[] buffer = new byte[msgLength];
+ using MemoryStream memory = new();
+ memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
- memory.Position = 0;
- using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
- {
- decompressor.Read(buffer, 0, buffer.Length);
- }
+ byte[] buffer = new byte[msgLength];
- return Util.UTF8.GetString(buffer);
- }
+ memory.Position = 0;
+ using GZipStream decompressor = new(memory, CompressionMode.Decompress);
+ decompressor.Read(buffer, 0, buffer.Length);
+
+ return Util.UTF8.GetString(buffer);
}
///
@@ -2197,7 +2330,8 @@ public static Stream Copy(Stream inputStream)
const int readSize = 256;
byte[] buffer = new byte[readSize];
- MemoryStream ms = new MemoryStream();
+
+ MemoryStream ms = new();
int count = inputStream.Read(buffer, 0, readSize);
@@ -2213,6 +2347,7 @@ public static Stream Copy(Stream inputStream)
return ms;
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
{
return SendXmlRpcCommand(url, methodName, args);
@@ -2220,8 +2355,9 @@ public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params
public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
{
- XmlRpcRequest client = new XmlRpcRequest(methodName, args);
- return client.Send(url, 6000);
+ XmlRpcRequest xmlclient = new(methodName, args);
+ using HttpClient hclient = WebUtil.GetNewGlobalHttpClient(10000);
+ return xmlclient.Send(url, hclient);
}
///
@@ -2230,14 +2366,16 @@ public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, ob
/// XML string consisting of a error element containing individual error(s)
public static XmlRpcResponse CreateUnknownUserErrorResponse()
{
- XmlRpcResponse response = new XmlRpcResponse();
- Hashtable responseData = new Hashtable()
+ Hashtable responseData = new()
{
["error_type"] = "unknown_user",
["error_desc"] = "The user requested is not in the database"
};
- response.Value = responseData;
+ XmlRpcResponse response = new()
+ {
+ Value = responseData
+ };
return response;
}
@@ -2318,46 +2456,36 @@ public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out u
///
public static string GetOperatingSystemInformation()
{
- string os = String.Empty;
+ return String.Empty;
+ //string os;
+ //if (Environment.OSVersion.Platform != PlatformID.Unix)
+ //{
+ // os = Environment.OSVersion.ToString();
+ //}
+ //else
+ //{
+ // os = ReadEtcIssue();
+ //}
- // if (Environment.OSVersion.Platform != PlatformID.Unix)
- // {
- // os = Environment.OSVersion.ToString();
- // }
- // else
- // {
- // os = ReadEtcIssue();
- // }
- //
- // if (os.Length > 45)
- // {
- // os = os.Substring(0, 45);
- // }
+ //if (os.Length > 45)
+ //{
+ // os = os.Substring(0, 45);
+ //}
- return os;
+ //return os;
}
- public static string GetRuntimeInformation()
- {
- string ru = String.Empty;
-
- if (Environment.OSVersion.Platform == PlatformID.Unix)
+ public static readonly string RuntimeInformationStr = RuntimeInformation.ProcessArchitecture.ToString() + "/" + Environment.OSVersion.Platform switch
{
- ru = "Unix/Mono";
- }
- else
- if (Environment.OSVersion.Platform == PlatformID.MacOSX)
- ru = "OSX/Mono";
- else
- {
- if (IsPlatformMono)
- ru = "Win/Mono";
- else
- ru = "Win/.NET";
- }
+ PlatformID.MacOSX or PlatformID.Unix => RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "OSX/DotNet" : "Unix/DotNet",
+ _ => "Win/DotNet"
+ };
- return ru;
- }
+ public static readonly string RuntimePlatformStr = Environment.OSVersion.Platform switch
+ {
+ PlatformID.MacOSX or PlatformID.Unix => RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "OSX/DotNet" : "Unix/DotNet",
+ _ => "Win/DotNet"
+ };
///
/// Is the given string a UUID?
@@ -2371,9 +2499,8 @@ public static bool isUUID(string s)
public static string GetDisplayConnectionString(string connectionString)
{
- int passPosition = 0;
- int passEndPosition = 0;
- string displayConnectionString = null;
+ int passPosition;
+ int passEndPosition;
// hide the password in the connection string
passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
@@ -2384,11 +2511,7 @@ public static string GetDisplayConnectionString(string connectionString)
passPosition += 1;
passEndPosition = connectionString.IndexOf(";", passPosition);
- displayConnectionString = connectionString.Substring(0, passPosition);
- displayConnectionString += "***";
- displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
-
- return displayConnectionString;
+ return $"{connectionString[..passPosition]}***{connectionString[passEndPosition..]}";
}
public static string Base64ToString(string str)
@@ -2399,7 +2522,7 @@ public static string Base64ToString(string str)
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
- string result = new String(decoded_char);
+ string result = new(decoded_char);
return result;
}
@@ -2446,11 +2569,7 @@ public static void ReadStream(Stream stream, byte[] data)
public static Guid GetHashGuid(string data, string salt)
{
byte[] hash = ComputeMD5Hash(data + salt, Encoding.Default);
-
- //string s = BitConverter.ToString(hash);
-
- Guid guid = new Guid(hash);
-
+ Guid guid = new(hash);
return guid;
}
@@ -2495,7 +2614,7 @@ public static OSDMap GetOSDMap(Stream stream, int length)
byte[] data = new byte[length];
stream.Read(data, 0, length);
string strdata = Util.UTF8.GetString(data);
- OSDMap args = null;
+ OSDMap args;
OSD buffer;
buffer = OSDParser.DeserializeJson(strdata);
if (buffer.Type == OSDType.Map)
@@ -2508,7 +2627,7 @@ public static OSDMap GetOSDMap(Stream stream, int length)
public static OSDMap GetOSDMap(string data)
{
- OSDMap args = null;
+ OSDMap args;
try
{
OSD buffer;
@@ -2522,13 +2641,13 @@ public static OSDMap GetOSDMap(string data)
else
{
// uh?
- m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
+ m_log.Debug($"[UTILS]: Got OSD of unexpected type {buffer.Type}");
return null;
}
}
catch (Exception ex)
{
- m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
+ m_log.Debug($"[UTILS]: exception on GetOSDMap {ex.Message}");
return null;
}
}
@@ -2558,8 +2677,8 @@ public static string[] Glob(string path)
else
path = new String(new char[] { Path.DirectorySeparatorChar });
- List paths = new List();
- List found = new List();
+ List paths = new();
+ List found = new();
paths.Add(path);
int compIndex = -1;
@@ -2567,7 +2686,7 @@ public static string[] Glob(string path)
{
compIndex++;
- List addpaths = new List();
+ List addpaths = new();
foreach (string p in paths)
{
string[] dirs = Directory.GetDirectories(p, c);
@@ -2608,7 +2727,7 @@ public static string TrimEndSlash(string path)
int len = path.Length;
--len;
if (len > 0 && path[len] == '/')
- return path.Substring(0, len);
+ return path[..len];
return path;
}
@@ -2630,7 +2749,7 @@ public static string ServerURIasIP(string uri)
try
{
- port1 = uri.Split(new char[] { ':' })[2];
+ port1 = uri.Split(Util.SplitColonArray)[2];
}
catch { }
@@ -2649,12 +2768,13 @@ public static string ServerURIasIP(string uri)
/// Arguments to substitute into the string via the {} mechanism.
///
///
+ /*
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] StringToBytes256(string str, params object[] args)
{
return Utils.StringToBytes(string.Format(str, args), 255);
}
-
+ */
///
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
///
@@ -2664,7 +2784,7 @@ public static byte[] StringToBytes256(string str, params object[] args)
///
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static byte[] StringToBytes256(string str)
+ public static byte[] StringToBytes256(ReadOnlySpan str)
{
return Utils.StringToBytes(str, 255);
}
@@ -2680,11 +2800,13 @@ public static byte[] StringToBytes256(string str)
/// Arguments to substitute into the string via the {} mechanism.
///
///
+ /*
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] StringToBytes1024(string str, params object[] args)
{
- return Utils.StringToBytes(string.Format(str, args), 1024);
+ return Utils.StringToBytes(string.Format(str, args).AsSpan(), 1024);
}
+ */
///
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
@@ -2695,7 +2817,7 @@ public static byte[] StringToBytes1024(string str, params object[] args)
///
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static byte[] StringToBytes1024(string str)
+ public static byte[] StringToBytes1024(ReadOnlySpan str)
{
return Utils.StringToBytes(str, 1024);
}
@@ -2711,11 +2833,13 @@ public static byte[] StringToBytes1024(string str)
/// Arguments to substitute into the string via the {} mechanism.
///
///
+ /*
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] StringToBytes(string str, int MaxLength, params object[] args)
{
- return StringToBytes1024(string.Format(str, args), MaxLength);
+ return Utils.StringToBytes(string.Format(str, args).AsSpan(), MaxLength);
}
+ */
///
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
@@ -2726,26 +2850,26 @@ public static byte[] StringToBytes(string str, int MaxLength, params object[] ar
///
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static byte[] StringToBytes(string str, int MaxLength)
+ public static byte[] StringToBytes(ReadOnlySpan str, int MaxLength)
{
return Utils.StringToBytes(str, MaxLength);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static byte[] StringToBytesNoTerm(string str, int MaxLength)
+ public static byte[] StringToBytesNoTerm(ReadOnlySpan str, int MaxLength)
{
return Utils.StringToBytesNoTerm(str, MaxLength);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static int osUTF8Getbytes(string srcstr, byte[] dstarray, int maxdstlen, bool NullTerm = true)
+ public static int osUTF8Getbytes(ReadOnlySpan srcstr, byte[] dstarray, int maxdstlen, bool NullTerm = true)
{
return osUTF8Getbytes(srcstr, dstarray, 0, maxdstlen, NullTerm);
}
- public static unsafe int osUTF8Getbytes(string srcstr, byte* dstarray, int maxdstlen, bool NullTerm = true)
+ public static unsafe int osUTF8Getbytes(ReadOnlySpan srcstr, byte* dstarray, int maxdstlen, bool NullTerm = true)
{
- if (string.IsNullOrEmpty(srcstr))
+ if (srcstr.Length == 0)
return 0;
fixed (char* srcbase = srcstr)
@@ -2754,9 +2878,9 @@ public static unsafe int osUTF8Getbytes(string srcstr, byte* dstarray, int maxds
}
}
- public static unsafe int osUTF8Getbytes(string srcstr, byte[] dstarray, int pos, int maxdstlen, bool NullTerm = true)
+ public static unsafe int osUTF8Getbytes(ReadOnlySpan srcstr, byte[] dstarray, int pos, int maxdstlen, bool NullTerm = true)
{
- if (string.IsNullOrEmpty(srcstr))
+ if (srcstr.Length == 0)
return 0;
if (pos + maxdstlen > dstarray.Length)
@@ -2861,13 +2985,13 @@ public static unsafe int osUTF8Getbytes(char* srcarray, int srclength, byte* dst
///
public static string PrettyFormatToSingleLine(Hashtable ht)
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
int i = 0;
foreach (string key in ht.Keys)
{
- sb.AppendFormat("{0}:{1}", key, ht[key]);
+ sb.Append($"{key}:{ht[key]}");
if (++i < ht.Count)
sb.AppendFormat(", ");
@@ -2884,7 +3008,7 @@ public static bool TryParseHttpRange(string header, out int start, out int end)
if (header.StartsWith("bytes="))
{
- string[] rangeValues = header.Substring(6).Split('-');
+ string[] rangeValues = header[6..].Split('-');
if (rangeValues.Length == 2)
{
@@ -2932,10 +3056,10 @@ public static bool TryParseHttpRange(string header, out int start, out int end)
public static void InitThreadPool(int minThreads, int maxThreads)
{
if (maxThreads < 2)
- throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
+ throw new ArgumentOutOfRangeException(nameof(maxThreads), "maxThreads must be greater than 2");
if (minThreads > maxThreads || minThreads < 2)
- throw new ArgumentOutOfRangeException("minThreads", "minThreads must be greater than 2 and less than or equal to maxThreads");
+ throw new ArgumentOutOfRangeException(nameof(minThreads), "minThreads must be greater than 2 and less than or equal to maxThreads");
if (m_ThreadPool != null)
{
@@ -2943,7 +3067,7 @@ public static void InitThreadPool(int minThreads, int maxThreads)
return;
}
- STPStartInfo startInfo = new STPStartInfo()
+ STPStartInfo startInfo = new()
{
ThreadPoolName = "Util",
IdleTimeout = 20000,
@@ -2963,15 +3087,14 @@ public static int FireAndForgetCount()
switch (FireAndForgetMethod)
{
case FireAndForgetMethod.QueueUserWorkItem:
- int workerThreads, iocpThreads;
- ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
+ ThreadPool.GetAvailableThreads(out int workerThreads, out _);
return workerThreads;
case FireAndForgetMethod.SmartThreadPool:
return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
case FireAndForgetMethod.Thread:
{
- using (Process p = System.Diagnostics.Process.GetCurrentProcess())
- return MAX_SYSTEM_THREADS - p.Threads.Count;
+ using Process p = System.Diagnostics.Process.GetCurrentProcess();
+ return MAX_SYSTEM_THREADS - p.Threads.Count;
}
default:
throw new NotImplementedException();
@@ -3062,7 +3185,7 @@ public string GetStackTrace()
public static long TotalRunningFireAndForgetCalls { get { return numRunningThreadFuncs; } }
// Maps (ThreadFunc number -> Thread)
- private static ConcurrentDictionary activeThreads = new ConcurrentDictionary();
+ private static readonly ConcurrentDictionary activeThreads = new();
private static readonly int THREAD_TIMEOUT = 10 * 60 * 1000; // 10 minutes
@@ -3076,10 +3199,9 @@ private static void ThreadPoolWatchdog(object state)
ThreadInfo t = entry.Value;
if (t.DoTimeout && t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
{
- m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace());
+ m_log.Warn($"Timeout in threadfunc {t.ThreadFuncNum} ({t.Thread.Name}) {t.GetStackTrace()}");
t.Abort();
-
- activeThreads.TryRemove(entry.Key, out ThreadInfo dummy);
+ activeThreads.TryRemove(entry.Key, out _);
// It's possible that the thread won't abort. To make sure the thread pool isn't
// depleted, increase the pool size.
@@ -3095,14 +3217,14 @@ public static Dictionary GetFireAndForgetCallsMade()
return new Dictionary(m_fireAndForgetCallsMade);
}
- private static readonly Dictionary m_fireAndForgetCallsMade = new Dictionary();
+ private static readonly Dictionary m_fireAndForgetCallsMade = new();
public static Dictionary GetFireAndForgetCallsInProgress()
{
return new Dictionary(m_fireAndForgetCallsInProgress);
}
- private static readonly Dictionary m_fireAndForgetCallsInProgress = new Dictionary();
+ private static readonly Dictionary m_fireAndForgetCallsInProgress = new();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FireAndForget(System.Threading.WaitCallback callback)
@@ -3124,7 +3246,7 @@ public static void FireAndForget(System.Threading.WaitCallback callback, object
bool loggingEnabled = LogThreadPool > 0;
long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
- ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context, dotimeout);
+ ThreadInfo threadInfo = new(threadFuncNum, context, dotimeout);
if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
@@ -3161,14 +3283,14 @@ public static void FireAndForget(System.Threading.WaitCallback callback, object
}
catch (Exception e)
{
- m_log.Error(string.Format("[UTIL]: Util STP threadfunc {0} terminated with error ", threadFuncNum), e);
+ m_log.Error($"[UTIL]: Util STP threadfunc {threadFuncNum} terminated with error {e.Message}");
}
finally
{
Interlocked.Decrement(ref numRunningThreadFuncs);
activeThreads.TryRemove(threadFuncNum, out ThreadInfo dummy);
if (loggingEnabled && threadInfo.LogThread)
- m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed()));
+ m_log.Debug($"Exit threadfunc {threadFuncNum} ({FormatDuration(threadInfo.Elapsed())}");
callback = null;
o = null;
threadInfo = null;
@@ -3196,7 +3318,7 @@ public static void FireAndForget(System.Threading.WaitCallback callback, object
threadInfo.WorkItem = m_ThreadPool.QueueWorkItem(realCallback, obj);
break;
case FireAndForgetMethod.Thread:
- Thread thread = new Thread(delegate (object o) { realCallback(o); realCallback = null; });
+ Thread thread = new(delegate (object o) { realCallback(o); realCallback = null; });
thread.Start(obj);
break;
default:
@@ -3238,7 +3360,7 @@ private static void GetFireAndForgetStackTrace(out string full, out string parti
string src = Environment.StackTrace;
string[] lines = src.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
- StringBuilder dest = new StringBuilder(src.Length);
+ StringBuilder dest = new(src.Length);
bool started = false;
bool first = true;
@@ -3273,7 +3395,6 @@ private static void GetFireAndForgetStackTrace(out string full, out string parti
full = dest.ToString();
}
-#pragma warning disable 0618
///
/// Return the stack trace of a different thread.
///
@@ -3291,7 +3412,6 @@ private static void GetFireAndForgetStackTrace(out string full, out string parti
/// The stack trace, or null if failed to get it
private static StackTrace GetStackTrace(Thread targetThread)
{
-
return null;
/*
not only this does not work on mono but it is not longer recomended on windows.
@@ -3361,7 +3481,6 @@ can cause deadlocks etc.
}
*/
}
-#pragma warning restore 0618
///
/// Get information about the current state of the smart thread pool.
@@ -3458,8 +3577,8 @@ public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
public static long GetPhysicalMemUse()
{
- using (Process p = System.Diagnostics.Process.GetCurrentProcess())
- return p.WorkingSet64;
+ using Process p = System.Diagnostics.Process.GetCurrentProcess();
+ return p.WorkingSet64;
}
// returns a timestamp in seconds as double
@@ -3503,7 +3622,7 @@ public static void AddToGatheredIds(Dictionary uuids, UUID id, sbyt
///
public static string FormatDuration(int ms)
{
- TimeSpan span = new TimeSpan(ms * TimeSpan.TicksPerMillisecond);
+ TimeSpan span = new(ms * TimeSpan.TicksPerMillisecond);
string str = "";
string suffix = null;
@@ -3520,8 +3639,7 @@ public static string FormatDuration(int ms)
if (str.Length > 0)
str += ":";
str += span.Minutes.ToString(str.Length == 0 ? "0" : "00");
- if (suffix == null)
- suffix = "min";
+ suffix ??= "min";
}
if ((hours > 0) || (span.Minutes > 0) || (span.Seconds > 0))
@@ -3529,12 +3647,10 @@ public static string FormatDuration(int ms)
if (str.Length > 0)
str += ":";
str += span.Seconds.ToString(str.Length == 0 ? "0" : "00");
- if (suffix == null)
- suffix = "sec";
+ suffix ??= "sec";
}
- if (suffix == null)
- suffix = "ms";
+ suffix ??= "ms";
if (span.TotalMinutes < 1)
{
@@ -3563,14 +3679,14 @@ public static void PrintCallStack()
public delegate void DebugPrinter(string msg, params Object[] parm);
public static void PrintCallStack(DebugPrinter printer)
{
- StackTrace stackTrace = new StackTrace(true); // get call stack
+ StackTrace stackTrace = new(true); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
// write call stack method names
foreach (StackFrame stackFrame in stackFrames)
{
MethodBase mb = stackFrame.GetMethod();
- printer("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
+ printer($"{mb.DeclaringType}.{mb.Name}:{stackFrame.GetFileLineNumber()}"); // write method name
}
}
@@ -3584,7 +3700,7 @@ public static IPEndPoint GetClientIPFromXFF(string xff)
if (xff.Length == 0)
return null;
- string[] parts = xff.Split(new char[] { ',' });
+ string[] parts = xff.Split(Util.SplitCommaArray);
if (parts.Length > 0)
{
try
@@ -3593,7 +3709,7 @@ public static IPEndPoint GetClientIPFromXFF(string xff)
}
catch (Exception e)
{
- m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
+ m_log.Warn($"[UTIL]: Exception parsing XFF header {xff}: {e.Message}");
}
}
@@ -3612,7 +3728,7 @@ public static string GetCallerIP(Hashtable req)
}
catch (Exception e)
{
- m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
+ m_log.Warn($"[UTIL]: exception in GetCallerIP: {e.Message}");
}
}
return string.Empty;
@@ -3632,20 +3748,17 @@ public static bool ReadBoolean(XmlReader reader)
public static UUID ReadUUID(XmlReader reader, string name)
{
- string idStr;
-
reader.ReadStartElement(name);
-
- if (reader.Name == "Guid")
- idStr = reader.ReadElementString("Guid");
- else if (reader.Name == "UUID")
- idStr = reader.ReadElementString("UUID");
- else // no leading tag
- idStr = reader.ReadContentAsString();
-
- UUID.TryParse(idStr, out UUID id);
+ string idStr = reader.Name switch
+ {
+ "Guid" => reader.ReadElementString("Guid"),
+ "UUID" => reader.ReadElementString("UUID"),
+ // no leading tag
+ _ => reader.ReadContentAsString(),
+ };
reader.ReadEndElement();
+ UUID.TryParse(idStr, out UUID id);
return id;
}
@@ -3664,7 +3777,7 @@ public static Vector3 ReadVector(XmlReader reader, string name)
public static Quaternion ReadQuaternion(XmlReader reader, string name)
{
- Quaternion quat = new Quaternion();
+ Quaternion quat = new();
reader.ReadStartElement(name);
while (reader.NodeType != XmlNodeType.EndElement)
@@ -3695,10 +3808,10 @@ public static T ReadEnum(XmlReader reader, string name)
{
string value = reader.ReadElementContentAsString(name, String.Empty);
// !!!!! to deal with flags without commas
- if (value.Contains(" ") && !value.Contains(","))
+ if (value.Contains(' ') && !value.Contains(','))
value = value.Replace(" ", ", ");
- return (T)Enum.Parse(typeof(T), value); ;
+ return (T)Enum.Parse(typeof(T), value);
}
#endregion
@@ -3734,7 +3847,7 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
return false;
}
- if (!UUID.TryParse(value.Substring(0, 36), out uuid))
+ if (!UUID.TryParse(value[..36], out uuid))
{
url = string.Empty;
firstname = string.Empty;
@@ -3761,7 +3874,7 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
int indxA = seps[0] + 1;
int indxB = seps[1];
- url = value.Substring(indxA, indxB - indxA).Trim().ToLower();
+ url = value[indxA..indxB].Trim().ToLower();
++indxB;
if (indxB >= value.Length)
@@ -3772,14 +3885,14 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
}
string n;
if (nseps == 2)
- n = value.Substring(indxB).Trim();
+ n = value[indxB..].Trim();
else
{
indxA = seps[2];
- n = value.Substring(indxB, indxA - indxB);
+ n = value[indxB..indxA];
++indxA;
if (indxA < value.Length)
- secret = value.Substring(indxA);
+ secret = value[indxA..];
}
string[] name = n.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
@@ -3809,7 +3922,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
return false;
}
- if (!UUID.TryParse(value.Substring(0, 36), out uuid))
+ if (!UUID.TryParse(value[..36], out uuid))
{
url = string.Empty;
firstname = string.Empty;
@@ -3836,7 +3949,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
int indxA = seps[0] + 1;
int indxB = seps[1];
- url = value.Substring(indxA, indxB - indxA).Trim().ToLower();
+ url = value[indxA..indxB].Trim().ToLower();
++indxB;
if (indxB >= value.Length)
@@ -3847,14 +3960,14 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
}
string n;
if (nseps == 2)
- n = value.Substring(indxB).Trim();
+ n = value[indxB..].Trim();
else
{
indxA = seps[2];
- n = value.Substring(indxB, indxA - indxB);
+ n = value[indxB..indxA];
++indxA;
if (indxA < value.Length)
- secret = value.Substring(indxA);
+ secret = value[indxA..];
}
string[] name = n.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
@@ -3890,7 +4003,7 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
return false;
}
- if (!UUID.TryParse(value.Substring(0, 36), out uuid))
+ if (!UUID.TryParse(value[..36], out uuid))
{
url = string.Empty;
firstname = string.Empty;
@@ -3916,7 +4029,7 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
int indxA = seps[0] + 1;
int indxB = seps[1];
- url = value.Substring(indxA, indxB - indxA).Trim().ToLower();
+ url = value[indxA..indxB].Trim().ToLower();
++indxB;
if (indxB >= value.Length)
@@ -3927,9 +4040,9 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
}
string n;
if (nseps == 2)
- n = value.Substring(indxB);
+ n = value[indxB..];
else
- n = value.Substring(indxB, seps[2] - indxB);
+ n = value[indxB..seps[2]];
string[] name = n.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (name.Length == 0)
@@ -3956,7 +4069,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
return false;
}
- if (!UUID.TryParse(value.Substring(0, 36), out uuid))
+ if (!UUID.TryParse(value[..36], out uuid))
{
url = string.Empty;
firstname = string.Empty;
@@ -3982,7 +4095,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
int indxA = seps[0] + 1;
int indxB = seps[1];
- url = value.Substring(indxA, indxB - indxA).Trim().ToLower();
+ url = value[indxA..indxB].Trim().ToLower();
++indxB;
if (indxB >= value.Length)
@@ -3993,9 +4106,9 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
}
string n;
if (nseps == 2)
- n = value.Substring(indxB);
+ n = value[indxB..];
else
- n = value.Substring(indxB, seps[2] - indxB);
+ n = value[indxB..seps[2]];
string[] name = n.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (name.Length == 0)
@@ -4020,7 +4133,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
return false;
}
- if (!UUID.TryParse(value.Substring(0, 36), out uuid))
+ if (!UUID.TryParse(value[..36], out uuid))
{
url = string.Empty;
return false;
@@ -4043,7 +4156,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
int indxA = seps[0] + 1;
int indxB = seps[1];
- url = value.Substring(indxA, indxB - indxA).Trim().ToLower();
+ url = value[indxA..indxB].Trim().ToLower();
indxA = seps[1] + 3;
indxB = nseps > 2 ? seps[2] : value.Length;
@@ -4060,7 +4173,7 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
return false;
}
- if (!UUID.TryParse(value.Substring(0, 36), out uuid))
+ if (!UUID.TryParse(value[..36], out uuid))
{
url = string.Empty;
return false;
@@ -4083,7 +4196,7 @@ public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uu
int indxA = seps[0] + 1;
int indxB = seps[1];
- url = value.Substring(indxA, indxB - indxA).Trim().ToLower();
+ url = value[indxA..indxB].Trim().ToLower();
return true;
}
@@ -4109,7 +4222,7 @@ public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUI
return false;
}
- if (!UUID.TryParse(value.Substring(0, seps[0]), out uuid))
+ if (!UUID.TryParse(value[..seps[0]], out uuid))
return false;
int indxA = seps[1] + 3;
@@ -4125,7 +4238,7 @@ public static bool ParseUniversalUserIdentifier(string value, out UUID uuid)
uuid = UUID.Zero;
return false;
}
- return (value.Length == 36) ? UUID.TryParse(value, out uuid) : UUID.TryParse(value.Substring(0, 36), out uuid);
+ return (value.Length == 36) ? UUID.TryParse(value, out uuid) : UUID.TryParse(value[..36], out uuid);
}
public static unsafe string RemoveUniversalUserIdentifierSecret(string value)
@@ -4141,7 +4254,7 @@ public static unsafe string RemoveUniversalUserIdentifierSecret(string value)
}
if (nseps < 3)
return value;
- return value.Substring(0, seps[3]);
+ return value[..seps[3]];
}
///
@@ -4152,7 +4265,7 @@ public static bool ParseForeignAvatarName(string firstname, string lastname,
{
realFirstName = realLastName = serverURI = string.Empty;
- if (!lastname.Contains("@"))
+ if (!lastname.Contains('@'))
return false;
string[] parts = firstname.Split('.');
@@ -4162,7 +4275,7 @@ public static bool ParseForeignAvatarName(string firstname, string lastname,
realFirstName = parts[0].Trim();
realLastName = parts[1].Trim();
lastname = lastname.Trim();
- serverURI = new Uri("http://" + lastname.Replace("@", "")).ToString();
+ serverURI = new Uri($"http://{lastname.Replace("@", "")}").ToString();
return true;
}
@@ -4202,7 +4315,7 @@ public static int ParseAvatarName(string name, out string FirstName, out string
++i;
}
- FirstName = name.Substring(start, i - start);
+ FirstName = name[start..i];
if (i >= name.Length - 1)
return 1;
@@ -4232,19 +4345,19 @@ public static int ParseAvatarName(string name, out string FirstName, out string
if (j <= start)
return 0;
- LastName = name.Substring(start, j - start);
+ LastName = name[start..j];
++i;
while (i < name.Length && name[i] == ' ') ++i;
if (i > name.Length - 3)
return 0;
- serverURI = name.Substring(i).TrimEnd();
+ serverURI = name[i..].TrimEnd();
return serverURI.Length == 0 ? 2 : 3;
}
++i;
}
- LastName = name.Substring(start).TrimEnd();
+ LastName = name[start..].TrimEnd();
return LastName.Length == 0 ? 1 : 2;
}
@@ -4272,14 +4385,14 @@ public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
{
string agentsURI = homeURI;
- if (!agentsURI.EndsWith("/"))
+ if (!agentsURI.EndsWith('/'))
agentsURI += "/";
// This is ugly, but there's no other way, given that the name is changed
// in the agent circuit data for foreigners
- if (lastName.Contains("@"))
+ if (lastName.Contains('@'))
{
- string[] parts = firstName.Split(new char[] { '.' });
+ string[] parts = firstName.Split(Util.SplitDotArray);
if (parts.Length == 2)
return CalcUniversalIdentifier(id, agentsURI, parts[0].Trim() + " " + parts[1].Trim());
}
@@ -4301,16 +4414,16 @@ private static string CalcUniversalIdentifier(UUID id, string agentsURI, string
/// string of the form first.last @foo.com or first last
public static string UniversalName(String firstName, String lastName, String homeURI)
{
- Uri uri = null;
+ Uri uri;
try
{
uri = new Uri(homeURI);
}
catch (UriFormatException)
{
- return firstName.Trim() + " " + lastName.Trim();
+ return $"{firstName.Trim()} {lastName.Trim()}";
}
- return firstName.Trim() + "." + lastName.Trim() + " " + "@" + uri.Authority;
+ return $"{firstName.Trim()}.{lastName.Trim()}@{uri.Authority}";
}
#endregion
@@ -4361,7 +4474,7 @@ public static void LogFailedXML(string message, string xml)
{
int length = xml.Length;
if (length > 250)
- xml = xml.Substring(0, 250) + "...";
+ xml = xml[..250] + "...";
for (int i = 0; i < xml.Length; i++)
{
@@ -4372,7 +4485,7 @@ public static void LogFailedXML(string message, string xml)
}
}
- m_log.ErrorFormat("{0} Failed XML ({1} bytes) = {2}", message, length, xml);
+ m_log.Error($"{message} Failed XML ({length} bytes) = {xml}");
}
///
@@ -4384,9 +4497,9 @@ public static void LogFailedXML(string message, string xml)
/// Resized image
public static Bitmap ResizeImageSolid(Image image, int width, int height)
{
- Bitmap result = new Bitmap(width, height, PixelFormat.Format24bppRgb);
+ Bitmap result = new(width, height, PixelFormat.Format24bppRgb);
- using (ImageAttributes atrib = new ImageAttributes())
+ using (ImageAttributes atrib = new())
using (Graphics graphics = Graphics.FromImage(result))
{
atrib.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
@@ -4410,174 +4523,23 @@ public static void SaveAssetToFile(string filename, byte[] data)
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, filename));
- BinaryWriter bw = new BinaryWriter(fs);
+ BinaryWriter bw = new(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
- }
-
- /* don't like this code
- public class DoubleQueue where T:class
- {
- private Queue m_lowQueue = new Queue();
- private Queue m_highQueue = new Queue();
-
- private object m_syncRoot = new object();
- private Semaphore m_s = new Semaphore(0, 1);
-
- public DoubleQueue()
- {
- }
-
- public virtual int Count
- {
- get
- {
- lock (m_syncRoot)
- return m_highQueue.Count + m_lowQueue.Count;
- }
- }
-
- public virtual void Enqueue(T data)
- {
- Enqueue(m_lowQueue, data);
- }
-
- public virtual void EnqueueLow(T data)
- {
- Enqueue(m_lowQueue, data);
- }
-
- public virtual void EnqueueHigh(T data)
- {
- Enqueue(m_highQueue, data);
- }
-
- private void Enqueue(Queue q, T data)
- {
- lock (m_syncRoot)
- {
- q.Enqueue(data);
- m_s.WaitOne(0);
- m_s.Release();
- }
- }
-
- public virtual T Dequeue()
- {
- return Dequeue(Timeout.Infinite);
- }
-
- public virtual T Dequeue(int tmo)
- {
- return Dequeue(TimeSpan.FromMilliseconds(tmo));
- }
-
- public virtual T Dequeue(TimeSpan wait)
- {
- T res = null;
-
- if (!Dequeue(wait, ref res))
- return null;
-
- return res;
- }
- public bool Dequeue(int timeout, ref T res)
- {
- return Dequeue(TimeSpan.FromMilliseconds(timeout), ref res);
- }
-
- public bool Dequeue(TimeSpan wait, ref T res)
- {
- if (!m_s.WaitOne(wait))
- return false;
-
- lock (m_syncRoot)
- {
- if (m_highQueue.Count > 0)
- res = m_highQueue.Dequeue();
- else if (m_lowQueue.Count > 0)
- res = m_lowQueue.Dequeue();
-
- if (m_highQueue.Count == 0 && m_lowQueue.Count == 0)
- return true;
-
- try
- {
- m_s.Release();
- }
- catch
- {
- }
-
- return true;
- }
- }
-
- public virtual void Clear()
- {
-
- lock (m_syncRoot)
- {
- // Make sure sem count is 0
- m_s.WaitOne(0);
-
- m_lowQueue.Clear();
- m_highQueue.Clear();
- }
- }
- }
- */
- public class BetterRandom
- {
- private const int BufferSize = 1024; // must be a multiple of 4
- private byte[] RandomBuffer;
- private int BufferOffset;
- private RNGCryptoServiceProvider rng;
- public BetterRandom()
- {
- RandomBuffer = new byte[BufferSize];
- rng = new RNGCryptoServiceProvider();
- BufferOffset = RandomBuffer.Length;
- }
- private void FillBuffer()
- {
- rng.GetBytes(RandomBuffer);
- BufferOffset = 0;
- }
- public int Next()
- {
- if (BufferOffset >= RandomBuffer.Length)
- {
- FillBuffer();
- }
- int val = BitConverter.ToInt32(RandomBuffer, BufferOffset) & 0x7fffffff;
- BufferOffset += sizeof(int);
- return val;
- }
- public int Next(int maxValue)
- {
- return Next() % maxValue;
- }
- public int Next(int minValue, int maxValue)
- {
- if (maxValue < minValue)
- {
- throw new ArgumentOutOfRangeException("maxValue must be greater than or equal to minValue");
- }
- int range = maxValue - minValue;
- return minValue + Next(range);
- }
- public double NextDouble()
+ //https://www.color.org/sRGB.pdf
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static float LinearTosRGB(float linear)
{
- int val = Next();
- return (double)val / int.MaxValue;
+ return linear <= 0.0031308f ? (linear * 12.92f) : (1.055f * MathF.Pow(linear, 0.4166667f) - 0.055f);
}
- public void GetBytes(byte[] buff)
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static float sRGBtoLinear(float rgb)
{
- rng.GetBytes(buff);
+ return (rgb < 0.04045f) ? rgb * 0.07739938f : MathF.Pow((rgb + 0.055f) / 1.055f, 2.4f);
}
}
}
diff --git a/OpenSim/Framework/VersionInfo.cs b/OpenSim/Framework/VersionInfo.cs
index 4391af35837..64367b2212d 100644
--- a/OpenSim/Framework/VersionInfo.cs
+++ b/OpenSim/Framework/VersionInfo.cs
@@ -37,9 +37,9 @@ namespace OpenSim
{
public class VersionInfo
{
- public const string VersionNumber = "0.9.2.2";
- public const string AssemblyVersionNumber = "0.9.2.2";
- public const string Release = "8738";
+ public const string VersionNumber = "0.9.3.0";
+ public const string AssemblyVersionNumber = "0.9.3.0";
+ public const string Release = "8882";
public static string Version
{
@@ -48,7 +48,7 @@ public static string Version
public static string GetVersionString(string versionNumber, string release)
{
- string versionString = "OpenSim-NGC Tranquillity " + versionNumber + "." + release;
+ string versionString = $"OpenSim-NGC Tranquillity {versionNumber}.{release}";
return versionString.PadRight(VERSIONINFO_VERSION_LENGTH);
}
diff --git a/OpenSim/Framework/VersionInfo.tt b/OpenSim/Framework/VersionInfo.tt
index b8a22e42b2c..fded930ac93 100644
--- a/OpenSim/Framework/VersionInfo.tt
+++ b/OpenSim/Framework/VersionInfo.tt
@@ -37,8 +37,8 @@ namespace OpenSim
{
public class VersionInfo
{
- public const string VersionNumber = "0.9.2.2";
- public const string AssemblyVersionNumber = "0.9.2.2";
+ public const string VersionNumber = "0.9.3.0";
+ public const string AssemblyVersionNumber = "0.9.3.0";
public const string Release = "<#= (int)DateTimeOffset.UtcNow.Subtract(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalDays #>";
public static string Version
@@ -48,7 +48,7 @@ namespace OpenSim
public static string GetVersionString(string versionNumber, string release)
{
- string versionString = "OpenSim-NGC Tranquillity " + versionNumber + "." + release;
+ string versionString = $"OpenSim-NGC Tranquillity {versionNumber}.{release}";
return versionString.PadRight(VERSIONINFO_VERSION_LENGTH);
}
diff --git a/OpenSim/Framework/ViewerEnvironment.cs b/OpenSim/Framework/ViewerEnvironment.cs
index 7042c7ee778..65ca2482a83 100644
--- a/OpenSim/Framework/ViewerEnvironment.cs
+++ b/OpenSim/Framework/ViewerEnvironment.cs
@@ -36,38 +36,38 @@ namespace OpenSim.Framework
// legacy lightshare
public class RegionLightShareData
{
- public Vector3 waterColor = new Vector3(4.0f, 38.0f, 64.0f);
+ public Vector3 waterColor = new(4.0f, 38.0f, 64.0f);
public float waterFogDensityExponent = 4.0f;
public float underwaterFogModifier = 0.25f;
- public Vector3 reflectionWaveletScale = new Vector3(2.0f, 2.0f, 2.0f);
+ public Vector3 reflectionWaveletScale = new(2.0f, 2.0f, 2.0f);
public float fresnelScale = 0.40f;
public float fresnelOffset = 0.50f;
public float refractScaleAbove = 0.03f;
public float refractScaleBelow = 0.20f;
public float blurMultiplier = 0.040f;
- public Vector2 bigWaveDirection = new Vector2(1.05f, -0.42f);
- public Vector2 littleWaveDirection = new Vector2(1.11f, -1.16f);
- public UUID normalMapTexture = new UUID("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
- public Vector4 horizon = new Vector4(0.25f, 0.25f, 0.32f, 0.32f);
+ public Vector2 bigWaveDirection = new(1.05f, -0.42f);
+ public Vector2 littleWaveDirection = new(1.11f, -1.16f);
+ public UUID normalMapTexture = new("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
+ public Vector4 horizon = new(0.25f, 0.25f, 0.32f, 0.32f);
public float hazeHorizon = 0.19f;
- public Vector4 blueDensity = new Vector4(0.12f, 0.22f, 0.38f, 0.38f);
+ public Vector4 blueDensity = new(0.12f, 0.22f, 0.38f, 0.38f);
public float hazeDensity = 0.70f;
public float densityMultiplier = 0.18f;
public float distanceMultiplier = 0.8f;
public UInt16 maxAltitude = 1605;
- public Vector4 sunMoonColor = new Vector4(0.24f, 0.26f, 0.30f, 0.30f);
+ public Vector4 sunMoonColor = new(0.24f, 0.26f, 0.30f, 0.30f);
public float sunMoonPosition = 0.317f;
- public Vector4 ambient = new Vector4(0.35f, 0.35f, 0.35f, 0.35f);
+ public Vector4 ambient = new(0.35f, 0.35f, 0.35f, 0.35f);
public float eastAngle = 0.0f;
public float sunGlowFocus = 0.10f;
public float sunGlowSize = 1.75f;
public float sceneGamma = 1.0f;
public float starBrightness = 0.0f;
- public Vector4 cloudColor = new Vector4(0.41f, 0.41f, 0.41f, 0.41f);
- public Vector3 cloudXYDensity = new Vector3(1.00f, 0.53f, 1.00f);
+ public Vector4 cloudColor = new(0.41f, 0.41f, 0.41f, 0.41f);
+ public Vector3 cloudXYDensity = new(1.00f, 0.53f, 1.00f);
public float cloudCoverage = 0.27f;
public float cloudScale = 0.42f;
- public Vector3 cloudDetailXYDensity = new Vector3(1.00f, 0.53f, 0.12f);
+ public Vector3 cloudDetailXYDensity = new(1.00f, 0.53f, 0.12f);
public float cloudScrollX = 0.20f;
public bool cloudScrollXLock = false;
public float cloudScrollY = 0.01f;
@@ -77,7 +77,7 @@ public class RegionLightShareData
public class ViewerEnvironment
{
- DayCycle Cycle = new DayCycle();
+ DayCycle Cycle = new();
public int DayLength = 14400;
public int DayOffset = 57600;
public int Flags = 0;
@@ -104,7 +104,7 @@ public void FromWLOSD(OSD osd)
public OSD ToWLOSD(UUID message, UUID region)
{
- OSDArray array = new OSDArray(4) { null, null, null, null };
+ OSDArray array = new() { null, null, null, null };
array[0] = new OSDMap { {"messageID", message }, { "regionID", region } };
Cycle.ToWLOSD(ref array);
return array;
@@ -115,23 +115,23 @@ private static Quaternion AzAlToRot(float az, float al)
if (Utils.ApproxEqual(al, 0, 1e-3f) || Utils.ApproxEqual(Math.Abs(al), Utils.TWO_PI, 1e-3f))
{
az *= 0.5f;
- return new Quaternion(0, 0, (float)Math.Sin(az), (float)Math.Cos(az));
+ return new Quaternion(0, 0, MathF.Sin(az), MathF.Cos(az));
}
if (Utils.ApproxEqual(az, 0, 1e-3f) || Utils.ApproxEqual(Math.Abs(az), Utils.TWO_PI, 1e-3f))
{
al *= 0.5f;
- return new Quaternion(0, -(float)Math.Sin(al), 0, (float)Math.Cos(al));
+ return new Quaternion(0, -MathF.Sin(al), 0, MathF.Cos(al));
}
az *= 0.5f;
- float sz = (float)Math.Sin(az);
- float cz = (float)Math.Cos(az);
+ float sz = MathF.Sin(az);
+ float cz = MathF.Cos(az);
al *= 0.5f;
- float sl = (float)Math.Sin(al);
- float cl = (float)Math.Cos(al);
+ float sl = MathF.Sin(al);
+ float cl = MathF.Cos(al);
- Quaternion rot = new Quaternion(sl * sz, -sl * cz, cl * sz, cl * cz);
+ Quaternion rot = new(sl * sz, -sl * cz, cl * sz, cl * cz);
rot.Normalize();
return rot;
}
@@ -142,7 +142,7 @@ public static void convertFromAngles(SkyData sky, float sun_angle, float east_an
float al = sun_angle;
sky.sun_rotation = AzAlToRot(az, al);
- sky.moon_rotation = AzAlToRot(az, al + (float)Math.PI);
+ sky.moon_rotation = AzAlToRot(az, al + MathF.PI);
}
public static Vector3 Xrot(Quaternion rot)
@@ -162,17 +162,16 @@ public static void convertToAngles(SkyData sky, out float sun_angle, out float e
else if (v.Z > -0.12)
{
float m = v.Y * v.Y + v.Z * v.Z;
- m = 1/(float)Math.Sqrt(m);
+ m = 1.0f / MathF.Sqrt(m);
lightnorm = new Vector4(v.Y * m, 0, v.X * m, 1);
}
else
lightnorm = new Vector4(-v.Y, -v.Z, -v.X, 1);
- sun_angle = (float)Math.Asin(v.Z);
- east_angle = -(float)Math.Atan2(v.Y, v.X);
+ sun_angle = MathF.Asin(v.Z);
+ east_angle = -MathF.Atan2(v.Y, v.X);
-
- if (Math.Abs(east_angle) < 1e-6)
+ if (MathF.Abs(east_angle) < 1e-6f)
east_angle = 0;
else if (east_angle < 0)
east_angle = Utils.TWO_PI + east_angle;
@@ -185,7 +184,7 @@ public static void convertToAngles(SkyData sky, out float sun_angle, out float e
sun_angle = Utils.PI - sun_angle;
}
*/
- if (Math.Abs(sun_angle) < 1e-6)
+ if (MathF.Abs(sun_angle) < 1e-6f)
sun_angle = 0;
else if (sun_angle < 0)
sun_angle = Utils.TWO_PI + sun_angle;
@@ -194,29 +193,30 @@ public static void convertToAngles(SkyData sky, out float sun_angle, out float e
public void FromLightShare(RegionLightShareData ls)
{
- WaterData water = new WaterData();
-
- water.waterFogColor = ls.waterColor / 256f;
- water.waterFogDensity = (float)Math.Pow(2.0f, ls.waterFogDensityExponent);
- //water.waterFogDensity = ls.waterFogDensityExponent;
- water.underWaterFogMod = ls.underwaterFogModifier;
- water.normScale = ls.reflectionWaveletScale;
- water.fresnelScale = ls.fresnelScale;
- water.fresnelOffset = ls.fresnelOffset;
- water.scaleAbove = ls.refractScaleAbove;
- water.scaleBelow = ls.refractScaleBelow;
- water.blurMultiplier = ls.blurMultiplier;
- water.wave1Dir = ls.littleWaveDirection;
- water.wave2Dir = ls.bigWaveDirection;
- water.normalMap = ls.normalMapTexture;
- water.Name = "LightshareWater";
-
- SkyData sky = new SkyData();
- convertFromAngles(sky, 2.0f * (float)Math.PI * ls.sunMoonPosition, 2.0f * (float)Math.PI * ls.eastAngle);
+ WaterData water = new()
+ {
+ waterFogColor = ls.waterColor / 256f,
+ waterFogDensity = MathF.Pow(2.0f, ls.waterFogDensityExponent),
+ //water.waterFogDensity = ls.waterFogDensityExponent;
+ underWaterFogMod = ls.underwaterFogModifier,
+ normScale = ls.reflectionWaveletScale,
+ fresnelScale = ls.fresnelScale,
+ fresnelOffset = ls.fresnelOffset,
+ scaleAbove = ls.refractScaleAbove,
+ scaleBelow = ls.refractScaleBelow,
+ blurMultiplier = ls.blurMultiplier,
+ wave1Dir = ls.littleWaveDirection,
+ wave2Dir = ls.bigWaveDirection,
+ normalMap = ls.normalMapTexture,
+ Name = "LightshareWater"
+ };
+
+ SkyData sky = new();
+ convertFromAngles(sky, Utils.TWO_PI * ls.sunMoonPosition, Utils.TWO_PI * ls.eastAngle);
sky.sunlight_color = ls.sunMoonColor * 3.0f;
sky.ambient = new Vector3(ls.ambient.X * 3.0f, ls.ambient.Y * 3.0f, ls.ambient.Z * 3.0f);
sky.blue_horizon = new Vector3(ls.horizon.X * 2.0f, ls.horizon.Y * 2.0f, ls.horizon.Z * 2.0f);
- sky.blue_density = new Vector3(ls.blueDensity.X * 2.0f, ls.blueDensity.Y * 2.0f, ls.blueDensity.Z * 2.0f);;
+ sky.blue_density = new Vector3(ls.blueDensity.X * 2.0f, ls.blueDensity.Y * 2.0f, ls.blueDensity.Z * 2.0f);
sky.haze_horizon = ls.hazeHorizon;
sky.haze_density = ls.hazeDensity;
sky.cloud_shadow = ls.cloudCoverage;
@@ -237,14 +237,13 @@ public void FromLightShare(RegionLightShareData ls)
sky.star_brightness = ls.starBrightness * 250f;
sky.Name = "LightshareSky";
- Cycle = new DayCycle();
- Cycle.Name = "Lightshare";
+ Cycle = new DayCycle { Name = "Lightshare" };
Cycle.waterframes.Add(water.Name, water);
- DayCycle.TrackEntry track = new DayCycle.TrackEntry(-1, water.Name);
+ DayCycle.TrackEntry track = new(-1, water.Name);
Cycle.waterTrack.Add(track);
Cycle.skyframes.Add(sky.Name, sky);
- track = new DayCycle.TrackEntry(-1, sky.Name);
+ track = new(-1, sky.Name);
Cycle.skyTrack0.Add(track);
InvalidateCaches();
@@ -252,7 +251,7 @@ public void FromLightShare(RegionLightShareData ls)
public RegionLightShareData ToLightShare()
{
- RegionLightShareData ls = new RegionLightShareData();
+ RegionLightShareData ls = new();
DayCycle.TrackEntry te;
if (Cycle.waterTrack.Count > 0)
@@ -261,7 +260,7 @@ public RegionLightShareData ToLightShare()
if (Cycle.waterframes.TryGetValue(te.frameName, out WaterData water))
{
ls.waterColor = water.waterFogColor * 256f;
- ls.waterFogDensityExponent = (float)Math.Sqrt(water.waterFogDensity);
+ ls.waterFogDensityExponent = MathF.Sqrt(water.waterFogDensity);
//ls.waterFogDensityExponent = water.waterFogDensity;
ls.underwaterFogModifier = water.underWaterFogMod;
ls.reflectionWaveletScale = water.normScale;
@@ -281,10 +280,9 @@ public RegionLightShareData ToLightShare()
te = Cycle.skyTrack0[0];
if (Cycle.skyframes.TryGetValue(te.frameName, out SkyData sky))
{
- Vector4 lightnorm;
- convertToAngles(sky, out ls.sunMoonPosition, out ls.eastAngle, out lightnorm);
- ls.sunMoonPosition *= 0.5f / (float)Math.PI;
- ls.eastAngle *= 0.5f / (float)Math.PI;
+ convertToAngles(sky, out ls.sunMoonPosition, out ls.eastAngle, out Vector4 _);
+ ls.sunMoonPosition *= 0.5f / MathF.PI;
+ ls.eastAngle *= 0.5f / MathF.PI;
ls.sunMoonColor = sky.sunlight_color / 3f;
ls.ambient = new Vector4(sky.ambient.X / 3.0f, sky.ambient.Y / 3.0f, sky.ambient.Z / 3.0f, 1);
ls.horizon = new Vector4(sky.blue_horizon.X / 2.0f, sky.blue_horizon.Y / 2.0f, sky.blue_horizon.Z / 2.0f, 1);
@@ -314,8 +312,7 @@ public RegionLightShareData ToLightShare()
public void FromOSD(OSD osd)
{
- OSDMap map = osd as OSDMap;
- if (map == null)
+ if (osd is not OSDMap map)
return;
OSD otmp;
@@ -325,8 +322,8 @@ public void FromOSD(OSD osd)
Cycle = new DayCycle();
Cycle.FromOSD(otmp as OSDMap);
}
- if (Cycle == null)
- Cycle = new DayCycle();
+
+ Cycle ??= new DayCycle();
if (map.TryGetValue("day_length", out otmp))
DayLength = otmp;
@@ -375,8 +372,7 @@ public void SortAltitudes()
public bool CycleFromOSD(OSD osd)
{
- OSDMap map = osd as OSDMap;
- if (map == null)
+ if (osd is not OSDMap map)
return false;
if (!map.TryGetValue("type", out OSD tmp))
return false;
@@ -393,8 +389,7 @@ public bool CycleFromOSD(OSD osd)
public bool FromAssetOSD(string name, OSD osd)
{
- OSDMap map = osd as OSDMap;
- if (map == null)
+ if (osd is not OSDMap map)
return false;
if (!map.TryGetValue("type", out OSD tmp))
return false;
@@ -403,8 +398,7 @@ public bool FromAssetOSD(string name, OSD osd)
bool ok = false;
if (type == "water")
{
- if (Cycle == null)
- Cycle = new DayCycle();
+ Cycle ??= new DayCycle();
ok = Cycle.replaceWaterFromOSD(name, map);
}
else
@@ -417,8 +411,7 @@ public bool FromAssetOSD(string name, OSD osd)
}
else if(type == "sky")
{
- if (Cycle == null)
- Cycle = new DayCycle();
+ Cycle ??= new DayCycle();
ok = Cycle.replaceSkyFromOSD(name, map);
}
}
@@ -431,22 +424,18 @@ public bool FromAssetOSD(string name, OSD osd)
public OSD ToOSD()
{
- OSDMap env = new OSDMap();
- env["day_cycle"] = Cycle.ToOSD();
- env["day_length"] = DayLength;
- env["day_offset"] = DayOffset;
- env["flags"] = Flags;
- env["env_version"] = version;
-
- OSDArray alt = new OSDArray();
- alt.Add(Altitudes[0]);
- alt.Add(Altitudes[1]);
- alt.Add(Altitudes[2]);
- env["track_altitudes"] = alt;
- return env;
+ return new OSDMap
+ {
+ ["day_cycle"] = Cycle.ToOSD(),
+ ["day_length"] = DayLength,
+ ["day_offset"] = DayOffset,
+ ["flags"] = Flags,
+ ["env_version"] = version,
+ ["track_altitudes"] = new OSDArray() { Altitudes[0], Altitudes[1], Altitudes[2] }
+ };
}
- public readonly object m_cachedbytesLock = new object();
+ public readonly object m_cachedbytesLock = new();
public byte[] m_cachedbytes = null;
public byte[] m_cachedWLbytes = null;
@@ -470,7 +459,7 @@ public byte[] ToCapBytes(UUID regionID, int parcelID)
byte[] ret = m_cachedbytes;
if (ret == null)
{
- OSDMap map = new OSDMap();
+ OSDMap map = new();
OSDMap cenv = (OSDMap)ToOSD();
cenv["parcel_id"] = parcelID;
cenv["region_id"] = regionID;
@@ -509,7 +498,7 @@ public static ViewerEnvironment FromOSDString(string s)
try
{
OSD eosd = OSDParser.Deserialize(s);
- ViewerEnvironment VEnv = new ViewerEnvironment();
+ ViewerEnvironment VEnv = new();
VEnv.FromOSD(eosd);
return VEnv;
}
@@ -537,28 +526,29 @@ public ViewerEnvironment Clone()
{
// im lazy need to proper clone later
OSD osd = ToOSD();
- ViewerEnvironment VEnv = new ViewerEnvironment();
+ ViewerEnvironment VEnv = new();
VEnv.FromOSD(osd);
return VEnv;
}
public static OSD DefaultToOSD(UUID regionID, int parcel)
{
- OSDMap top = new OSDMap();
- OSDMap env = new OSDMap();
- env["is_default"] = true;
+ OSDMap env = new()
+ {
+ ["is_default"] = true,
+ ["region_id"] = regionID,
+ ["track_altitudes"] = new OSDArray() { 1000f, 2000f, 3000f }
+ };
if (parcel >= 0)
env["parcel_id"] = parcel;
- env["region_id"] = regionID;
- OSDArray alt = new OSDArray();
- alt.Add(1000f);
- alt.Add(2000f);
- alt.Add(3000f);
- env["track_altitudes"] = alt;
- top["environment"] = env;
+
+ OSDMap top = new()
+ {
+ ["environment"] = env,
+ ["success"] = true
+ };
if (parcel >= 0)
top["parcel_id"] = parcel;
- top["success"] = true;
return top;
}
@@ -667,13 +657,13 @@ public bool getPositions(float altitude, float dayfrac, out Vector3 sundir, out
moonrot = Quaternion.Identity;
List track = FindTrack(altitude);
- if (track == null || track.Count == 0)
+ if (track is null || track.Count == 0)
return false;
if (!FindSkies(track, dayfrac, out dayfrac, out SkyData sky1, out SkyData sky2))
return false;
- if (sky2 == null)
+ if (sky2 is null)
{
moonrot = sky1.moon_rotation;
moondir = Xrot(moonrot);
@@ -690,6 +680,92 @@ public bool getPositions(float altitude, float dayfrac, out Vector3 sundir, out
return true;
}
+ public bool getPositions_sundir(float altitude, float dayfrac, out Vector3 sundir)
+ {
+ sundir = Vector3.Zero;
+
+ List track = FindTrack(altitude);
+ if (track is null || track.Count == 0)
+ return false;
+
+ if (!FindSkies(track, dayfrac, out dayfrac, out SkyData sky1, out SkyData sky2))
+ return false;
+
+ if (sky2 is null)
+ {
+ sundir = Xrot(sky1.sun_rotation);
+ return true;
+ }
+
+ Quaternion sunrot = Quaternion.Slerp(sky1.sun_rotation, sky2.sun_rotation, dayfrac);
+ sundir = Xrot(sunrot);
+ return true;
+ }
+
+ public bool getPositions_sunrot(float altitude, float dayfrac, out Quaternion sunrot)
+ {
+ sunrot = Quaternion.Identity;
+
+ List track = FindTrack(altitude);
+ if (track is null || track.Count == 0)
+ return false;
+
+ if (!FindSkies(track, dayfrac, out dayfrac, out SkyData sky1, out SkyData sky2))
+ return false;
+
+ if (sky2 is null)
+ {
+ sunrot = sky1.sun_rotation;
+ return true;
+ }
+
+ sunrot = Quaternion.Slerp(sky1.sun_rotation, sky2.sun_rotation, dayfrac);
+ return true;
+ }
+
+ public bool getPositions_moondir(float altitude, float dayfrac, out Vector3 moondir)
+ {
+ moondir = Vector3.Zero;
+
+ List track = FindTrack(altitude);
+ if (track is null || track.Count == 0)
+ return false;
+
+ if (!FindSkies(track, dayfrac, out dayfrac, out SkyData sky1, out SkyData sky2))
+ return false;
+
+ if (sky2 is null)
+ {
+ moondir = Xrot(sky1.moon_rotation);
+ return true;
+ }
+
+ Quaternion moonrot = Quaternion.Slerp(sky1.moon_rotation, sky2.moon_rotation, dayfrac);
+ moondir = Xrot(moonrot);
+ return true;
+ }
+
+ public bool getPositions_moonrot(float altitude, float dayfrac, out Quaternion moonrot)
+ {
+ moonrot = Quaternion.Identity;
+
+ List track = FindTrack(altitude);
+ if (track is null || track.Count == 0)
+ return false;
+
+ if (!FindSkies(track, dayfrac, out dayfrac, out SkyData sky1, out SkyData sky2))
+ return false;
+
+ if (sky2 is null)
+ {
+ moonrot = sky1.moon_rotation;
+ return true;
+ }
+
+ moonrot = Quaternion.Slerp(sky1.moon_rotation, sky2.moon_rotation, dayfrac);
+ return true;
+ }
+
/* not needed for wl viewers
public bool getWLPositions(float altitude, float dayfrac, out Vector3 sundir)
{
@@ -718,8 +794,7 @@ public bool getWLPositions(float altitude, float dayfrac, out Vector3 sundir)
public void GatherAssets(Dictionary uuids)
{
- if (Cycle != null)
- Cycle.GatherAssets(uuids);
+ Cycle?.GatherAssets(uuids);
}
}
}
diff --git a/OpenSim/Framework/ViewerSky.cs b/OpenSim/Framework/ViewerSky.cs
index 7ce7794e955..2fd412ab142 100644
--- a/OpenSim/Framework/ViewerSky.cs
+++ b/OpenSim/Framework/ViewerSky.cs
@@ -52,12 +52,14 @@ public AbsCoefData(float w, float expt, float exps, float lin, float cons)
public OSDMap ToOSD()
{
- OSDMap map = new OSDMap();
- map["constant_term"] = constant_term;
- map["exp_scale"] = exp_scale;
- map["exp_term"] = exp_term;
- map["linear_term"] = linear_term;
- map["width"] = width;
+ OSDMap map = new()
+ {
+ ["constant_term"] = constant_term,
+ ["exp_scale"] = exp_scale,
+ ["exp_term"] = exp_term,
+ ["linear_term"] = linear_term,
+ ["width"] = width
+ };
return map;
}
@@ -92,13 +94,15 @@ public mCoefData(float w, float expt, float exps, float lin, float cons, float a
public OSDMap ToOSD()
{
- OSDMap map = new OSDMap();
- map["anisotropy"] = anisotropy;
- map["constant_term"] = constant_term;
- map["exp_scale"] = exp_scale;
- map["exp_term"] = exp_term;
- map["linear_term"] = linear_term;
- map["width"] = width;
+ OSDMap map = new()
+ {
+ ["anisotropy"] = anisotropy,
+ ["constant_term"] = constant_term,
+ ["exp_scale"] = exp_scale,
+ ["exp_term"] = exp_term,
+ ["linear_term"] = linear_term,
+ ["width"] = width
+ };
return map;
}
@@ -113,40 +117,40 @@ public void FromOSD(OSDMap map)
}
}
//AbsCoefData(float w, float expt, float exps, float lin, float cons)
- public AbsCoefData abscoefA = new AbsCoefData(25000f, 0, 0, 0, 0);
- public AbsCoefData abscoefB = new AbsCoefData(0, 0, 0, -6.6666667e-5f, 1f);
- public AbsCoefData rayleigh_config = new AbsCoefData(0, 1, -1.25e-4f, 0, 0);
+ public AbsCoefData abscoefA = new(25000f, 0, 0, 0, 0);
+ public AbsCoefData abscoefB = new(0, 0, 0, -6.6666667e-5f, 1f);
+ public AbsCoefData rayleigh_config = new(0, 1, -1.25e-4f, 0, 0);
//mCoefData(float w, float expt, float exps, float lin, float cons, float ani)
- public mCoefData mieconf = new mCoefData(0, 1f, -8.333333e-4f, 0, 0, 0.8f);
+ public mCoefData mieconf = new(0, 1f, -8.333333e-4f, 0, 0, 0.8f);
- UUID bloom_id = new UUID("3c59f7fe-9dc8-47f9-8aaf-a9dd1fbc3bef");
- UUID cloud_id = new UUID("1dc1368f-e8fe-f02d-a08d-9d9f11c1af6b");
- UUID halo_id = new UUID("12149143-f599-91a7-77ac-b52a3c0f59cd");
- UUID moon_id = new UUID("ec4b9f0b-d008-45c6-96a4-01dd947ac621");
- UUID rainbow_id = new UUID("11b4c57c-56b3-04ed-1f82-2004363882e4");
+ UUID bloom_id = new("3c59f7fe-9dc8-47f9-8aaf-a9dd1fbc3bef");
+ UUID cloud_id = new("1dc1368f-e8fe-f02d-a08d-9d9f11c1af6b");
+ UUID halo_id = new("12149143-f599-91a7-77ac-b52a3c0f59cd");
+ UUID moon_id = new("ec4b9f0b-d008-45c6-96a4-01dd947ac621");
+ UUID rainbow_id = new("11b4c57c-56b3-04ed-1f82-2004363882e4");
UUID sun_id = UUID.Zero;
- public Vector3 ambient = new Vector3(1.047f, 1.047f, 1.047f); //?
- public Vector3 blue_density = new Vector3(0.2447f, 0.4487f, 0.76f);
- public Vector3 blue_horizon = new Vector3(0.4954f, 0.4954f, 0.64f);
- public Vector3 cloud_color = new Vector3(0.41f, 0.41f, 0.41f);
- public Vector3 cloud_pos_density1 = new Vector3(1, 0.5260f, 1);
- public Vector3 cloud_pos_density2 = new Vector3(1, 0.5260f, 0.12f);
+ public Vector3 ambient = new(1.047f, 1.047f, 1.047f); //?
+ public Vector3 blue_density = new(0.2447f, 0.4487f, 0.76f);
+ public Vector3 blue_horizon = new(0.4954f, 0.4954f, 0.64f);
+ public Vector3 cloud_color = new(0.41f, 0.41f, 0.41f);
+ public Vector3 cloud_pos_density1 = new(1, 0.5260f, 1);
+ public Vector3 cloud_pos_density2 = new(1, 0.5260f, 0.12f);
public float cloud_scale = 0.42f;
- public Vector2 cloud_scroll_rate = new Vector2(0.2f, 0.011f);
+ public Vector2 cloud_scroll_rate = new(0.2f, 0.011f);
public float cloud_shadow = 0.27f;
public float density_multiplier = 0.00018f;
public float distance_multiplier = 0.8f;
public float gamma = 1;
- public Vector3 glow = new Vector3(5, 0.0010f, -0.48f);
+ public Vector3 glow = new(5, 0.0010f, -0.48f);
public float haze_density = 0.7f;
public float haze_horizon = 0.19f;
public float max_y = 1605;
public float star_brightness = 0f;
//this is a vector3 now, but all viewers expect a vector4, so keeping like this for now
- public Vector4 sunlight_color = new Vector4(0.7342f, 0.7815f, 0.9f, 0.3f);
+ public Vector4 sunlight_color = new(0.7342f, 0.7815f, 0.9f, 0.3f);
public string Name = "DefaultSky";
public float cloud_variance = 0;
@@ -154,6 +158,8 @@ public void FromOSD(OSDMap map)
public float dome_radius = 15000f;
public float droplet_radius = 800.0f;
public float ice_level = 0f;
+
+ public bool HasRefProbe = false;
public float reflectionProbeAmbiance = 0f;
public float moisture_level = 0;
@@ -161,11 +167,11 @@ public void FromOSD(OSDMap map)
public float sky_top_radius = 6420;
public float sun_arc_radians = 0.00045f;
- public Quaternion sun_rotation = new Quaternion(0, -0.3824995f, 0, 0.9239557f);
+ public Quaternion sun_rotation = new(0, -0.3824995f, 0, 0.9239557f);
public float sun_scale = 1;
public float moon_brightness = 0.5f;
- public Quaternion moon_rotation = new Quaternion(0, 0.9239557f, 0, 0.3824995f);
+ public Quaternion moon_rotation = new(0, 0.9239557f, 0, 0.3824995f);
public float moon_scale = 1;
public float planet_radius = 6360f;
@@ -218,24 +224,19 @@ public void FromWLOSD(string name, OSD osd)
sunlight_color = map["sunlight_color"];
- reflectionProbeAmbiance = 0f;
-
ViewerEnvironment.convertFromAngles(this, map["sun_angle"], map["east_angle"]);
Name = name;
}
public OSD ToWLOSD()
{
- OSDMap map = new OSDMap();
+ OSDMap map = new();
- float sun_angle;
- float east_angle;
- Vector4 lightnorm;
- ViewerEnvironment.convertToAngles(this, out sun_angle, out east_angle, out lightnorm);
+ ViewerEnvironment.convertToAngles(this, out float sun_angle, out float east_angle, out Vector4 lightnorm);
map["ambient"] = new Vector4(ambient.X, ambient.Y, ambient.Z, 1);
map["blue_density"] = new Vector4(blue_density.X, blue_density.Y, blue_density.Z, 1);
map["blue_horizon"] = new Vector4(blue_horizon.X, blue_horizon.Y, blue_horizon.Z, 1);
- map["cloud_color"] = new Vector4(cloud_color.X, cloud_color.Y, cloud_color.Z, 1);;
+ map["cloud_color"] = new Vector4(cloud_color.X, cloud_color.Y, cloud_color.Z, 1);
map["cloud_pos_density1"] = new Vector4(cloud_pos_density1.X, cloud_pos_density1.Y, cloud_pos_density1.Z, 1);
map["cloud_pos_density2"] = new Vector4(cloud_pos_density2.X, cloud_pos_density2.Y, cloud_pos_density2.Z, 1);
map["cloud_scale"] = new Vector4(cloud_scale, 0, 0, 1);
@@ -261,87 +262,78 @@ public OSD ToWLOSD()
public OSD ToOSD()
{
- OSDMap map = new OSDMap(64);
-
- OSDArray abscfg = new OSDArray(2);
- abscfg.Add(abscoefA.ToOSD());
- abscfg.Add(abscoefB.ToOSD());
- map["absorption_config"] = abscfg;
-
- map["bloom_id"] = bloom_id;
- map["cloud_color"] = cloud_color;
- map["cloud_id"] = cloud_id;
- map["cloud_pos_density1"] = cloud_pos_density1;
- map["cloud_pos_density2"] = cloud_pos_density2;
- map["cloud_scale"] = cloud_scale;
- map["cloud_scroll_rate"] = cloud_scroll_rate;
- map["cloud_shadow"] = cloud_shadow;
- map["cloud_variance"] = cloud_variance;
- map["dome_offset"] = dome_offset;
- map["dome_radius"] = dome_radius;
- map["droplet_radius"] = droplet_radius;
- map["gamma"] = gamma;
- map["glow"] = glow;
- map["halo_id"] = halo_id;
- map["ice_level"] = ice_level;
-
- if (reflectionProbeAmbiance != 0f)
+ OSDMap map = new(64)
+ {
+ ["absorption_config"] = new OSDArray() { abscoefA.ToOSD(), abscoefB.ToOSD() },
+ ["bloom_id"] = bloom_id,
+ ["cloud_color"] = cloud_color,
+ ["cloud_id"] = cloud_id,
+ ["cloud_pos_density1"] = cloud_pos_density1,
+ ["cloud_pos_density2"] = cloud_pos_density2,
+ ["cloud_scale"] = cloud_scale,
+ ["cloud_scroll_rate"] = cloud_scroll_rate,
+ ["cloud_shadow"] = cloud_shadow,
+ ["cloud_variance"] = cloud_variance,
+ ["dome_offset"] = dome_offset,
+ ["dome_radius"] = dome_radius,
+ ["droplet_radius"] = droplet_radius,
+ ["gamma"] = gamma,
+ ["glow"] = glow,
+ ["halo_id"] = halo_id,
+ ["ice_level"] = ice_level,
+
+ ["legacy_haze"] = new OSDMap()
+ {
+ ["ambient"] = ambient,
+ ["blue_density"] = blue_density,
+ ["blue_horizon"] = blue_horizon,
+ ["density_multiplier"] = density_multiplier,
+ ["distance_multiplier"] = distance_multiplier,
+ ["haze_density"] = haze_density,
+ ["haze_horizon"] = haze_horizon
+ },
+
+ ["max_y"] = max_y,
+ ["moisture_level"] = moisture_level,
+ ["moon_brightness"] = moon_brightness,
+ ["moon_id"] = moon_id,
+ ["moon_rotation"] = moon_rotation,
+ ["moon_scale"] = moon_scale,
+ ["planet_radius"] = planet_radius,
+ ["rainbow_id"] = rainbow_id,
+
+ ["sky_bottom_radius"] = sky_bottom_radius,
+ ["sky_top_radius"] = sky_top_radius,
+ ["star_brightness"] = star_brightness,
+
+ ["sun_arc_radians"] = sun_arc_radians,
+ ["sun_id"] = sun_id,
+ ["sun_rotation"] = sun_rotation,
+ ["sun_scale"] = sun_scale,
+ ["sunlight_color"] = sunlight_color,
+
+ ["mie_config"] = new OSDArray() { mieconf.ToOSD() },
+ ["rayleigh_config"] = new OSDArray() { rayleigh_config.ToOSD() },
+
+ ["type"] = "sky"
+ };
+
+ if(HasRefProbe)
map["reflection_probe_ambiance"] = reflectionProbeAmbiance;
- OSDMap lhaze = new OSDMap();
- lhaze["ambient"] = ambient;
- lhaze["blue_density"] = blue_density;
- lhaze["blue_horizon"] = blue_horizon;
- lhaze["density_multiplier"] = density_multiplier;
- lhaze["distance_multiplier"] = distance_multiplier;
- lhaze["haze_density"] = haze_density;
- lhaze["haze_horizon"] = haze_horizon;
- map["legacy_haze"] = lhaze;
-
- map["max_y"] = max_y;
-
- OSDArray miecfg = new OSDArray();
- miecfg.Add(mieconf.ToOSD());
- map["mie_config"] = miecfg;
-
- map["moisture_level"] = moisture_level;
- map["moon_brightness"] = moon_brightness;
- map["moon_id"] = moon_id;
- map["moon_rotation"] = moon_rotation;
- map["moon_scale"] = moon_scale;
- map["planet_radius"] = planet_radius;
- map["rainbow_id"] = rainbow_id;
-
- OSDArray rayl = new OSDArray();
- rayl.Add(rayleigh_config.ToOSD());
- map["rayleigh_config"] = rayl;
-
- map["sky_bottom_radius"] = sky_bottom_radius;
- map["sky_top_radius"] = sky_top_radius;
- map["star_brightness"] = star_brightness;
-
- map["sun_arc_radians"] = sun_arc_radians;
- map["sun_id"] = sun_id;
- map["sun_rotation"] = sun_rotation;
- map["sun_scale"] = sun_scale;
- map["sunlight_color"] = sunlight_color;
-
- map["type"] = "sky";
return map;
}
public void FromOSD(string name, OSDMap map)
{
- OSDArray tmpArray;
OSD otmp;
- if (map.TryGetValue("absorption_config",out otmp) && otmp is OSDArray)
+ if (map.TryGetValue("absorption_config", out otmp) && otmp is OSDArray absorptionArray)
{
- tmpArray = otmp as OSDArray;
- if (tmpArray.Count > 0)
+ if (absorptionArray.Count > 0)
{
- abscoefA.FromOSD(tmpArray[0] as OSDMap);
- if (tmpArray.Count > 1)
- abscoefA.FromOSD(tmpArray[1] as OSDMap);
+ abscoefA.FromOSD(absorptionArray[0] as OSDMap);
+ if (absorptionArray.Count > 1)
+ abscoefA.FromOSD(absorptionArray[1] as OSDMap);
}
}
if (map.TryGetValue("bloom_id", out otmp))
@@ -378,11 +370,13 @@ public void FromOSD(string name, OSDMap map)
ice_level = otmp;
if (map.TryGetValue("reflection_probe_ambiance", out otmp))
+ {
reflectionProbeAmbiance = otmp;
+ HasRefProbe = true;
+ }
- if (map.TryGetValue("legacy_haze", out OSD tmp) && tmp is OSDMap)
+ if (map.TryGetValue("legacy_haze", out OSD tmp) && tmp is OSDMap lHaze)
{
- OSDMap lHaze = tmp as OSDMap;
if (lHaze.TryGetValue("ambient", out otmp))
ambient = otmp;
if (lHaze.TryGetValue("blue_density", out otmp))
@@ -402,11 +396,10 @@ public void FromOSD(string name, OSDMap map)
if (map.TryGetValue("max_y", out otmp))
max_y = otmp;
- if (map.TryGetValue("mie_config", out otmp) && otmp is OSDArray)
+ if (map.TryGetValue("mie_config", out otmp) && otmp is OSDArray mieArray)
{
- tmpArray = otmp as OSDArray;
- if (tmpArray.Count > 0)
- mieconf.FromOSD(tmpArray[0] as OSDMap);
+ if (mieArray.Count > 0)
+ mieconf.FromOSD(mieArray[0] as OSDMap);
}
if (map.TryGetValue("moisture_level", out otmp))
@@ -424,11 +417,10 @@ public void FromOSD(string name, OSDMap map)
if (map.TryGetValue("rainbow_id", out otmp))
rainbow_id = otmp;
- if (map.TryGetValue("rayleigh_config", out otmp) && otmp is OSDArray)
+ if (map.TryGetValue("rayleigh_config", out otmp) && otmp is OSDArray rayleighArray)
{
- tmpArray = otmp as OSDArray;
- if (tmpArray.Count > 0)
- rayleigh_config.FromOSD(tmpArray[0] as OSDMap);
+ if (rayleighArray.Count > 0)
+ rayleigh_config.FromOSD(rayleighArray[0] as OSDMap);
}
if (map.TryGetValue("sky_bottom_radius", out otmp))
@@ -447,10 +439,9 @@ public void FromOSD(string name, OSDMap map)
if (map.TryGetValue("sun_scale", out otmp))
sun_scale = otmp;
- if (map.TryGetValue("sunlight_color", out otmp) && otmp is OSDArray)
+ if (map.TryGetValue("sunlight_color", out otmp) && otmp is OSDArray sunlightArray)
{
- tmpArray = otmp as OSDArray;
- if(tmpArray.Count == 4)
+ if(sunlightArray.Count == 4)
sunlight_color = otmp;
else
{
diff --git a/OpenSim/Framework/ViewerWater.cs b/OpenSim/Framework/ViewerWater.cs
index 41383d2a050..e3a95738508 100644
--- a/OpenSim/Framework/ViewerWater.cs
+++ b/OpenSim/Framework/ViewerWater.cs
@@ -33,20 +33,20 @@ namespace OpenSim.Framework
{
public class WaterData
{
- public UUID normalMap = new UUID("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
- public UUID transpTexture = new UUID("2bfd3884-7e27-69b9-ba3a-3e673f680004");
+ public UUID normalMap = new("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
+ public UUID transpTexture = new("2bfd3884-7e27-69b9-ba3a-3e673f680004");
public float blurMultiplier = 0.04f;
public float fresnelOffset = 0.5f;
public float fresnelScale = 0.4f;
- public Vector3 normScale = new Vector3(2f, 2f, 2f);
+ public Vector3 normScale = new(2f, 2f, 2f);
public float scaleAbove = 0.03f;
public float scaleBelow = 0.2f;
public float underWaterFogMod = 0.25f;
- public Vector3 waterFogColor = new Vector3(0.0156f, 0.149f, 0.2509f);
+ public Vector3 waterFogColor = new(0.0156f, 0.149f, 0.2509f);
public float waterFogDensity = 10;
- public Vector2 wave1Dir = new Vector2(1.05f, -0.42f);
- public Vector2 wave2Dir = new Vector2(1.11f, -1.16f);
+ public Vector2 wave1Dir = new(1.05f, -0.42f);
+ public Vector2 wave2Dir = new(1.11f, -1.16f);
public string Name;
public void FromWLOSD(string name, OSD osd)
@@ -71,23 +71,22 @@ public void FromWLOSD(string name, OSD osd)
public OSDMap ToWLOSD()
{
- OSDMap map = new OSDMap();
-
- map["blurMultiplier"] = blurMultiplier;
- map["fresnelOffset"] = fresnelOffset;
- map["fresnelScale"] = fresnelScale;
- map["normScale"] = normScale;
- map["normalMap"] = normalMap;
- map["scaleAbove"] = scaleAbove;
- map["scaleBelow"] = scaleBelow;
- map["underWaterFogMod"] = underWaterFogMod;
- map["waterFogColor"] = new Vector4(waterFogColor.X, waterFogColor.Y, waterFogColor.Z, 1);
- map["waterFogDensity"] = waterFogDensity;
- //map["waterFogDensity"] = (float)Math.Pow(2.0f, waterFogDensity);
- map["wave1Dir"] = wave1Dir;
- map["wave2Dir"] = wave2Dir;
-
- return map;
+ return new OSDMap
+ {
+ ["blurMultiplier"] = blurMultiplier,
+ ["fresnelOffset"] = fresnelOffset,
+ ["fresnelScale"] = fresnelScale,
+ ["normScale"] = normScale,
+ ["normalMap"] = normalMap,
+ ["scaleAbove"] = scaleAbove,
+ ["scaleBelow"] = scaleBelow,
+ ["underWaterFogMod"] = underWaterFogMod,
+ ["waterFogColor"] = new Vector4(waterFogColor.X, waterFogColor.Y, waterFogColor.Z, 1),
+ ["waterFogDensity"] = waterFogDensity,
+ //["waterFogDensity"] = MathF.Pow(2.0f, waterFogDensity),
+ ["wave1Dir"] = wave1Dir,
+ ["wave2Dir"] = wave2Dir
+ };
}
public void FromOSD(string name, OSDMap map)
@@ -125,24 +124,23 @@ public void FromOSD(string name, OSDMap map)
public OSDMap ToOSD()
{
- OSDMap map = new OSDMap();
-
- map["blur_multiplier"] = blurMultiplier;
- map["fresnel_offset"] = fresnelOffset;
- map["fresnel_scale"] = fresnelScale;
- map["normal_scale"] = normScale;
- map["normal_map"] = normalMap;
- map["scale_above"] = scaleAbove;
- map["scale_below"] = scaleBelow;
- map["underwater_fog_mod"] = underWaterFogMod;
- map["water_fog_color"] = waterFogColor;
- map["water_fog_density"] = waterFogDensity;
- map["wave1_direction"] = wave1Dir;
- map["wave2_direction"] = wave2Dir;
- map["transparent_texture"] = transpTexture;
- map["type"] ="water";
-
- return map;
+ return new OSDMap
+ {
+ ["blur_multiplier"] = blurMultiplier,
+ ["fresnel_offset"] = fresnelOffset,
+ ["fresnel_scale"] = fresnelScale,
+ ["normal_scale"] = normScale,
+ ["normal_map"] = normalMap,
+ ["scale_above"] = scaleAbove,
+ ["scale_below"] = scaleBelow,
+ ["underwater_fog_mod"] = underWaterFogMod,
+ ["water_fog_color"] = waterFogColor,
+ ["water_fog_density"] = waterFogDensity,
+ ["wave1_direction"] = wave1Dir,
+ ["wave2_direction"] = wave2Dir,
+ ["transparent_texture"] = transpTexture,
+ ["type"] = "water"
+ };
}
public void GatherAssets(Dictionary uuids)
diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs
index 2d48c2acb10..9d3e682bf7e 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,8 +43,10 @@
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse.StructuredData;
-using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
+using System.Net.Http;
+using System.Security.Authentication;
+using System.Runtime.CompilerServices;
namespace OpenSim.Framework
{
@@ -58,7 +59,10 @@ public static class WebUtil
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- public static ExpiringKey GlobalExpiringBadURLs = new ExpiringKey(30000);
+ public static SocketsHttpHandler SharedSocketsHttpHandlerNoRedir = null;
+ public static SocketsHttpHandler SharedSocketsHttpHandler = null;
+
+ public static ExpiringKey GlobalExpiringBadURLs = new(30000);
///
/// Control the printing of certain debug messages.
///
@@ -102,41 +106,198 @@ public static bool ValidateServerCertificateNoChecks(
{
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
- if (sslPolicyErrors == SslPolicyErrors.None)
- return true;
- return false;
+ return sslPolicyErrors == SslPolicyErrors.None;
}
#region JSONRequest
+ public static void SetupHTTPClients(bool NoVerifyCertChain, bool NoVerifyCertHostname, IWebProxy proxy, int MaxConnectionsPerServer )
+ {
+ SocketsHttpHandler shh = new()
+ {
+ AllowAutoRedirect = false,
+ AutomaticDecompression = DecompressionMethods.None,
+ ConnectTimeout = TimeSpan.FromSeconds(120),
+ PreAuthenticate = false,
+ UseCookies = false,
+ MaxConnectionsPerServer = MaxConnectionsPerServer,
+ PooledConnectionIdleTimeout = TimeSpan.FromSeconds(31),
+ PooledConnectionLifetime = TimeSpan.FromMinutes(3)
+ };
+ //shh.SslOptions.ClientCertificates = null,
+ shh.SslOptions.EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
+ if (NoVerifyCertChain)
+ {
+ shh.SslOptions.CertificateRevocationCheckMode = X509RevocationMode.NoCheck;
+ if (NoVerifyCertHostname)
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ errors &= ~(SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch);
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ else
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ }
+ else
+ {
+ shh.SslOptions.CertificateRevocationCheckMode = X509RevocationMode.NoCheck;
+ if (NoVerifyCertHostname)
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ errors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ else
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ }
+
+ if (proxy is null)
+ shh.UseProxy = false;
+ else
+ {
+ shh.Proxy = proxy;
+ shh.UseProxy = true;
+ }
+
+ SharedSocketsHttpHandlerNoRedir = shh;
+
+ // ****************
+
+ shh = new()
+ {
+ AllowAutoRedirect = true,
+ MaxAutomaticRedirections = 10,
+ AutomaticDecompression = DecompressionMethods.None,
+ ConnectTimeout = TimeSpan.FromSeconds(120),
+ PreAuthenticate = false,
+ UseCookies = false,
+ MaxConnectionsPerServer = MaxConnectionsPerServer,
+ PooledConnectionIdleTimeout = TimeSpan.FromSeconds(31),
+ PooledConnectionLifetime = TimeSpan.FromMinutes(3)
+ };
+ //shh.SslOptions.ClientCertificates = null,
+ shh.SslOptions.EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
+ if (NoVerifyCertChain)
+ {
+ shh.SslOptions.CertificateRevocationCheckMode = X509RevocationMode.NoCheck;
+ if (NoVerifyCertHostname)
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ errors &= ~(SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch);
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ else
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ }
+ else
+ {
+ shh.SslOptions.CertificateRevocationCheckMode = X509RevocationMode.NoCheck;
+ if (NoVerifyCertHostname)
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ errors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ else
+ {
+ shh.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
+ {
+ return errors == SslPolicyErrors.None;
+ };
+ }
+ }
+
+ if (proxy is null)
+ shh.UseProxy = false;
+ else
+ {
+ shh.Proxy = proxy;
+ shh.UseProxy = true;
+ }
+ SharedSocketsHttpHandler = shh;
+ }
+
+ public static HttpClient GetNewGlobalHttpClient(int timeout)
+ {
+ var client = new HttpClient(SharedSocketsHttpHandler, false)
+ {
+ Timeout = TimeSpan.FromMilliseconds(timeout > 0 ? timeout : 30000),
+ MaxResponseContentBufferSize = 250 * 1024 * 1024,
+ };
+ client.DefaultRequestHeaders.ExpectContinue = false;
+ return client;
+ }
+
+ public static HttpClient GetGlobalNoRedirHttpClient(int timeout)
+ {
+ var client = new HttpClient(SharedSocketsHttpHandlerNoRedir, false)
+ {
+ Timeout = TimeSpan.FromMilliseconds(timeout > 0 ? timeout : 30000),
+ MaxResponseContentBufferSize = 250 * 1024 * 1024,
+ };
+ client.DefaultRequestHeaders.ExpectContinue = false;
+ return client;
+ }
+
///
/// PUT JSON-encoded data to a web service that returns LLSD or
/// JSON data
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url, data, "PUT", timeout, true, false);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OSDMap PutToService(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url, data, "PUT", timeout, false, false);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OSDMap PostToService(string url, OSDMap data, int timeout, bool rpc)
{
return ServiceOSDRequest(url, data, "POST", timeout, false, rpc);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url, data, "POST", timeout, true, false);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OSDMap GetFromService(string url, int timeout)
{
return ServiceOSDRequest(url, null, "GET", timeout, false, false);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LogOutgoingDetail(Stream outputStream)
{
LogOutgoingDetail("", outputStream);
@@ -144,50 +305,52 @@ public static void LogOutgoingDetail(Stream outputStream)
public static void LogOutgoingDetail(string context, Stream outputStream)
{
- using (Stream stream = Util.Copy(outputStream))
- using (StreamReader reader = new StreamReader(stream, 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, len);
- }
- else
- {
- output = reader.ReadToEnd();
- }
+ using Stream stream = Util.Copy(outputStream);
+ using StreamReader reader = new(stream, Encoding.UTF8);
+ string output;
- LogOutgoingDetail(context, output);
+ if (DebugLevel == 5)
+ {
+ 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);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LogOutgoingDetail(string type, int reqnum, string output)
{
- LogOutgoingDetail(string.Format("{0} {1}: ", type, reqnum), output);
+ LogOutgoingDetail($"{type} {reqnum}: ", output);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LogOutgoingDetail(string context, string output)
{
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)}");
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LogResponseDetail(int reqnum, Stream inputStream)
{
- LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), inputStream);
+ LogOutgoingDetail($"RESPONSE {reqnum}: ", inputStream);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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,36 +358,22 @@ public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, i
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 ticks = Util.EnvironmentTickCount();
+
int sendlen = 0;
int rcvlen = 0;
- HttpWebRequest request = null;
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
try
{
- request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = method;
- request.Timeout = timeout;
- request.KeepAlive = keepalive;
- request.MaximumAutomaticRedirections = 10;
- request.ReadWriteTimeout = timeout / 2;
- request.Headers[OSHeaderRequestID] = reqnum.ToString();
- request.AllowWriteStreamBuffering = false;
- }
- catch (Exception ex)
- {
- errorMessage = ex.Message;
- m_log.Debug("[WEB UTIL]: SvcOSD error creating request " + ex.Message);
- return ErrorResponseMap(errorMessage);
- }
+ client = GetNewGlobalHttpClient(timeout);
+ request = new(new HttpMethod(method), url);
- try
- {
- // If there is some input, write it into the request
- if (data != null)
+ if (data is not null)
{
byte[] buffer;
if (DebugLevel >= 5)
@@ -236,72 +385,83 @@ public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, i
else
buffer = OSDParser.SerializeJsonToBytes(data);
- request.ContentType = rpc ? "application/json-rpc" : "application/json";
-
- if (compressed)
+ if (buffer.Length > 0)
{
- 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())
+ if (compressed)
{
- using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true))
+ using MemoryStream ms = new();
+ using (GZipStream comp = new(ms, CompressionMode.Compress, true))
{
comp.Write(buffer, 0, buffer.Length);
- }
+ }
buffer = ms.ToArray();
+
+ request.Headers.TryAddWithoutValidation("X-Content-Encoding", "gzip"); // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding
}
+
+ sendlen = buffer.Length;
+ request.Content = new ByteArrayContent(buffer);
+ request.Content.Headers.TryAddWithoutValidation("Content-Type",
+ rpc ? "application/json-rpc" : "application/json");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", sendlen.ToString());
}
+ }
- sendlen = buffer.Length;
- request.ContentLength = buffer.Length; //Count bytes to send
- using (Stream requestStream = request.GetRequestStream())
- requestStream.Write(buffer, 0, buffer.Length); //Send it
- buffer = null;
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
+ if(keepalive)
+ {
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
}
+ else
+ request.Headers.TryAddWithoutValidation("Connection", "close");
+
+ request.Headers.TryAddWithoutValidation(OSHeaderRequestID, reqnum.ToString());
- using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+ responseMessage.EnsureSuccessStatusCode();
+
+ Stream resStream = responseMessage.Content.ReadAsStream();
+ if (resStream is not null)
{
- 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 StreamReader reader = new(resStream);
+ string responseStr = reader.ReadToEnd();
+ if (WebUtil.DebugLevel >= 5)
+ WebUtil.LogResponseDetail(reqnum, responseStr);
+ rcvlen = responseStr.Length;
+ return CanonicalizeResults(responseStr);
}
}
- catch (WebException we)
+ catch (HttpRequestException e)
{
- errorMessage = we.Message;
- if (we.Status == WebExceptionStatus.ProtocolError)
- {
- using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
- errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription);
- }
+ int Status = e.StatusCode is null ? 499 : (int)e.StatusCode;
+ errorMessage = $"[{Status}] {e.Message}";
}
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)
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
+
+ ticks = Util.EnvironmentTickCountSubtract(ticks);
+ if (ticks > 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 {ticks}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 {ticks}ms");
}
}
- m_log.DebugFormat("[LOGHTTP]: JSON request {0} {1} to {2} FAILED: {3}", reqnum, method, url, errorMessage);
+ m_log.Debug($"[LOGHTTP]: request {reqnum} {method} to {url} FAILED: {errorMessage}");
return ErrorResponseMap(errorMessage);
}
@@ -316,13 +476,14 @@ public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, i
///
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 +507,7 @@ private static OSDMap CanonicalizeResults(string response)
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;
@@ -360,6 +521,7 @@ private static OSDMap CanonicalizeResults(string response)
/// POST URL-encoded form data to a web service that returns LLSD or
/// JSON data
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OSDMap PostToService(string url, NameValueCollection data)
{
return ServiceFormRequest(url,data, 30000);
@@ -368,37 +530,40 @@ public static OSDMap PostToService(string url, NameValueCollection data)
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 ticks = Util.EnvironmentTickCount();
int sendlen = 0;
int rcvlen = 0;
- HttpWebRequest request = null;
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
try
{
- request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "POST";
- request.Timeout = timeout;
- request.KeepAlive = false;
- request.MaximumAutomaticRedirections = 10;
- request.ReadWriteTimeout = timeout / 2;
- request.Headers[OSHeaderRequestID] = reqnum.ToString();
- request.AllowWriteStreamBuffering = false;
- }
- catch (Exception ex)
- {
- return ErrorResponseMap(ex.Message);
- }
+ client = GetNewGlobalHttpClient(timeout);
- try
- {
- if (data != null)
+ request = new(HttpMethod.Post, url);
+
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
+
+ //if (keepalive)
+ //{
+ // request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ // request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ // request.Headers.ConnectionClose = false;
+ //}
+ //else
+ request.Headers.TryAddWithoutValidation("Connection", "close");
+
+ request.Headers.TryAddWithoutValidation(OSHeaderRequestID, reqnum.ToString());
+
+ if (data is not null)
{
string queryString = BuildQueryString(data);
@@ -408,37 +573,38 @@ public static OSDMap ServiceFormRequest(string url, NameValueCollection data, in
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString);
queryString = null;
- request.ContentLength = buffer.Length;
sendlen = buffer.Length;
- request.ContentType = "application/x-www-form-urlencoded";
- using (Stream requestStream = request.GetRequestStream())
- requestStream.Write(buffer, 0, buffer.Length);
- buffer = null;
- }
- using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
+ request.Content = new ByteArrayContent(buffer);
+ request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", sendlen.ToString()); buffer = null;
+ }
+ else
{
- 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);
-
- if (responseOSD.Type == OSDType.Map)
- return (OSDMap)responseOSD;
- }
+ request.Content = new ByteArrayContent(Array.Empty());
+ request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", "0");
}
+
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+ responseMessage.EnsureSuccessStatusCode();
+
+ using StreamReader reader = new(responseMessage.Content.ReadAsStream());
+ 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;
}
- catch (WebException we)
+ catch (HttpRequestException we)
{
- errorMessage = we.Message;
- if (we.Status == WebExceptionStatus.ProtocolError)
- {
- using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
- errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
- }
+ if (we.StatusCode is HttpStatusCode status)
+ errorMessage = $"[{status}] {we.Message}";
+ else
+ errorMessage = we.Message;
}
catch (Exception ex)
{
@@ -446,21 +612,23 @@ public static OSDMap ServiceFormRequest(string url, NameValueCollection data, in
}
finally
{
- int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
- if (tickdiff > LongCallTime)
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
+
+ ticks = Util.EnvironmentTickCountSubtract(ticks);
+ if (ticks > 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 {ticks}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 {ticks}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 +639,11 @@ public static OSDMap ServiceFormRequest(string url, NameValueCollection data, in
///
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 +667,10 @@ public static Uri Combine(this Uri uri, string fragment)
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 +692,10 @@ public static Uri Combine(this Uri uri, Uri fragment)
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 +711,18 @@ public static Uri Combine(this Uri uri, Uri fragment)
/// 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 +740,19 @@ public static string BuildQueryString(NameValueCollection parameters)
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 +772,7 @@ public static string BuildQueryString(NameValueCollection parameters)
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 +829,13 @@ public int Compare(Object x, Object y)
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 +861,29 @@ private float GetQ(Object o)
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 +893,7 @@ public static string[] GetPreferredImageTypes(string accept)
return result;
}
- return new string[0];
+ return Array.Empty();
}
}
@@ -738,12 +914,14 @@ public static class AsynchronousRestObjectRequester
/// network issue while posting the request. You'll want to make
/// sure you deal with this as they're not uncommon
//
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void MakeRequest(string verb,
string requestUrl, TRequest obj, Action action)
{
- MakeRequest(verb, requestUrl, obj, action, 0);
+ MakeRequest(verb, requestUrl, obj, action, 0, null);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void MakeRequest(string verb,
string requestUrl, TRequest obj, Action action,
int maxConnections)
@@ -758,7 +936,7 @@ public static void MakeRequest(string verb,
///
///
///
- /// Request timeout in seconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
+ /// Request timeout in seconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default timeout is used (100 seconds)
///
///
///
@@ -772,8 +950,7 @@ public static void MakeRequest(string verb,
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 +968,7 @@ public static void MakeRequest(string verb,
if (maxConnections > 0 && request.ServicePoint.ConnectionLimit < maxConnections)
request.ServicePoint.ConnectionLimit = maxConnections;
- TResponse deserial = default(TResponse);
+ TResponse deserial = default;
request.Method = verb;
@@ -802,12 +979,14 @@ public static void MakeRequest(string verb,
{
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 +1012,9 @@ public static void MakeRequest(string verb,
{
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 +1034,20 @@ public static void MakeRequest(string verb,
{
// 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 +1058,30 @@ public static void MakeRequest(string verb,
{
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 +1089,7 @@ public static void MakeRequest(string verb,
}
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 +1114,7 @@ public static void MakeRequest(string verb,
}
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 { }
@@ -956,7 +1128,7 @@ public static class SynchronousRestFormsRequester
///
/// Perform a synchronous REST request.
///
- ///
+ ///
///
///
///
@@ -964,91 +1136,86 @@ public static class SynchronousRestFormsRequester
///
/// Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon
- public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs = -1,
+ public static string MakeRequest(string method, string requestUrl, string obj, int timeoutsecs = -1,
IServiceAuth auth = null, bool keepalive = true)
{
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 {method} to {requestUrl}");
- int tickstart = Util.EnvironmentTickCount();
-
- HttpWebRequest request = null;
+ int ticks = Util.EnvironmentTickCount();
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
+ string respstring = String.Empty;
+ int sendlen = 0;
+ int rcvlen = 0;
try
{
- request = (HttpWebRequest)WebRequest.Create(requestUrl);
- request.Method = verb;
- if (timeoutsecs > 0)
- request.Timeout = timeoutsecs * 1000;
- if(!keepalive)
- request.KeepAlive = false;
- if (auth != null)
- auth.AddAuthorization(request.Headers);
-
- request.AllowWriteStreamBuffering = false;
- request.ContentType = "application/x-www-form-urlencoded";
- }
- catch (Exception e)
- {
- m_log.InfoFormat("[FORMS]: Error creating {0} request to : {1}. Request: {2}", verb, requestUrl, e.Message);
- throw;
- }
+ client = WebUtil.GetNewGlobalHttpClient(timeoutsecs * 1000);
- int sendlen = 0;
- if (obj.Length > 0 && (verb == "POST") || (verb == "PUT"))
- {
- byte[] data = Util.UTF8NBGetbytes(obj);
- sendlen = data.Length;
- request.ContentLength = sendlen;
+ request = new(new HttpMethod(method), requestUrl);
- if (WebUtil.DebugLevel >= 5)
- WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
+ auth?.AddAuthorization(request.Headers);
- try
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false; if (timeoutsecs > 0)
+
+ if (keepalive)
{
- using(Stream requestStream = request.GetRequestStream())
- requestStream.Write(data, 0, sendlen);
- data = null;
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
}
- catch (Exception e)
+ else
+ request.Headers.TryAddWithoutValidation("Connection", "close");
+
+ if (obj.Length > 0 &&
+ (method.Equals("POST", StringComparison.OrdinalIgnoreCase) ||
+ method.Equals("PUT", StringComparison.OrdinalIgnoreCase)))
{
- m_log.InfoFormat("[FORMS]: Error sending {0} request to: {1}. {2}", verb,requestUrl, e.Message);
- throw;
+ byte[] data = Util.UTF8NBGetbytes(obj);
+ sendlen = data.Length;
+
+ if (WebUtil.DebugLevel >= 5)
+ WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
+
+ request.Content = new ByteArrayContent(data);
+ request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", sendlen.ToString());
}
- }
- int rcvlen = 0;
- string respstring = String.Empty;
- try
- {
- using (WebResponse resp = request.GetResponse())
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+ responseMessage.EnsureSuccessStatusCode();
+
+ if ((responseMessage.Content.Headers.ContentLength is long contentLength) && contentLength != 0)
{
- if (resp.ContentLength != 0)
- {
- using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
- respstring = reader.ReadToEnd();
- rcvlen = respstring.Length;
- }
+ using StreamReader reader = new(responseMessage.Content.ReadAsStream());
+ 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;
}
+ finally
+ {
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
+ }
- int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
- if (tickdiff > WebUtil.LongCallTime)
+ ticks = Util.EnvironmentTickCountSubtract(ticks);
+ if (ticks > 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} {method} {requestUrl} took {ticks}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 {ticks}ms");
if (WebUtil.DebugLevel >= 5)
WebUtil.LogResponseDetail(reqnum, respstring);
}
@@ -1056,7 +1223,7 @@ public static string MakeRequest(string verb, string requestUrl, string obj, int
return respstring;
}
-
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string MakeRequest(string verb, string requestUrl, string obj, IServiceAuth auth)
{
return MakeRequest(verb, requestUrl, obj, -1, auth);
@@ -1068,80 +1235,71 @@ public static string MakePostRequest(string requestUrl, string obj,
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
- m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms POST to {1}",
- reqnum, requestUrl);
-
- int tickstart = Util.EnvironmentTickCount();
+ m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SynchronousRestForms POST to {requestUrl}");
- HttpWebRequest request = null;
+ int ticks = Util.EnvironmentTickCount();
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
+ string respstring = String.Empty;
+ int sendlen = 0;
+ int rcvlen = 0;
try
{
- request = (HttpWebRequest)WebRequest.Create(requestUrl);
- request.Method = "POST";
- if (timeoutsecs > 0)
- request.Timeout = timeoutsecs * 1000;
- if (!keepalive)
- request.KeepAlive = false;
- if (auth != null)
- auth.AddAuthorization(request.Headers);
-
- request.AllowWriteStreamBuffering = false;
- request.ContentType = "application/x-www-form-urlencoded";
- }
- catch (Exception e)
- {
- m_log.InfoFormat("[FORMS]: Error creating POST request to {0}: {1}", requestUrl, e.Message);
- throw;
- }
+ client = WebUtil.GetNewGlobalHttpClient(timeoutsecs * 1000);
+ request = new(HttpMethod.Post, requestUrl);
- byte[] data = Util.UTF8NBGetbytes(obj);
- int sendlen = data.Length;
- request.ContentLength = sendlen;
+ auth?.AddAuthorization(request.Headers);
- if (WebUtil.DebugLevel >= 5)
- WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
- try
- {
- using (Stream requestStream = request.GetRequestStream())
- requestStream.Write(data, 0, sendlen);
- data = null;
- }
- catch (Exception e)
- {
- m_log.InfoFormat("[FORMS]: Error sending POST request to {0}: {1}", requestUrl, e.Message);
- throw;
- }
+ if (keepalive)
+ {
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
+ }
+ else
+ request.Headers.TryAddWithoutValidation("Connection", "close");
- string respstring = String.Empty;
- int rcvlen = 0;
- try
- {
- using (WebResponse resp = request.GetResponse())
+ byte[] data = Util.UTF8NBGetbytes(obj);
+ sendlen = data.Length;
+ request.Content = new ByteArrayContent(data);
+ request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", sendlen.ToString());
+
+ if (WebUtil.DebugLevel >= 5)
+ WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
+
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+
+ if ((responseMessage.Content.Headers.ContentLength is long contentLength) && contentLength != 0)
{
- if (resp.ContentLength != 0)
- {
- using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
- respstring = reader.ReadToEnd();
- }
+ using StreamReader reader = new(responseMessage.Content.ReadAsStream());
+ 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;
}
+ finally
+ {
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
+ }
- int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
- if (tickdiff > WebUtil.LongCallTime)
+ ticks = Util.EnvironmentTickCountSubtract(ticks);
+ if (ticks > 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 {ticks}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 {ticks}ms");
if (WebUtil.DebugLevel >= 5)
WebUtil.LogResponseDetail(reqnum, respstring);
}
@@ -1163,11 +1321,13 @@ public class SynchronousRestObjectRequester
///
/// The response. If there was an internal exception, then the default(TResponse) is returned.
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TResponse MakeRequest(string verb, string requestUrl, TRequest obj)
{
return MakeRequest(verb, requestUrl, obj, 0, null);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TResponse MakeRequest(string verb, string requestUrl, TRequest obj, IServiceAuth auth)
{
return MakeRequest(verb, requestUrl, obj, 0, auth);
@@ -1179,12 +1339,13 @@ public static TResponse MakeRequest(string verb, string req
///
///
///
- /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
+ /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default timeout is used (100 seconds)
///
///
/// The response. If there was an internal exception or the request timed out,
/// then the default(TResponse) is returned.
///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TResponse MakeRequest(string verb, string requestUrl, TRequest obj, int pTimeout)
{
return MakeRequest(verb, requestUrl, obj, pTimeout, null);
@@ -1193,151 +1354,131 @@ public static TResponse MakeRequest(string verb, string req
///
/// Perform a synchronous something request.
///
- ///
+ ///
///
///
///
- /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
+ /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default timeout is used (100 seconds)
///
///
/// The response. If there was an internal exception or the request timed out,
/// then the default(TResponse) is returned.
///
- public static TResponse MakeRequest(string verb, string requestUrl, TRequest obj, int pTimeout, IServiceAuth auth)
+ public static TResponse MakeRequest(string method, string requestUrl, TRequest obj, int pTimeout, IServiceAuth auth)
{
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
- m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SRestObjReq {1} {2}",
- reqnum, verb, requestUrl);
-
- int tickstart = Util.EnvironmentTickCount();
+ m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SRestObjReq {method} {requestUrl}");
- TResponse deserial = default(TResponse);
+ int ticks = Util.EnvironmentTickCount();
+ TResponse deserial = default;
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
- HttpWebRequest request = null;
try
{
- request = (HttpWebRequest)WebRequest.Create(requestUrl);
+ client = WebUtil.GetNewGlobalHttpClient(pTimeout);
- if (auth != null)
- auth.AddAuthorization(request.Headers);
+ request = new(new HttpMethod(method), requestUrl);
- if (pTimeout != 0)
- request.Timeout = pTimeout;
+ auth?.AddAuthorization(request.Headers);
- request.Method = verb;
- }
- catch (Exception e)
- {
- m_log.DebugFormat("[SRestObjReq]: Exception in creating request {0} {1}: {2}{3}",
- verb, requestUrl, e.Message, e.StackTrace);
- return deserial;
- }
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
- try
- {
- if ((verb == "POST") || (verb == "PUT"))
+ //if (keepalive)
{
- request.ContentType = "text/xml";
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
+ }
+ //else
+ // request.Headers.TryAddWithoutValidation("Connection", "close");
+ if (method.Equals("POST",StringComparison.OrdinalIgnoreCase) || method.Equals("PUT", StringComparison.OrdinalIgnoreCase))
+ {
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();
}
int sendlen = data.Length;
- request.ContentLength = sendlen;
-
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
- using (Stream requestStream = request.GetRequestStream())
- requestStream.Write(data, 0, sendlen);
- data = null;
+ request.Content = new ByteArrayContent(data);
+ request.Content.Headers.TryAddWithoutValidation("Content-Type", "text/xml");
+ request.Content.Headers.TryAddWithoutValidation("Content-Length", sendlen.ToString());
}
- }
- catch (Exception e)
- {
- m_log.DebugFormat(
- "[SRestObjReq]: Exception in making request {0} {1}: {2}{3}",
- verb, requestUrl, e.Message, e.StackTrace);
- return deserial;
- }
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+ responseMessage.EnsureSuccessStatusCode();
- int rcvlen = 0;
- try
- {
- using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
+ int rcvlen = 0;
+ if ((responseMessage.Content.Headers.ContentLength is long contentLength) && 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)contentLength;
+ using Stream respStream = responseMessage.Content.ReadAsStream();
+ deserial = XMLResponseHelper.LogAndDeserialize(
+ reqnum, respStream, contentLength);
+ }
+ else
+ {
+ m_log.Debug($"[SRestObjReq]: Oops! no content found in response stream from {method} {requestUrl}");
+ }
+
+ ticks = Util.EnvironmentTickCountSubtract(ticks);
+ if (ticks > WebUtil.LongCallTime)
+ {
+ m_log.Info($"[LOGHTTP]: Slow SRestObjReq {reqnum} {method} {requestUrl} took {ticks}ms, {rcvlen}bytes");
+ }
+ else if (WebUtil.DebugLevel >= 4)
+ {
+ m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {ticks}ms");
}
}
- catch (WebException e)
+ catch (HttpRequestException e)
{
- using (HttpWebResponse hwr = (HttpWebResponse)e.Response)
+ if (e.StatusCode is HttpStatusCode status)
{
- if (hwr != null)
+ if (status == 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]: GET {requestUrl} requires authentication");
+ }
+ else if (status != HttpStatusCode.NotFound)
+ {
+ m_log.Warn($"[SRestObjReq]: GET {requestUrl} returned error: {status}");
}
- 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}",
+ method, 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 {method} {requestUrl} {typeof(TResponse)}");
}
catch (Exception e)
{
- m_log.DebugFormat("[SRestObjReq]: Exception on response from {0} {1}: {2}",
- 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.Debug($"[SRestObjReq]: Exception on response from {method} {requestUrl}: {e.Message}");
}
- else if (WebUtil.DebugLevel >= 4)
+ finally
{
- m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff);
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
}
+
return deserial;
}
@@ -1346,98 +1487,88 @@ public static TResponse MakeGetRequest(string requestUrl, int pTimeou
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
- m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SRestObjReq GET {1}", reqnum, requestUrl);
- int tickstart = Util.EnvironmentTickCount();
+ m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} SRestObjReq GET {requestUrl}");
- TResponse deserial = default(TResponse);
- HttpWebRequest request = null;
+ int ticks = Util.EnvironmentTickCount();
+ TResponse deserial = default;
+ HttpResponseMessage responseMessage = null;
+ HttpRequestMessage request = null;
+ HttpClient client = null;
try
{
- request = (HttpWebRequest)WebRequest.Create(requestUrl);
+ client = WebUtil.GetNewGlobalHttpClient(pTimeout);
+ request = new(HttpMethod.Get, requestUrl);
- if (auth != null)
- auth.AddAuthorization(request.Headers);
+ auth?.AddAuthorization(request.Headers);
- request.AllowWriteStreamBuffering = false;
+ request.Headers.ExpectContinue = false;
+ request.Headers.TransferEncodingChunked = false;
- if (pTimeout != 0)
- request.Timeout = pTimeout;
+ //if (keepalive)
+ {
+ request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
+ request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
+ request.Headers.ConnectionClose = false;
+ }
+ //else
+ // request.Headers.TryAddWithoutValidation("Connection", "close");
- request.Method = "GET";
- }
- catch (Exception e)
- {
- m_log.DebugFormat("[SRestObjReq]: Exception in creating GET request {0}: {1}{2}",
- requestUrl, e.Message, e.StackTrace);
- return deserial;
- }
+ responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
+ responseMessage.EnsureSuccessStatusCode();
- int rcvlen = 0;
- try
- {
- using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
+ int rcvlen = 0;
+ if ((responseMessage.Content.Headers.ContentLength is long contentLength) && 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)contentLength;
+ using Stream respStream = responseMessage.Content.ReadAsStream();
+ deserial = XMLResponseHelper.LogAndDeserialize(
+ reqnum, respStream, contentLength);
+ }
+ else
+ {
+ m_log.Debug($"[SRestObjReq]: Oops! no content found in response stream from GET {requestUrl}");
+ }
+
+ ticks = Util.EnvironmentTickCountSubtract(ticks);
+ if (ticks > WebUtil.LongCallTime)
+ {
+ m_log.Info($"[LOGHTTP]: Slow SRestObjReq GET {reqnum} {requestUrl} took {ticks}ms, {rcvlen}bytes");
+ }
+ else if (WebUtil.DebugLevel >= 4)
+ {
+ m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} took {ticks}ms");
}
}
- catch (WebException e)
+ catch (HttpRequestException e)
{
- using (HttpWebResponse hwr = (HttpWebResponse)e.Response)
+ if(e.StatusCode is HttpStatusCode status)
{
- if (hwr != null)
+ if (status == 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 (status != HttpStatusCode.NotFound)
+ {
+ m_log.Warn($"[SRestObjReq]: GET {requestUrl} returned error: {status}");
}
- 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);
- }
-
- 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.Debug($"[SRestObjReq]: Exception on response from GET {requestUrl}: {e.Message}");
}
- else if (WebUtil.DebugLevel >= 4)
+ finally
{
- m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms",
- reqnum, tickdiff);
+ request?.Dispose();
+ responseMessage?.Dispose();
+ client?.Dispose();
}
return deserial;
}
@@ -1447,43 +1578,41 @@ public static class XMLResponseHelper
{
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
+ }
+ else
+ {
+ int remaining = (int)contentLength;
+ while (remaining > 0)
{
- 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;
- }
+ 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));
+ dataBuffer = ms.ToArray();
+ WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(dataBuffer));
- ms.Position = 0;
- return (TResponse)deserializer.Deserialize(ms);
- }
+ ms.Position = 0;
+ return (TResponse)deserializer.Deserialize(ms);
}
else
{
@@ -1501,18 +1630,19 @@ public static Hashtable SendRequest(Hashtable ReqParams, string method, string u
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;
-
+ HttpClient client = 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)
{
@@ -1521,7 +1651,8 @@ public static Hashtable SendRequest(Hashtable ReqParams, string method, string u
WebUtil.LogOutgoingDetail("SEND", reqnum, str);
}
- XmlRpcResponse Resp = Req.Send(url, 30000);
+ client = WebUtil.GetNewGlobalHttpClient(-1);
+ XmlRpcResponse Resp = Req.Send(url, client);
try
{
@@ -1534,14 +1665,13 @@ public static Hashtable SendRequest(Hashtable ReqParams, string method, string u
}
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;
}
@@ -1550,6 +1680,8 @@ public static Hashtable SendRequest(Hashtable ReqParams, string method, string u
}
finally
{
+ client?.Dispose();
+
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
if (tickdiff > WebUtil.LongCallTime)
{
@@ -1562,7 +1694,7 @@ public static Hashtable SendRequest(Hashtable ReqParams, string method, string u
}
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/Application/Application.cs b/OpenSim/Region/Application/Application.cs
index 14fe7c0f5a4..cb46b02b6d8 100644
--- a/OpenSim/Region/Application/Application.cs
+++ b/OpenSim/Region/Application/Application.cs
@@ -73,6 +73,8 @@ public static void Main(string[] args)
// First line, hook the appdomain to the crash reporter
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
+ System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);
+
Culture.SetCurrentCulture();
Culture.SetDefaultCurrentCulture();
@@ -89,7 +91,7 @@ public static void Main(string[] args)
// Configure Log4Net
configSource.AddSwitch("Startup", "logconfig");
string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
- if (logConfigFile != String.Empty)
+ if (!string.IsNullOrEmpty(logConfigFile))
{
XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file",
@@ -97,10 +99,32 @@ public static void Main(string[] args)
}
else
{
- XmlConfigurator.Configure();
+ XmlConfigurator.Configure(new System.IO.FileInfo("OpenSim.exe.config"));
m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config");
}
+ // temporay set the platform dependent System.Drawing.Common.dll
+ string targetdll = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
+ "System.Drawing.Common.dll");
+ string src = targetdll + (Util.IsWindows() ? ".win" : ".linux");
+ try
+ {
+ if (!File.Exists(targetdll))
+ File.Copy(src, targetdll);
+ else
+ {
+ FileInfo targetInfo = new(targetdll);
+ FileInfo srcInfo = new(src);
+ if(targetInfo.Length != srcInfo.Length)
+ File.Copy(src, targetdll, true);
+ }
+ }
+ catch (Exception e)
+ {
+ m_log.Error("Failed to copy System.Drawing.Common.dll for current platform" + e.Message);
+ throw;
+ }
+
m_log.InfoFormat(
"[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture);
if(!Util.IsWindows())
diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs
index ec26355b017..5f9573bb8b7 100755
--- a/OpenSim/Region/Application/OpenSim.cs
+++ b/OpenSim/Region/Application/OpenSim.cs
@@ -185,9 +185,9 @@ protected override void StartupSpecific()
MainServer.Instance.AddSimpleStreamHandler(new SimRobotsHandler());
MainServer.Instance.AddSimpleStreamHandler(new IndexPHPHandler(MainServer.Instance));
- if (managedStatsURI != String.Empty)
+ if (!string.IsNullOrEmpty(managedStatsURI))
{
- string urlBase = String.Format("/{0}/", managedStatsURI);
+ string urlBase = $"/{managedStatsURI}/";
StatsManager.StatsPassword = managedStatsPassword;
MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest);
m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase);
@@ -316,7 +316,7 @@ private void RegisterConsoleCommands()
+ "1: Rotation (around the incoming OARs region center)\n"
+ "2: Cropping (a bounding cube with origin and size)\n"
+ "3: Displacement (setting offset coordinates within the destination region)",
- LoadOar); ;
+ LoadOar);
m_console.Commands.AddCommand("Archiving", false, "save oar",
//"save oar [-v|--version=] [-p|--profile=] []",
@@ -614,7 +614,7 @@ private void HandleRotateScene(string module, string[] args)
return;
}
- float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI);
+ float angle = Convert.ToSingle(args[2]) / 180.0f * MathF.PI;
OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle);
if (args.Length > 4)
diff --git a/OpenSim/Region/Application/OpenSim.csproj b/OpenSim/Region/Application/OpenSim.csproj
index ff2bce30e78..49ff4b1d754 100644
--- a/OpenSim/Region/Application/OpenSim.csproj
+++ b/OpenSim/Region/Application/OpenSim.csproj
@@ -1,6 +1,6 @@
- net48
+ net8.0
Exe
OpenSim
http://opensimulator.org
@@ -62,6 +62,7 @@
-
+
+
\ No newline at end of file
diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs
index 104aa9ff135..e18419a9336 100755
--- a/OpenSim/Region/Application/OpenSimBase.cs
+++ b/OpenSim/Region/Application/OpenSimBase.cs
@@ -40,7 +40,7 @@
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Monitoring;
-using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
+//using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
diff --git a/OpenSim/Region/Application/runtimeconfig.template.json b/OpenSim/Region/Application/runtimeconfig.template.json
new file mode 100644
index 00000000000..772fa6058fd
--- /dev/null
+++ b/OpenSim/Region/Application/runtimeconfig.template.json
@@ -0,0 +1,11 @@
+{
+ "configProperties": {
+ "System.GC.Server": false,
+ "System.GC.HighMemoryPercent": 50,
+ "System.Drawing.EnableUnixSupport": true,
+ "System.Globalization.UseNls": true,
+ "System.Reflection.Metadata.MetadataUpdater.IsSupported": false,
+ "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": true,
+ "System.Runtime.TieredCompilation.QuickJit": false
+ }
+}
\ No newline at end of file
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
index 0c193a1bac4..516ea00ae3f 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
@@ -34,9 +34,7 @@
using System.Net;
using System.Threading;
using System.Reflection;
-using System.Security.Cryptography;
using System.Text;
-using System.Web;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
@@ -45,11 +43,9 @@
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
-using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
-using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
@@ -85,14 +81,14 @@ public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UU
public partial class BunchOfCaps
{
- private static readonly ILog m_log =
- LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+ private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_Scene;
private UUID m_AgentID;
private UUID m_scopeID;
private Caps m_HostCapsObj;
private ModelCost m_ModelCost;
+ private BunchOfCapsConfigOptions ConfigOptions;
// private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
@@ -103,30 +99,11 @@ public partial class BunchOfCaps
public ItemUpdatedCallback ItemUpdatedCall = null;
public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
public GetClientDelegate GetClient = null;
-
- private bool m_persistBakedTextures = false;
+
private IAssetService m_assetService;
private bool m_dumpAssetsToFile = false;
private string m_regionName;
- private int m_levelUpload = 0;
-
- private bool m_enableFreeTestUpload = false; // allows "TEST-" prefix hack
- private bool m_ForceFreeTestUpload = false; // forces all uploads to be test
-
- private bool m_enableModelUploadTextureToInventory = true; // place uploaded textures also in inventory
- // may not be visible till relog
-
- private bool m_RestrictFreeTestUploadPerms = false; // reduces also the permitions. Needs a creator defined!!
- private UUID m_testAssetsCreatorID = UUID.Zero;
-
- private float m_PrimScaleMin = 0.001f;
-
- private bool m_AllowCapHomeLocation = true;
- private bool m_AllowCapGroupMemberData = true;
- private bool m_AllowCapLandResources = true;
- private bool m_AllowCapAttachmentResources = true;
-
private IUserManagement m_UserManager;
private IUserAccountService m_userAccountService;
private IMoneyModule m_moneyModule;
@@ -140,89 +117,26 @@ private enum FileAgentInventoryState : int
}
private FileAgentInventoryState m_FileAgentInventoryState = FileAgentInventoryState.idle;
- public BunchOfCaps(Scene scene, UUID agentID, Caps caps)
+ public BunchOfCaps(Scene scene, UUID agentID, Caps caps, BunchOfCapsConfigOptions configOptions)
{
m_Scene = scene;
m_AgentID = agentID;
m_HostCapsObj = caps;
+ ConfigOptions = configOptions;
- // create a model upload cost provider
- m_ModelCost = new ModelCost(scene);
-
- m_PrimScaleMin = m_ModelCost.PrimScaleMin;
-
- IConfigSource config = m_Scene.Config;
- if (config != null)
- {
- IConfig sconfig = config.Configs["Startup"];
- if (sconfig != null)
- {
- m_levelUpload = sconfig.GetInt("LevelUpload", 0);
- }
- if (m_levelUpload == 0)
- {
- IConfig pconfig = config.Configs["Permissions"];
- if (pconfig != null)
- {
- m_levelUpload = pconfig.GetInt("LevelUpload", 0);
- }
- }
-
- IConfig appearanceConfig = config.Configs["Appearance"];
- if (appearanceConfig != null)
- {
- m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
- }
- // economy for model upload
- IConfig EconomyConfig = config.Configs["Economy"];
- if (EconomyConfig != null)
- {
- m_ModelCost.Econfig(EconomyConfig);
-
- m_enableModelUploadTextureToInventory = EconomyConfig.GetBoolean("MeshModelAllowTextureToInventory", m_enableModelUploadTextureToInventory);
-
- m_RestrictFreeTestUploadPerms = EconomyConfig.GetBoolean("m_RestrictFreeTestUploadPerms", m_RestrictFreeTestUploadPerms);
- m_enableFreeTestUpload = EconomyConfig.GetBoolean("AllowFreeTestUpload", m_enableFreeTestUpload);
- m_ForceFreeTestUpload = EconomyConfig.GetBoolean("ForceFreeTestUpload", m_ForceFreeTestUpload);
- string testcreator = EconomyConfig.GetString("TestAssetsCreatorID", "");
- if (!string.IsNullOrEmpty(testcreator))
- {
- if (UUID.TryParse(testcreator, out UUID id))
- m_testAssetsCreatorID = id;
- }
- }
-
- IConfig CapsConfig = config.Configs["ClientStack.LindenCaps"];
- if (CapsConfig != null)
- {
- string homeLocationUrl = CapsConfig.GetString("Cap_HomeLocation", "localhost");
- if(homeLocationUrl.Length == 0)
- m_AllowCapHomeLocation = false;
-
- string GroupMemberDataUrl = CapsConfig.GetString("Cap_GroupMemberData", "localhost");
- if(GroupMemberDataUrl.Length == 0)
- m_AllowCapGroupMemberData = false;
-
- string LandResourcesUrl = CapsConfig.GetString("Cap_LandResources", "localhost");
- if (LandResourcesUrl.Length == 0)
- m_AllowCapLandResources = false;
-
- string AttachmentResourcesUrl = CapsConfig.GetString("Cap_AttachmentResources", "localhost");
- if (AttachmentResourcesUrl.Length == 0)
- m_AllowCapAttachmentResources = false;
- }
- }
+ //cache model upload cost provider
+ m_ModelCost = configOptions.ModelCost;
m_assetService = m_Scene.AssetService;
m_regionName = m_Scene.RegionInfo.RegionName;
m_UserManager = m_Scene.RequestModuleInterface();
m_userAccountService = m_Scene.RequestModuleInterface();
m_moneyModule = m_Scene.RequestModuleInterface();
- if (m_UserManager == null)
+ if (m_UserManager is null)
m_log.Error("[CAPS]: GetDisplayNames disabled because user management component not found");
- UserAccount account = m_userAccountService.GetUserAccount(m_Scene.RegionInfo.ScopeID, m_AgentID);
- if (account == null) // Hypergrid?
+ UserAccount account = m_userAccountService?.GetUserAccount(m_Scene.RegionInfo.ScopeID, m_AgentID);
+ if (account is null) // Hypergrid?
m_scopeID = m_Scene.RegionInfo.ScopeID;
else
m_scopeID = account.ScopeID;
@@ -272,33 +186,36 @@ public void RegisterRegionServiceHandlers()
m_HostCapsObj.RegisterSimpleHandler("ResourceCostSelected",
new SimpleOSDMapHandler("POST", GetNewCapPath(), ResourceCostSelected));
- if(m_AllowCapHomeLocation)
+ if(ConfigOptions.AllowCapHomeLocation)
{
m_HostCapsObj.RegisterSimpleHandler("HomeLocation",
new SimpleStreamHandler(GetNewCapPath(), HomeLocation));
}
- if (m_AllowCapGroupMemberData)
+ if (ConfigOptions.AllowCapGroupMemberData)
{
m_HostCapsObj.RegisterSimpleHandler("GroupMemberData",
new SimpleStreamHandler(GetNewCapPath(), GroupMemberData));
}
- if (m_AllowCapLandResources)
+ if (ConfigOptions.AllowCapLandResources)
{
m_HostCapsObj.RegisterSimpleHandler("LandResources",
new SimpleOSDMapHandler("POST", GetNewCapPath(), LandResources));
}
- if (m_AllowCapAttachmentResources)
+ if (ConfigOptions.AllowCapAttachmentResources)
{
m_HostCapsObj.RegisterSimpleHandler("AttachmentResources",
new SimpleStreamHandler(GetNewCapPath(), AttachmentResources));
}
+
+ m_HostCapsObj.RegisterSimpleHandler("DispatchRegionInfo",
+ new SimpleOSDMapHandler("POST", GetNewCapPath(), DispatchRegionInfo), true);
}
catch (Exception e)
{
- m_log.Error("[CAPS]: " + e.ToString());
+ m_log.Error("[CAPS]: Error " + e.Message);
}
}
@@ -311,7 +228,7 @@ public void RegisterInventoryServiceHandlers()
"POST", GetNewCapPath(), NewAgentInventoryRequest, "NewFileAgentInventory", null));
SimpleOSDMapHandler oreq;
- if (ItemUpdatedCall != null)
+ if (ItemUpdatedCall is not null)
{
// first sets the http handler, others only register the cap, using it
oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateNotecardItemAsset);
@@ -339,7 +256,7 @@ public void RegisterInventoryServiceHandlers()
m_HostCapsObj.RegisterSimpleHandler("UpdateGestureTaskInventory", oreq, false);
}
- if (TaskScriptUpdatedCall != null)
+ if (TaskScriptUpdatedCall is not null)
{
oreq = new SimpleOSDMapHandler("POST", GetNewCapPath(), UpdateScriptTaskInventory);
m_HostCapsObj.RegisterSimpleHandler("UpdateScriptTask", oreq, true);
@@ -365,7 +282,7 @@ public void RegisterOtherHandlers()
{
try
{
- if (m_UserManager != null)
+ if (m_UserManager is not null)
{
m_HostCapsObj.RegisterSimpleHandler("GetDisplayNames",
new SimpleStreamHandler(GetNewCapPath(), GetDisplayNames));
@@ -373,7 +290,7 @@ public void RegisterOtherHandlers()
}
catch (Exception e)
{
- m_log.Error("[CAPS]: " + e.ToString());
+ m_log.Error("[CAPS]: Error " + e.Message);
}
}
///
@@ -387,9 +304,8 @@ public void RegisterOtherHandlers()
///
public void SeedCapRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
- UUID agentID = m_HostCapsObj.AgentID;
- m_log.DebugFormat(
- "[CAPS]: Received SEED caps request in {0} for agent {1}", m_regionName, agentID);
+ m_log.Debug(
+ $"[CAPS]: Received SEED caps request in {m_regionName} for agent {m_HostCapsObj.AgentID}");
if(httpRequest.HttpMethod != "POST" || httpRequest.ContentType != "application/llsd+xml")
{
@@ -404,11 +320,10 @@ public void SeedCapRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpRespo
return;
}
- if (!m_Scene.CheckClient(agentID, httpRequest.RemoteIPEndPoint))
+ if (!m_Scene.CheckClient(m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint))
{
m_log.WarnFormat(
- "[CAPS]: Unauthorized CAPS client {0} from {1}",
- agentID, httpRequest.RemoteIPEndPoint);
+ $"[CAPS]: Unauthorized CAPS client {m_HostCapsObj.AgentID} from {httpRequest.RemoteIPEndPoint}");
httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
@@ -424,24 +339,45 @@ public void SeedCapRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpRespo
return;
}
- List validCaps = new List();
+ HashSet validCaps = new();
foreach (OSD c in capsRequested)
{
string cstr = c.AsString();
- if (cstr.Equals("ObjectAnimation"))
- m_HostCapsObj.Flags |= Caps.CapsFlags.ObjectAnim;
- else if (cstr.Equals("EnvironmentSettings"))
- m_HostCapsObj.Flags |= Caps.CapsFlags.WLEnv;
- else if (cstr.Equals("ExtEnvironment"))
- m_HostCapsObj.Flags |= Caps.CapsFlags.AdvEnv;
+ if (string.IsNullOrEmpty(cstr))
+ continue;
+ switch (cstr)
+ {
+ case "SEED":
+ continue;
+ case "ViewerBenefits": // this may need a proper cap but not currently
+ m_HostCapsObj.Flags |= Caps.CapsFlags.ViewerBenefits;
+ continue;
+ case "ObjectAnimation":
+ m_HostCapsObj.Flags |= Caps.CapsFlags.ObjectAnim;
+ break;
+ case "EnvironmentSettings":
+ m_HostCapsObj.Flags |= Caps.CapsFlags.WLEnv;
+ break;
+ case "ExtEnvironment":
+ m_HostCapsObj.Flags |= Caps.CapsFlags.AdvEnv;
+ break;
+ case "ModifyMaterialParams": // will not work if a viewer has no edit features
+ m_HostCapsObj.Flags |= Caps.CapsFlags.PBR;
+ break;
+ default:
+ break;
+ }
validCaps.Add(cstr);
}
+
+ osUTF8 sb = LLSDxmlEncode2.Start();
+ LLSDxmlEncode2.AddMap(sb);
+ m_HostCapsObj.GetCapsDetailsLLSDxml(validCaps, sb);
+ LLSDxmlEncode2.AddEndMap(sb);
- string result = LLSDHelpers.SerialiseLLSDReply(m_HostCapsObj.GetCapsDetails(true, validCaps));
- httpResponse.RawBuffer = Util.UTF8NBGetbytes(result);
+ httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
httpResponse.StatusCode = (int)HttpStatusCode.OK;
- //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
m_HostCapsObj.Flags |= Caps.CapsFlags.SentSeeds;
}
@@ -508,9 +444,9 @@ public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest l
m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
// check user level
- if (avatar != null)
+ if (avatar is not null)
{
- if (avatar.GodController.UserLevel < m_levelUpload)
+ if (avatar.GodController.UserLevel < ConfigOptions.levelUpload)
{
LLSDAssetUploadError resperror = new LLSDAssetUploadError();
resperror.message = "Insufficient permissions to upload";
@@ -527,12 +463,12 @@ public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest l
}
// check test upload and funds
- if (client != null)
+ if (client is not null)
{
IMoneyModule mm = m_Scene.RequestModuleInterface();
int baseCost = 0;
- if (mm != null)
+ if (mm is not null)
baseCost = mm.UploadCharge;
string warning = String.Empty;
@@ -569,7 +505,7 @@ public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest l
{
// check for test upload
- if (m_ForceFreeTestUpload) // all are test
+ if (ConfigOptions.ForceFreeTestUpload) // all are test
{
if (!(assetName.Length > 5 && assetName.StartsWith("TEST-"))) // has normal name lets change it
assetName = "TEST-" + assetName;
@@ -577,7 +513,7 @@ public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest l
IsAtestUpload = true;
}
- else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
+ else if (ConfigOptions.enableFreeTestUpload) // only if prefixed with "TEST-"
{
IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
@@ -605,7 +541,7 @@ public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest l
}
}
}
- else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
+ else if (ConfigOptions.enableFreeTestUpload) // only if prefixed with "TEST-"
{
IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
if(IsAtestUpload)
@@ -624,7 +560,7 @@ public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest l
string uploaderPath = GetNewCapPath();
UUID texturesFolder = UUID.Zero;
- if(!IsAtestUpload && m_enableModelUploadTextureToInventory)
+ if(!IsAtestUpload && ConfigOptions.enableModelUploadTextureToInventory)
texturesFolder = llsdRequest.texture_folder_id;
AssetUploader uploader =
@@ -693,12 +629,12 @@ public void UploadCompleteHandler(string assetName, string assetDescription, UUI
UUID owner_id = m_HostCapsObj.AgentID;
UUID creatorID;
- bool istest = IsAtestUpload && m_enableFreeTestUpload;
+ bool istest = IsAtestUpload && ConfigOptions.enableFreeTestUpload;
- bool restrictPerms = m_RestrictFreeTestUploadPerms && istest;
+ bool restrictPerms = ConfigOptions.RestrictFreeTestUploadPerms && istest;
- if (istest && m_testAssetsCreatorID != UUID.Zero)
- creatorID = m_testAssetsCreatorID;
+ if (istest && ConfigOptions.testAssetsCreatorID.IsNotZero())
+ creatorID = ConfigOptions.testAssetsCreatorID;
else
creatorID = owner_id;
@@ -784,7 +720,7 @@ public void UploadCompleteHandler(string assetName, string assetDescription, UUI
SceneObjectGroup grp = null;
// create and store texture assets
- bool doTextInv = (!istest && m_enableModelUploadTextureToInventory &&
+ bool doTextInv = (!istest && ConfigOptions.enableModelUploadTextureToInventory &&
texturesFolder != UUID.Zero);
@@ -909,6 +845,7 @@ public void UploadCompleteHandler(string assetName, string assetDescription, UUI
}
int skipedMeshs = 0;
+ float primScaleMin = m_ModelCost.PrimScaleMin;
// build prims from instances
for (int i = 0; i < instance_list.Count; i++)
{
@@ -917,7 +854,7 @@ public void UploadCompleteHandler(string assetName, string assetDescription, UUI
// skip prims that are 2 small
Vector3 scale = inner_instance_list["scale"].AsVector3();
- if (scale.X < m_PrimScaleMin || scale.Y < m_PrimScaleMin || scale.Z < m_PrimScaleMin)
+ if (scale.X < primScaleMin || scale.Y < primScaleMin || scale.Z < primScaleMin)
{
skipedMeshs++;
continue;
@@ -1558,12 +1495,8 @@ public void GetObjectCost(IOSHttpRequest httpRequest, IOSHttpResponse httpRespon
if (grp != null)
{
haveone = true;
- float linksetCost;
- float linksetPhysCost;
- float partCost;
- float partPhysCost;
- grp.GetResourcesCosts(part,out linksetCost,out linksetPhysCost,out partCost,out partPhysCost);
+ grp.GetResourcesCosts(part, out float linksetCost, out float linksetPhysCost, out float partCost, out float partPhysCost);
LLSDxmlEncode2.AddMap(uuid.ToString(), lsl);
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCapsModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCapsModule.cs
index 2b0598058c5..0098e95970a 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCapsModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCapsModule.cs
@@ -26,8 +26,6 @@
*/
using System;
-using System.Collections.Generic;
-using System.Reflection;
using log4net;
using Nini.Config;
@@ -44,14 +42,35 @@
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.AssemblyVersionNumber)]
namespace OpenSim.Region.ClientStack.Linden
{
+ public class BunchOfCapsConfigOptions
+ {
+ public ModelCost ModelCost;
+
+ public bool persistBakedTextures = false;
+ public bool enableModelUploadTextureToInventory = true; // place uploaded textures also in inventory
+ // may not be visible till relog
+ public bool enableFreeTestUpload = false; // allows "TEST-" prefix hack
+ public bool ForceFreeTestUpload = false; // forces all uploads to be test
+
+ public bool RestrictFreeTestUploadPerms = false; // reduces also the permitions. Needs a creator defined!!
+
+ public int levelUpload = 0;
+
+ public bool AllowCapHomeLocation = true;
+ public bool AllowCapGroupMemberData = true;
+ public bool AllowCapLandResources = true;
+ public bool AllowCapAttachmentResources = true;
+
+ public UUID testAssetsCreatorID = UUID.Zero;
+ }
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BunchOfCapsModule")]
public class BunchOfCapsModule : INonSharedRegionModule
{
-// private static readonly ILog m_log =
-// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+ //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_Scene;
+ private BunchOfCapsConfigOptions ConfigOptions = new();
#region INonSharedRegionModule
@@ -68,7 +87,6 @@ public void Close() { }
public void AddRegion(Scene scene)
{
m_Scene = scene;
- m_Scene.EventManager.OnRegisterCaps += OnRegisterCaps;
}
public void RemoveRegion(Scene scene)
@@ -77,6 +95,70 @@ public void RemoveRegion(Scene scene)
public void RegionLoaded(Scene scene)
{
+ ConfigOptions.ModelCost = new ModelCost(m_Scene);
+
+ IConfigSource config = m_Scene.Config;
+ if (config is not null)
+ {
+ IConfig sconfig = config.Configs["Startup"];
+ if (sconfig is not null)
+ ConfigOptions.levelUpload = sconfig.GetInt("LevelUpload", 0);
+
+ if (ConfigOptions.levelUpload == 0)
+ {
+ IConfig pconfig = config.Configs["Permissions"];
+ if (pconfig is not null)
+ ConfigOptions.levelUpload = pconfig.GetInt("LevelUpload", 0);
+ }
+
+ IConfig appearanceConfig = config.Configs["Appearance"];
+ if (appearanceConfig is not null)
+ {
+ ConfigOptions.persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", ConfigOptions.persistBakedTextures);
+ }
+ // economy for model upload
+ IConfig EconomyConfig = config.Configs["Economy"];
+ if (EconomyConfig is not null)
+ {
+ ConfigOptions.ModelCost.Econfig(EconomyConfig);
+
+ ConfigOptions.enableModelUploadTextureToInventory =
+ EconomyConfig.GetBoolean("MeshModelAllowTextureToInventory", ConfigOptions.enableModelUploadTextureToInventory);
+
+ ConfigOptions.RestrictFreeTestUploadPerms =
+ EconomyConfig.GetBoolean("m_RestrictFreeTestUploadPerms", ConfigOptions.RestrictFreeTestUploadPerms);
+
+ ConfigOptions.enableFreeTestUpload = EconomyConfig.GetBoolean("AllowFreeTestUpload", ConfigOptions.enableFreeTestUpload);
+
+ ConfigOptions.ForceFreeTestUpload =
+ EconomyConfig.GetBoolean("ForceFreeTestUpload", ConfigOptions.ForceFreeTestUpload);
+
+ string testcreator = EconomyConfig.GetString("TestAssetsCreatorID", "");
+ if (!string.IsNullOrEmpty(testcreator))
+ {
+ if (UUID.TryParse(testcreator, out UUID id))
+ ConfigOptions.testAssetsCreatorID = id;
+ }
+ }
+
+ IConfig CapsConfig = config.Configs["ClientStack.LindenCaps"];
+ if (CapsConfig is not null)
+ {
+ string homeLocationUrl = CapsConfig.GetString("Cap_HomeLocation", "localhost");
+ ConfigOptions.AllowCapHomeLocation = !string.IsNullOrEmpty(homeLocationUrl);
+
+ string GroupMemberDataUrl = CapsConfig.GetString("Cap_GroupMemberData", "localhost");
+ ConfigOptions.AllowCapGroupMemberData = !string.IsNullOrEmpty(GroupMemberDataUrl);
+
+ string LandResourcesUrl = CapsConfig.GetString("Cap_LandResources", "localhost");
+ ConfigOptions.AllowCapLandResources = !string.IsNullOrEmpty(LandResourcesUrl);
+
+ string AttachmentResourcesUrl = CapsConfig.GetString("Cap_AttachmentResources", "localhost");
+ ConfigOptions.AllowCapAttachmentResources = !string.IsNullOrEmpty(AttachmentResourcesUrl);
+ }
+
+ m_Scene.EventManager.OnRegisterCaps += OnRegisterCaps;
+ }
}
public void PostInitialise() { }
@@ -84,7 +166,7 @@ public void PostInitialise() { }
private void OnRegisterCaps(UUID agentID, Caps caps)
{
- new BunchOfCaps(m_Scene, agentID, caps);
+ _ = new BunchOfCaps(m_Scene, agentID, caps, ConfigOptions);
}
}
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/DispatchRegionInfo.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/DispatchRegionInfo.cs
new file mode 100644
index 00000000000..3fdcdf085af
--- /dev/null
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/DispatchRegionInfo.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Collections;
+
+using System.IO;
+using System.Net;
+using System.Text;
+using System.Threading;
+
+using OpenMetaverse;
+using OpenMetaverse.StructuredData;
+
+using OpenSim.Framework;
+using OpenSim.Framework.Capabilities;
+using OpenSim.Region.Framework.Scenes;
+using OpenSim.Region.Framework.Interfaces;
+using OpenSim.Framework.Servers.HttpServer;
+using OSDMap = OpenMetaverse.StructuredData.OSDMap;
+
+namespace OpenSim.Region.ClientStack.Linden
+{
+
+ public partial class BunchOfCaps
+{
+ public void DispatchRegionInfo(IOSHttpRequest request, IOSHttpResponse response, OSDMap map)
+ {
+ //m_log.Debug("[CAPS]: DispatchRegionInfo Request in region: " + m_regionName + "\n");
+
+ if (request.HttpMethod != "POST")
+ {
+ response.StatusCode = (int)HttpStatusCode.NotFound;
+ return;
+ }
+
+ if(map == map.Count < 3)
+ {
+ response.StatusCode = (int)HttpStatusCode.BadRequest;
+ return;
+ }
+
+ if (!m_Scene.TryGetScenePresence(m_AgentID, out ScenePresence _) || !m_Scene.Permissions.CanIssueEstateCommand(m_AgentID, false))
+ {
+ response.StatusCode = (int)HttpStatusCode.Unauthorized;
+ return;
+ }
+
+ IEstateModule estateModule = m_Scene.RequestModuleInterface();
+ if (estateModule == null)
+ {
+ response.StatusCode = (int)HttpStatusCode.NotImplemented;
+ return;
+ }
+
+ response.StatusCode = estateModule.SetRegionInfobyCap(map) ? (int)HttpStatusCode.OK : (int)HttpStatusCode.NotImplemented;
+ }
+ }
+}
\ No newline at end of file
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/UpdateItemAsset.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/UpdateItemAsset.cs
index 9a2ab410c31..a57a3e71d90 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/UpdateItemAsset.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/UpdateItemAsset.cs
@@ -335,7 +335,7 @@ public void process(IOSHttpRequest request, IOSHttpResponse response, byte[] dat
if (m_dumpAssetToFile)
{
- Util.SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
+ Util.SaveAssetToFile("updateditem" + Random.Shared.Next(1, 1000) + ".dat", data);
}
response.StatusCode = (int)HttpStatusCode.OK;
@@ -417,7 +417,7 @@ public void process(IOSHttpRequest request, IOSHttpResponse response, byte[] dat
if (m_dumpAssetToFile)
{
- Util.SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
+ Util.SaveAssetToFile("updatedtaskscript" + Random.Shared.Next(1, 1000) + ".dat", data);
}
// m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EstateAccess.cs b/OpenSim/Region/ClientStack/Linden/Caps/EstateAccess.cs
index caf7fb7e8ec..a77e3fec1d7 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/EstateAccess.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/EstateAccess.cs
@@ -144,8 +144,7 @@ public void ProcessRequest(IOSHttpRequest request, IOSHttpResponse response, UUI
return;
}
- ScenePresence avatar;
- if (!m_scene.TryGetScenePresence(AgentId, out avatar) || m_scene.RegionInfo == null || m_scene.RegionInfo.EstateSettings == null)
+ if (!m_scene.TryGetScenePresence(AgentId, out ScenePresence _) || m_scene.RegionInfo == null || m_scene.RegionInfo.EstateSettings == null)
{
response.StatusCode = (int)HttpStatusCode.Gone;
return;
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EstateChangeInfo.cs b/OpenSim/Region/ClientStack/Linden/Caps/EstateChangeInfo.cs
index 0c4c1326193..f2c6883a8bc 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/EstateChangeInfo.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/EstateChangeInfo.cs
@@ -26,10 +26,7 @@
*/
using System;
-using System.Collections;
-using System.Collections.Generic;
using System.Net;
-using System.Text;
using System.Reflection;
using log4net;
@@ -38,7 +35,6 @@
using OpenMetaverse.StructuredData;
using Mono.Addins;
-using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
@@ -144,8 +140,7 @@ public void ProcessRequest(IOSHttpRequest request, IOSHttpResponse response, UUI
return;
}
- ScenePresence avatar;
- if (!m_scene.TryGetScenePresence(AgentId, out avatar) || !m_scene.Permissions.CanIssueEstateCommand(AgentId, false))
+ if (!m_scene.TryGetScenePresence(AgentId, out ScenePresence _) || !m_scene.Permissions.CanIssueEstateCommand(AgentId, false))
{
response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetHandlers.cs b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetHandlers.cs
index 8ca35f5abc4..131ce0d2dd9 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetHandlers.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetHandlers.cs
@@ -26,21 +26,12 @@
*/
using System;
-using System.Collections;
using System.Collections.Generic;
using System.Net;
-using System.Reflection;
-using System.Text;
-using log4net;
-using Nini.Config;
-using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
-using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
-using OpenSim.Region.Framework.Scenes;
-using Caps=OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.ClientStack.Linden
{
@@ -84,8 +75,7 @@ public byte[] EndEventToBytes(osUTF8 sb)
public virtual void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY)
{
if (DebugLevel > 0)
- m_log.DebugFormat("{0} EnableSimulator. handle={1}, endPoint={2}, avatarID={3}",
- LogHeader, handle, endPoint, avatarID, regionSizeX, regionSizeY);
+ m_log.Debug($"{LogHeader} EnableSimulator. handle={handle}, endPoint={endPoint}, avatarID={avatarID}");
osUTF8 sb = StartEvent("EnableSimulator");
LLSDxmlEncode2.AddArrayAndMap("SimulatorInfo", sb);
@@ -103,8 +93,7 @@ public virtual void EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoi
ulong regionHandle, int regionSizeX, int regionSizeY)
{
if (DebugLevel > 0)
- m_log.DebugFormat("{0} EstablishAgentCommunication. handle={1}, endPoint={2}, avatarID={3}",
- LogHeader, regionHandle, endPoint, avatarID, regionSizeX, regionSizeY);
+ m_log.Debug($"{LogHeader} EstablishAgentCommunication. handle={regionHandle}, endPoint={endPoint}, avatarID={avatarID}");
osUTF8 sb = StartEvent("EstablishAgentCommunication");
@@ -125,8 +114,7 @@ public virtual void TeleportFinishEvent(ulong regionHandle, byte simAccess,
UUID avatarID, int regionSizeX, int regionSizeY)
{
if (DebugLevel > 0)
- m_log.DebugFormat("{0} TeleportFinishEvent. handle={1}, endPoint={2}, avatarID={3}",
- LogHeader, regionHandle, regionExternalEndPoint, avatarID, regionSizeX, regionSizeY);
+ m_log.Debug($"{LogHeader} TeleportFinishEvent. handle={regionHandle}, endPoint={regionExternalEndPoint}, avatarID={avatarID}");
// not sure why flags get overwritten here
if ((flags & (uint)TeleportFlags.IsFlying) != 0)
@@ -157,8 +145,7 @@ public virtual void CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
string capsURL, UUID avatarID, UUID sessionID, int regionSizeX, int regionSizeY)
{
if (DebugLevel > 0)
- m_log.DebugFormat("{0} CrossRegion. handle={1}, avatarID={2}, regionSize={3},{4}>",
- LogHeader, handle, avatarID, regionSizeX, regionSizeY);
+ m_log.Debug($"{LogHeader} CrossRegion. handle={handle}, avatarID={avatarID}, regionSize={regionSizeX},{regionSizeY}>");
osUTF8 sb = StartEvent("CrossedRegion");
@@ -189,7 +176,7 @@ private static string InstantMessageBody(UUID fromAgent, string message, UUID to
Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket,
bool checkEstate, int godLevel, bool limitedToEstate)
{
- osUTF8 sb = new osUTF8(512);
+ osUTF8 sb = new(512);
LLSDxmlEncode2.AddMap("instantmessage", sb);
LLSDxmlEncode2.AddMap("message_params", sb); //messageParams
LLSDxmlEncode2.AddElem("type", dialog, sb);
@@ -350,7 +337,7 @@ public void GroupMembershipData(UUID AgentID, GroupMembershipData[] data)
public void PlacesQueryReply(UUID avatarID, UUID queryID, UUID transactionID, PlacesReplyData[] replyDataArray)
{
- osUTF8 sb = new osUTF8(256);
+ osUTF8 sb = new(256);
LLSDxmlEncode2.AddMap(sb);
LLSDxmlEncode2.AddElem("message", "PlacesReplyMessage", sb);
LLSDxmlEncode2.AddMap("QueryData[]", sb); LLSDxmlEncode2.AddArray(sb);
@@ -437,9 +424,8 @@ public void SendBulkUpdateInventoryItem(InventoryItemBase item, UUID avatarID, U
LLSDxmlEncode2.AddEndMapAndArray(sb);
LLSDxmlEncode2.AddRawElem("FolderData",sb);
-
- osUTF8 osName = new osUTF8(Utils.StringToBytesNoTerm(item.Name, 255));
- osUTF8 osDesc = new osUTF8(Utils.StringToBytesNoTerm(item.Description, 255));
+ osUTF8 osName = new osUTF8(item.Name, 255);
+ osUTF8 osDesc = new osUTF8(item.Description, 255);
LLSDxmlEncode2.AddArray("ItemData", sb);
LLSDxmlEncode2.AddMap(sb);
@@ -480,7 +466,7 @@ public void SendBulkUpdateInventoryItem(InventoryItemBase item, UUID avatarID, U
public static string KeepAliveEvent()
{
- osUTF8 sb = new osUTF8(256);
+ osUTF8 sb = new(256);
LLSDxmlEncode2.AddMap(sb);
LLSDxmlEncode2.AddElem("message", "FAKEEVENT", sb);
LLSDxmlEncode2.AddMap("body", sb);
@@ -489,9 +475,63 @@ public static string KeepAliveEvent()
return sb.ToString();
}
+ public void SendLargeGenericMessage(UUID avatarID, UUID? transationID, UUID? sessionID,
+ string method, UUID invoice, List message)
+ {
+ osUTF8 sb = StartEvent("LargeGenericMessage");
+ LLSDxmlEncode2.AddArrayAndMap("AgentData", sb);
+ LLSDxmlEncode2.AddElem("AgentID", avatarID, sb);
+ if (transationID.HasValue)
+ LLSDxmlEncode2.AddElem("TransactionID", transationID.Value, sb);
+ if (sessionID.HasValue)
+ LLSDxmlEncode2.AddElem("SessionID", sessionID.Value, sb);
+ LLSDxmlEncode2.AddEndMapAndArray(sb);
+
+ LLSDxmlEncode2.AddArrayAndMap("MethodData", sb);
+ LLSDxmlEncode2.AddElem("Method", method, sb);
+ LLSDxmlEncode2.AddElem("Invoice", invoice, sb);
+ LLSDxmlEncode2.AddEndMapAndArray(sb);
+
+ LLSDxmlEncode2.AddArrayAndMap("ParamList", sb);
+ foreach (string s in message)
+ LLSDxmlEncode2.AddElem("Parameter", s, sb);
+ LLSDxmlEncode2.AddEndMapAndArray(sb);
+
+ Enqueue(EndEventToBytes(sb), avatarID);
+ }
+
+ public void SendLargeGenericMessage(UUID avatarID, UUID? transationID, UUID? sessionID,
+ string method, UUID invoice, List message)
+ {
+ osUTF8 sb = StartEvent("LargeGenericMessage");
+ LLSDxmlEncode2.AddArrayAndMap("AgentData", sb);
+ LLSDxmlEncode2.AddElem("AgentID", avatarID, sb);
+ if (transationID.HasValue)
+ LLSDxmlEncode2.AddElem("TransactionID", transationID.Value, sb);
+ if (sessionID.HasValue)
+ LLSDxmlEncode2.AddElem("SessionID", sessionID.Value, sb);
+ LLSDxmlEncode2.AddEndMapAndArray(sb);
+
+ LLSDxmlEncode2.AddArrayAndMap("MethodData", sb);
+ LLSDxmlEncode2.AddElem("Method", method, sb);
+ LLSDxmlEncode2.AddElem("Invoice", invoice, sb);
+ LLSDxmlEncode2.AddEndMapAndArray(sb);
+
+ LLSDxmlEncode2.AddArrayAndMap("ParamList", sb);
+ foreach (byte[] b in message)
+ {
+ LLSDxmlEncode2.AddLLSD("Parameter", sb);
+ sb.Append(b);
+ LLSDxmlEncode2.AddLLSD("", sb);
+ }
+ LLSDxmlEncode2.AddEndMapAndArray(sb);
+
+ Enqueue(EndEventToBytes(sb), avatarID);
+ }
+
public byte[] BuildEvent(string eventName, OSD eventBody)
{
- OSDMap llsdEvent = new OSDMap(2);
+ OSDMap llsdEvent = new(2);
llsdEvent.Add("message", new OSDString(eventName));
llsdEvent.Add("body", eventBody);
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs
index 6ef07f3619f..3852296bbba 100755
--- a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs
@@ -30,6 +30,7 @@
using System.Collections.Generic;
using System.Net;
using System.Reflection;
+using System.Runtime.CompilerServices;
using System.Text;
using log4net;
using Nini.Config;
@@ -50,11 +51,11 @@ public struct QueueItem
public OSDMap body;
}
- [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EventQueueGetModule")]
+ [Mono.Addins.Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EventQueueGetModule")]
public partial class EventQueueGetModule : IEventQueue, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- private static string LogHeader = "[EVENT QUEUE GET MODULE]";
+ private static readonly string LogHeader = "[EVENT QUEUE GET MODULE]";
private const int KEEPALIVE = 60; // this could be larger now, but viewers expect it on opensim
// we need to go back to close before viwers, or we may lose data
@@ -67,10 +68,10 @@ public partial class EventQueueGetModule : IEventQueue, INonSharedRegionModule
protected Scene m_scene;
- private Dictionary m_ids = new Dictionary();
+ private readonly Dictionary m_ids = new();
- private Dictionary> queues = new Dictionary>();
- private Dictionary m_AvatarQueueUUIDMapping = new Dictionary();
+ private readonly Dictionary> queues = new();
+ private readonly Dictionary m_AvatarQueueUUIDMapping = new();
#region INonSharedRegionModule methods
public virtual void Initialise(IConfigSource config)
@@ -147,20 +148,19 @@ protected void HandleDebugEq(string module, string[] args)
else
{
DebugLevel = debugLevel;
- MainConsole.Instance.Output(
- "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.RegionInfo.RegionName);
+ MainConsole.Instance.Output($"Set event queue debug level to {DebugLevel} in {m_scene.RegionInfo.RegionName}");
}
}
protected void HandleShowEq(string module, string[] args)
{
- MainConsole.Instance.Output("Events in Scene {0} agents queues :", m_scene.Name);
+ MainConsole.Instance.Output($"Events in Scene {m_scene.Name} agents queues :");
lock (queues)
{
foreach (KeyValuePair> kvp in queues)
{
- MainConsole.Instance.Output(" {0} {1}", kvp.Key, kvp.Value.Count);
+ MainConsole.Instance.Output($" {kvp.Key} {kvp.Value.Count}");
}
}
}
@@ -221,14 +221,12 @@ public bool Enqueue(OSD data, UUID avatarID)
}
else
{
- m_log.WarnFormat(
- "[EVENTQUEUE]: (Enqueue) No queue found for agent {0} in region {1}",
- avatarID, m_scene.Name);
+ m_log.Warn($"[EVENTQUEUE]: (Enqueue) No queue found for agent {avatarID} in region {m_scene.Name}");
}
}
catch (NullReferenceException e)
{
- m_log.Error("[EVENTQUEUE] Caught exception: " + e);
+ m_log.Error($"[EVENTQUEUE] Caught exception: {e.Message}");
return false;
}
return true;
@@ -341,9 +339,9 @@ private void ClientClosed(UUID agentID, Scene scene)
/// Generate an Event Queue Get handler path for the given eqg uuid.
///
///
- private string GenerateEqgCapPath(UUID eqgUuid)
+ private static string GenerateEqgCapPath(UUID eqgUuid)
{
- return string.Format("/CE/{0}", eqgUuid);
+ return $"/CE/{eqgUuid}";
}
public void OnRegisterCaps(UUID agentID, Caps caps)
@@ -351,16 +349,13 @@ public void OnRegisterCaps(UUID agentID, Caps caps)
// Register an event queue for the client
if (DebugLevel > 0)
- m_log.DebugFormat(
- "[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}",
- agentID, caps, m_scene.RegionInfo.RegionName);
+ m_log.Debug(
+ $"[EVENTQUEUE]: OnRegisterCaps: agentID {agentID} caps {caps} region {m_scene.Name}");
UUID eventQueueGetUUID;
- Queue queue = null;
-
lock (queues)
{
- queues.TryGetValue(agentID, out queue);
+ queues.TryGetValue(agentID, out Queue queue);
if (queue == null)
{
@@ -377,8 +372,7 @@ public void OnRegisterCaps(UUID agentID, Caps caps)
m_ids[agentID]++;
else
{
- Random rnd = new Random(Environment.TickCount);
- m_ids[agentID] = rnd.Next(30000000);
+ m_ids[agentID] = Random.Shared.Next(30000000);
}
}
}
@@ -391,21 +385,19 @@ public void OnRegisterCaps(UUID agentID, Caps caps)
lock (m_AvatarQueueUUIDMapping)
{
// Its reuse caps path not queues those are been reused already
- if (m_AvatarQueueUUIDMapping.ContainsKey(agentID))
+ if (m_AvatarQueueUUIDMapping.TryGetValue(agentID, out eventQueueGetUUID))
{
m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!");
- eventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID];
lock (m_ids)
{
// change to negative numbers so they are changed at end of sending first marker
// old data on a queue may be sent on a response for a new caps
// but at least will be sent with coerent IDs
- if (m_ids.ContainsKey(agentID))
- m_ids[agentID] = -m_ids[agentID];
+ if (m_ids.TryGetValue(agentID, out int previd))
+ m_ids[agentID] = -previd;
else
{
- Random rnd = new Random(Environment.TickCount);
- m_ids[agentID] = -rnd.Next(30000000);
+ m_ids[agentID] = -Random.Shared.Next(30000000);
}
}
}
@@ -415,12 +407,11 @@ public void OnRegisterCaps(UUID agentID, Caps caps)
m_AvatarQueueUUIDMapping[agentID] = eventQueueGetUUID;
lock (m_ids)
{
- if (m_ids.ContainsKey(agentID))
- m_ids[agentID]++;
+ if (m_ids.TryGetValue(agentID, out int previd))
+ m_ids[agentID] = ++previd;
else
{
- Random rnd = new Random(Environment.TickCount);
- m_ids.Add(agentID, rnd.Next(30000000));
+ m_ids.Add(agentID, Random.Shared.Next(30000000));
}
}
}
@@ -433,7 +424,7 @@ public void OnRegisterCaps(UUID agentID, Caps caps)
new PollServiceEventArgs(null, GenerateEqgCapPath(eventQueueGetUUID), HasEvents, GetEvents, NoEvents, Drop, agentID, VIEWERKEEPALIVE));
}
- public bool HasEvents(UUID requestID, UUID agentID)
+ public bool HasEvents(UUID _, UUID agentID)
{
Queue queue = GetQueue(agentID);
if (queue != null)
@@ -454,12 +445,9 @@ public bool HasEvents(UUID requestID, UUID agentID)
/// Element containing message
private void LogOutboundDebugMessage(OSD element, UUID agentId)
{
- if (element is OSDMap)
+ if (element is OSDMap ev)
{
- OSDMap ev = (OSDMap)element;
- m_log.DebugFormat(
- "Eq OUT {0,-30} to {1,-20} {2,-20}",
- ev["message"], m_scene.GetScenePresence(agentId).Name, m_scene.Name);
+ m_log.Debug($"Eq OUT {ev["message"],-30} to {m_scene.GetScenePresence(agentId).Name,-20} {m_scene.Name,-20}");
}
}
@@ -468,16 +456,16 @@ public void Drop(UUID requestID, UUID pAgentId)
// do nothing, in last case http server will do it
}
- private readonly byte[] EventHeader = osUTF8.GetASCIIBytes("