Compare commits

...

129 Commits

Author SHA1 Message Date
Justin Clark-Casey d600c35a40 Change version number to 0.8.0.4 2015-03-04 17:21:03 +00:00
Justin Clark-Casey 732d04cb4a Make private services forbid llHTTPRequest() calls by rejecting those that have the X-SecondLife-Shard header.
If you need to enable this, set AllowHttpRequestIn = true in [Network] for all private services or individual [*Service] sections.
2015-03-04 17:20:13 +00:00
Justin Clark-Casey b710295607 Add outbound URL filter to llHttpRequest() and osSetDynamicTextureURL*() script functions.
This is to address an issue where HTTP script functions could make calls to localhost and other endpoints inside the simulator's LAN.
By default, calls to all private addresses are now blocked as per http://en.wikipedia.org/wiki/Reserved_IP_addresses
If you require exceptions to this, configure [Network] OutboundDisallowForUserScriptsExcept in OpenSim.ini
2015-03-04 17:20:05 +00:00
Justin Clark-Casey 3990d922fb Update version to 0.8.0.3 and flavour to release 2014-11-11 17:38:21 +00:00
Justin Clark-Casey 5dcc49c9ec Fix issue where llRemoteLoadScriptPin() would treat 0 (the default) as a valid set pin in a destination prim rather than the unset no pin state
Adds regression test for this case.
2014-11-11 17:27:02 +00:00
Justin Clark-Casey 3879f9a081 Change 0.8-post-fixes branch back to Post-Fixes flavour 2014-10-16 21:10:02 +01:00
Justin Clark-Casey 10ed3a5520 Change 0.8 post fixes to 0.8.0.2 release 2014-10-16 20:22:43 +01:00
Justin Clark-Casey (justincc) ddda314f14 Add some more llGiveInventory() regression tests 2014-10-16 20:18:20 +01:00
Melanie Thielker 8fb0dccffa Fix transferring inventory from prims to agent inventory 2014-10-16 20:18:16 +01:00
Justin Clark-Casey 4a90dd3556 Change 0.8-post-fixes branch back to Post_Fixes flavour 2014-08-23 00:02:12 +01:00
Justin Clark-Casey f6d02a63eb Change 0.8 post fixes branch to version 0.8.0.1 with release flavour. 2014-08-22 20:19:16 +01:00
Oren Hurvitz 422f718949 Fixed crash when using Allowed/Denied Viewers, and the viewer's name is shorter than one of the test strings
This fixes http://opensimulator.org/mantis/view.php?id=7294
2014-08-22 19:20:19 +01:00
Oren Hurvitz 3176237169 Fixed premature closing of the connection in DataSnapshotManager 2014-08-08 20:46:59 +01:00
Justin Clark-Casey (justincc) a4595b18ca Make currently unfiltered EventQueue log messages only appear now at DebugLevel 1
This covers event queue setup messages and some outgoing messages (e.g. EnableSimulator)
In my experience these messages are only useful if you really know what they mean and you're looking for them
Otherwise, they're quite spammy.
Event queue DebugLevel 1 is enabled with the "debug eq 1" console command
2014-08-05 00:51:17 +01:00
Justin Clark-Casey 4640281e57 Add conflict resolution that should have been done in conflict resolution of 4e3a2d3a64 2014-08-02 01:04:58 +01:00
Justin Clark-Casey (justincc) 319bbce517 If REMOVEAGENTFROMGROUP core groups call fails because requesting agent does not have sufficient permission, return null failure result rather than true.
On non-HG this is on the only recognized failure state so we can return more information in the error result.
On HG there are multiple failure states which would require more work to distinguish, so currently return the unsatisfying "Internal Error" like some other existing calls.
2014-08-02 00:58:37 +01:00
Justin Clark-Casey (justincc) a48b3ef97a Don't overwrite the null result with the true result is groups service REMOVEAGENTFROMGROUP call has failed because of missing parameters 2014-08-02 00:58:33 +01:00
Justin Clark-Casey (justincc) 32a9fcd8b3 Fix bug where calling PUTGROUP on the core groups service without specifying a ServiceLocation would set the group name to an empty string.
This should set the ServiceLocation to an empty string instead.
2014-08-02 00:58:30 +01:00
Robert Adams eedefdc5ff BulletSim: rearrange code for sensing whether shapes have been
constructed.
Add routine to check for failed and use that method rather than
    checking individual state.
2014-08-02 00:58:27 +01:00
Justin Clark-Casey (justincc) 05dfc38f66 Add inventory.<url>.RequestsMade stat.
This gives a count of all requests made to the remote inventory service.
This is finer grained than inventory.httpfetch.ProcessedFetchInventoryRequests since such a request can be comprised of many individual inv service calls.
In addition, this will count requests that don't go through the HTTP inventory fetch (e.g. HG, archiving, etc.)

Conflicts:
	OpenSim/Services/Connectors/Inventory/XInventoryServicesConnector.cs
2014-08-02 00:58:23 +01:00
Justin Clark-Casey (justincc) 95f3a9452d Fix issue with TestTextureNotFound in previous commit 1e3027a
Stop failure by actually giving the test handler a path instead of null
2014-08-02 00:58:15 +01:00
Justin Clark-Casey (justincc) 3410b36d76 Temporary stop CAPS service points from being added to stats as this can be a huge number.
A stop gap solution - a better one may be to improve stats display on simulator-side.
Caps information is still accessible via the "show caps stats by user" and "show caps stats by cap" commands
2014-08-02 00:58:12 +01:00
Justin Clark-Casey (justincc) 2f7d950ead Add stats for service endpoints using existing data.
For each service endpoint (e.g. posts to the xinventory service), a stat is available which shows the number of requests received and moving average per second
The full name is "service.<http-method>:<path>.requests (e.g. service.POST:/xinventory.requests)
2014-08-02 00:58:09 +01:00
Michael Cerquoni 26916806db fix comments in physics section of [Startup] to reflect the actual default engine. 2014-08-02 00:58:06 +01:00
Justin Clark-Casey (justincc) bdfbe4d0e2 Add missing default female hair texture for Ruth avatar.
This was not in library assets despite being referred to in assets/BodyPartsAssetSet/base_hair.dat
Texture ID is 7ca39b4c-bd19-4699-aff7-f93fd03d3e7b
Taken from https://github.com/openmetaversefoundation/simiangrid/blob/master/Grid/default_assets/Default%20Female%20Hair-7ca39b4c-bd19-4699-aff7-f93fd03d3e7b.j2c
2014-08-02 00:58:02 +01:00
Justin Clark-Casey (justincc) dfaabf4d0d Fix recent regression in 3c6becd5 where login or hg login to variable sized regions failed with outdated simulator message.
I forgot that a null 'their version' would not be passed over the wire and ends up as an empty string instead (like older simulators).
So instead pass through the correct simulator protcol version instead (SIMULATOR/0.3) when querying from login or hg login.
Also removes a debug console write for agent limit accidentally left in for the same commit.
Relates to mantis 7276
2014-08-02 00:57:59 +01:00
Justin Clark-Casey (justincc) fdb0c7389e minor: convert tabs to spaces that got in on recent commit 4a9282e 2014-08-02 00:57:49 +01:00
Justin Clark-Casey (justincc) 92e2478059 On login and first HG entrance to a foreign grid, perform query access checks before proceeding. 2014-08-02 00:57:43 +01:00
Justin Clark-Casey (justincc) b6e32c000b minor: Limit processor related stats to 3 decimal places instead of all the places.
Easier to read and analyze, and probably still too much detail (1 dp would probably be fine)
2014-08-02 00:57:36 +01:00
Justin Clark-Casey (justincc) ed4a4d6bbd Fix CPU processor use reporting on Mono.
Despite the comments in the code, it appears that the issue where the .NET performance counter was wrongly idle time time on Mono was fixed in 2009.
https://bugzilla.novell.com/show_bug.cgi?id=468625
Which means that the workaround is no longer necessary and produces bad results instead.
2014-08-02 00:57:33 +01:00
BlueWall 7e0d0282c4 Add missing parts to profiles - classified delete 2014-08-02 00:57:29 +01:00
Oren Hurvitz 8de1be746f Fixed: after a Hypergrid teleport, attachments often either disappear, or appear both on the avatar AND as in-world objects.
Another manifestation of this bug is that after a Hypergrid teleport, when you click on one of the avatar's attachments the object doesn't show its name. This means that the viewer knows the attachment is there, but the simulator does not.

The problem was caused by treating Hypergrid teleports as if they're Logins (because the teleport flag ViaLogin is enabled).

This may fix: http://opensimulator.org/mantis/view.php?id=7238
This may fix: http://opensimulator.org/mantis/view.php?id=7220
2014-08-02 00:57:24 +01:00
Oren Hurvitz e7bd4a11aa Don't append attachments multiple times 2014-08-02 00:57:20 +01:00
Oren Hurvitz f1536de438 Allow reading the BulletSim detail log while the sim is running 2014-08-02 00:57:17 +01:00
Oren Hurvitz 4514799c8d Changed the default XBakes directory to a local path: "./bakes".
Previously it was an absolute path. Now it's a sibling of the maptiles directory.

This fixes http://opensimulator.org/mantis/view.php?id=7063
2014-08-02 00:57:11 +01:00
Oren Hurvitz 5f0456d91f XBakes: store the assets only in the sim's local assets cache; not in the main assets server. Also, some cleanup. 2014-08-02 00:57:07 +01:00
Oren Hurvitz 9a2dc6a0d7 Log RestClient requests similarly to WebClient (e.g, "debug http all 6" logs the entire request and response) 2014-08-02 00:57:04 +01:00
Oren Hurvitz 37fcc827e2 Fixed problems if an avatar tries to cross regions when the previous cross hasn't completed yet
This caused the client to stop responding, and even the simulators to have problems. The solution is to disallow crossing before the previous cross has completed.
2014-08-02 00:56:58 +01:00
Oren Hurvitz 5229a3c51c Added locking in AccessModule to prevent possible errors when shutting down a simulator that has >1 region 2014-08-02 00:56:54 +01:00
Oren Hurvitz e16403db80 Minor: changed "existant" to "existent" 2014-08-02 00:56:37 +01:00
Oren Hurvitz c4467353da Removed warning about YieldProlog 2014-08-02 00:56:29 +01:00
Oren Hurvitz d616f75d9a In "show throttles", show the maximum drip rate. This shows whether a client is being throttled due to past poor performance. 2014-08-02 00:56:26 +01:00
Oren Hurvitz ae53c6b834 Include the group name in group IM's
When sending an ImprovedInstantMessage to a group, the IM's binary bucket is supposed to contain the group's name (this is what SL does). Singularity uses this to show the group name when it shows the message at the bottom of the viewer for a few seconds: "[Group Name] From User: Message". Before this update, the group name was empty ("[]").

This update doesn't have any visible effect in Firestorm, because it doesn't use the group name sent in the IM.
2014-08-02 00:56:23 +01:00
Oren Hurvitz af344aa532 Added "debug packet --all" option, which changes the packet logging level for both current and future clients
The existing "--default" option only changes the logging level for future clients.
2014-08-02 00:56:16 +01:00
Oren Hurvitz 8920c65b9c Fixed the logic that decides if a packet was queued (it was reversed) 2014-08-02 00:56:13 +01:00
Oren Hurvitz e41e52e097 Close streams immediately when we finish using them 2014-08-02 00:55:57 +01:00
Robert Adams 01d13b4ad7 Add code to GridService to check for overlapping of varregions
when registering a new region.

Adds parameter "[GridService]SuppressVarRegionOverlapCheckOnRegistration=false"
that can be turned on to suppress the error check if a simulator's database
has old regions that overlap.
2014-08-02 00:55:47 +01:00
Justin Clark-Casey (justincc) 74848e9cdb minor: remove long unused RegionInfo.ignoreIncomingConfiguration 2014-08-02 00:55:12 +01:00
Justin Clark-Casey (justincc) ff88d371d2 minor: remove long unused RegionInfo.commFailTF 2014-08-02 00:55:04 +01:00
Justin Clark-Casey (justincc) 19bd27071a refactor: slightly adjust some code in ODECharacter.Move() to eliminate a condition check without changing the logic 2014-08-02 00:55:01 +01:00
Justin Clark-Casey (justincc) ad3ce54aca With ODE physics, fix an issue where the avatar couldn't jump and then move forward when moving south or west.
Addresses http://opensimulator.org/mantis/view.php?id=5003
Thanks to UbitUmarov for this fix.
2014-08-02 00:54:57 +01:00
Robert Adams db17f98c6f BulletSim: rearrange code to prevent using null pointers when a
child mesh is not available when building a linkset.
2014-08-02 00:54:54 +01:00
Michael Cerquoni 66340824e5 fix all instances of "non-existant" to "non-existent" (spelling mistakes) thanks Ai Austin for pointing this out. 2014-08-02 00:54:48 +01:00
Justin Clark-Casey (justincc) 539ffb7769 Use thread-safe version of .NET Random as the SDK class is not thread-safe.
As per http://msdn.microsoft.com/en-us/library/system.random%28v=vs.100%29.aspx, the .NET Random class is not thread-safe.
If called by multiple threads at once, methods may return 0.
Except for llRand(), other OpenSimulator code did not lock before calling a shared Random instance.
This commit adds a ThreadSafeRandom class that extends Random but does internal locking so that it is thread-safe.
This change is invisible to existing callers and the explicit locking in the llFrand() implementation is now redundant.
2014-08-02 00:54:42 +01:00
Dev Random d35b5737a8 Call RemoveScriptInstance when removing from inventory 2014-08-02 00:53:35 +01:00
Justin Clark-Casey (justincc) 1670d306d7 minor: Move debug xengine script console command to Debug help section where other debug commands live. 2014-08-02 00:53:32 +01:00
Justin Clark-Casey (justincc) 405db6d450 refactor: use existing Compiler.CreateScriptsDirectory() (renamed to CheckOrCreateScriptsDirectory()) when checking that scripts directory exists on compile.
Code was identical apart from error logging, but if there are failures creating these directories then you'll be
seeing lots of errors anyway, and these will be more informative
2014-08-02 00:53:20 +01:00
Justin Clark-Casey (justincc) 743b1efdb4 Fix bug in "show modules" comamnd that was showing shared modules as non-shared and non-shared as shared 2014-08-02 00:53:14 +01:00
Justin Clark-Casey (justincc) b243cde14f Turn RestClient.Request() logging down the debug and comment out for now. 2014-08-02 00:53:10 +01:00
Justin Clark-Casey (justincc) 73ed56f46a Fix issue with running "stats record start|stop" console command
In commit e6080a38 (Wed Mar 19 00:29:36 2014) I renamed this from "debug stats record start|stop"
Unfortunately, I didn't do this fully so before this commit "stats record start|stop" will report a usage failure with the old debug text.
Unfortunately this is in the 0.8 release.  The workaround is to repeat the last command twice (e.g. "stats record start start")
2014-08-02 00:53:06 +01:00
Justin Clark-Casey (justincc) 6b5533dbdb Add experimental "show grid size" robust console command.
This will show an approximate grid size that doesn't count regions that are hyperlinks
Not particularly trustworthy since it will still count regions that are not active but were not deregistered (deliberately or due to simulator crash or similar)
2014-08-02 00:52:53 +01:00
Diva Canto 3dd5d8508c Small change to my previous commit: not so aggressive on the trigger, please. 2014-08-02 00:52:46 +01:00
Justin Clark-Casey (justincc) 2a15739935 Show region size column in simulator version of "show regions" console command 2014-08-02 00:52:25 +01:00
Justin Clark-Casey (justincc) fabe054608 Adjust "show regions" and "show region" robust service console output to show size
"show regions" drops the owner id column but is till present in "show region"
"show regions" name column expanded to allow for longer hg regions (probably still too short, may eventually have to truncate rather than taking up huge screen space)
2014-08-02 00:52:22 +01:00
Diva Canto fe1ae9db1b Instrument the UDP path of creating assets so that it triggers an asset post for users with different asset servers 2014-08-02 00:52:15 +01:00
Justin Clark-Casey (justincc) 12ce20a203 minor: put standard 'category' in brackets at front of log messages from previous commit 3d70db4a 2014-08-02 00:52:12 +01:00
Latif Khalifa 45e280274c When uploading mesh objects with textures also create inventory items for uploaded textures.
This implements:
http://opensimulator.org/mantis/view.php?id=7250
2014-08-02 00:52:07 +01:00
Justin Clark-Casey (justincc) e87a0d9db1 Still log (but this time with warning rather than an exception) if we regenerate a new child caps seed for a region where we already have one.
I think it's still useful to know this to show up any errors early, but it's reasonable to still carry on rather than throw an exception.
Follow on from Diva's commit 9643792
2014-08-02 00:51:57 +01:00
Diva Canto 62e9cdd72a On logout, delay the removal of AgentCircuitData until the very end, because that data structure contains important information about the agent that may be needed by modules. 2014-08-02 00:51:53 +01:00
Diva Canto 3730163e5d This fixes the bug related to rebooting neighboring varregions while avatars are logged in; the avies would not see the region anymore until they relogged. Same problem as before: inconsistent calculation of scope. 2014-08-02 00:51:49 +01:00
Diva Canto 4e3a2d3a64 It turns out that child agent management has had a bug for a while: there was an inconsistency in the scope between opening and closing child agents in neighboring regions. For opening (in EnableChildAgents), the region's DrawDistance was being used; for closing (in IsOUtsideView) , the viewer's (SP) DrawDistance was being used. This fixes this inconsistency, therefore eliminating bugs observed in TPs between, at least, neighboring varregions. 2014-08-02 00:51:36 +01:00
Diva Canto e9447cc836 Avoid an exception in creating child agents some times. 2014-08-02 00:50:21 +01:00
Justin Clark-Casey (justincc) 693a3ea8fa Temporarily disable new regression test TestLifecycle() until I have a chance to fix it
This was working for me locally because it was still picking up all my *.ini config files, which jenkins won't have in its test env
2014-08-02 00:50:18 +01:00
Justin Clark-Casey (justincc) 7e2927f537 Re-enabled TestLifecycle regression test logging so I can get some idea of why it's failing on jenkins but not locally 2014-08-02 00:50:15 +01:00
Justin Clark-Casey (justincc) ba745a524d Actually call Close() for shared region modules when the simulator is being shutdown.
Adds regression test for this case.
2014-08-02 00:50:10 +01:00
Justin Clark-Casey (justincc) cf8b6efaf2 minor: Change default max phys prim size in code to match OpenSimDefaults.ini 2014-08-02 00:50:02 +01:00
Justin Clark-Casey (justincc) 40f7062d02 minor: change allow script crossings default in code to true in order to match OpenSimDefaults.ini 2014-08-02 00:49:59 +01:00
dahlia 81fe05bb84 add LSL constant PRIM_ALPHA_MODE 2014-08-02 00:49:56 +01:00
Vegaslon ed6aabb197 Bulletsim: Create AvatarTerminalVelocity to BulletSim like what ODE and SL has. Before this falling from really high caused the avatar to fall faster then the veiwer can handle and cause camera issues. 2014-08-02 00:49:50 +01:00
dahlia 8542f34d7d add LSL constants PRIM_SPECULAR and PRIM_NORMAL 2014-08-02 00:49:46 +01:00
Diva Canto 025ac85a46 Bug fix in map teleports in varregions. The cherry was missing from the ice-cream Sunday: the packet itself was hardcoding the size of the region... 2014-08-02 00:49:43 +01:00
Robert Adams 5edffc9ecd BulletSim: add some locking for collision lists to prevent collsions
from locking up when running BulletSim on a separate thread.
2014-08-02 00:49:39 +01:00
Aleric Inglewood 56a3d2f00d Improved line map heuristics.
If the C# column can't be found in the positionMap (but the line can),
use the map immediately after it while correcting for the offset,
unless that results in an LSL position before the previous LSL position
in the positionMap.

The idea behind this heuristic is that in most, if not all cases C#
consumes more characters than LSL (for example LSL_Types.LSLInteger
instead of just 'integer').

Thus if the distance between the columns of two markers differ in
the C# and LSL file, the distance in the C# file will be larger.
Moreover, we can assume that every time this happens we will have
a marker at the beginning of the longer 'keyword', because those
keywords were generated by us in the first place.

For example:

C#:     LSL_Types.LSLInteger f2(LSL_Types.LSLString s)
        ^                       ^
        1                       2

will always have markers at the beginning of the long keywords
'LSL_Types.LSLInteger' and 'LSL_Types.LSLString'.
If an error is generated in between (for example at the beginning
of the function name 'f2') then the correct position is found
by using an offset relative to 2 rather than 1.

Note that a case where this isn't working correctly is
when the user adds extra spaces. For example:

LSL:   integer f2(    string s)

would still use the start of 'string' as reference and
then go backwards 3 characters only because the corresponding
C# still looks like

C#:     LSL_Types.LSLInteger f2(LSL_Types.LSLString s)
                             ^  ^
			     only 3 chars difference

and the reported error at 'f2' would be here:

LSL:   integer f2(    string s)
                   ^

This can only be fixed by generating a mapping for 'f2' itself, or
generating a mapping whenever the amount of spaces is changed.
2014-08-02 00:49:36 +01:00
Aleric Inglewood 28babf307e Fix looking up line number and colum when there is no exact match.
When a compile error reports a colum/error that is not an exact
match in the positionMap dictionary, the last position in the
map with a line number and position before the reported error
should be returned.

The old code had the following problems:
1) It returns l,c - which are line and column of the C# file, not LSL.
2) It doesn't set l to 'line' when the map has an entry with 'line'.
3) It sorts the map without taking columns into account, which may
   result in a random order of the columns. With my mono implementation
   the columns were reversed in order.

For example, if the map contains the following lines:

99,5,49,10
100,30,50,10
100,40,1,0
101,5,51,10

and a translation of 100,35 was requested,
then the old code would compare '100' with the keys in
the first column - setting l to that key while it is
smaller. Hence, l is set to 99.
Then it finds the key 100 and doesn't update l.
Because of the reversed sort order, it first compares
the column 35 with 40, finding that it is smaller
and therefore it stops; returning 99,1 instead of finding
the correct 100,30 entry and returning 50,10.

This patch causes 50,10 to be returned.

The remaining problems after this patch are:
1) The sorting might not be necessary at all.
2) The is code duplication (I fixed both instances,
   but really there should be no code duplication
   imho).
2014-08-02 00:49:32 +01:00
Robert Adams 03c6d2b0b4 BulletSim: stop processing linkset child when it is discovered that the
child doesn't have a physical shape. Another attempt at fixing Mantis 7191.
2014-08-02 00:49:28 +01:00
Robert Adams b293242017 BulletSim: more tweeks to AliciaRaven's flying mods. Added parameters
AvatarFlyingGroundMargin and AvatarFlyingGroundUpForce set to 5.0 and
2.0 respectively which seems to give about the same action as in SL.
Also moved force addition to before the velocity to force computation
so the upward velocity is properly applied to the avatar mass.
2014-08-02 00:49:24 +01:00
Justin Clark-Casey (justincc) 924ca8e2e9 refactor: Simplify compilation result tests by factoring out common code. 2014-08-02 00:49:21 +01:00
Justin Clark-Casey (justincc) 86630a9010 In compiler regression tests, setup and teardown structures for each test to avoid any possibility of inter-test inter-ference 2014-08-02 00:49:17 +01:00
Justin Clark-Casey (justincc) 68fcb132d9 Fix issue with LSL jumps screwing up the C# compiler error -> LSL code position map and leading to invalid error line numbers/columns
This is because jump statement generation was mistakenly inserting its own line without updating the csharp positions in CSCodeGenerator.
This is Aleric Inglewood's patch in http://opensimulator.org/mantis/view.php?id=7195 but applied to opensim itself rather than the defunct code generation in opensim-libs.  Thanks!
This patch also adds a regression test for this case from myself.
2014-08-02 00:49:02 +01:00
AliciaRaven 6f582aeaff Fix previous commit to ignore water height and allow flying underwater (swimming)
Signed-off-by: Michael Cerquoni <nebadon2025@gmail.com>
2014-08-02 00:48:59 +01:00
AliciaRaven fa1f6031ca Add upward force to flight when close to the ground. Prevents current belly flop to the floor when flying with bullet physics and acts more like ODE and SL flight.
Signed-off-by: Michael Cerquoni <nebadon2025@gmail.com>
2014-08-02 00:48:55 +01:00
Justin Clark-Casey eea3be9b17 Change flavour to post-fixes 2014-06-17 18:44:31 +01:00
Justin Clark-Casey 698dfe8977 Change 0.8 flavour to release 2014-06-17 16:48:36 +01:00
Justin Clark-Casey (justincc) 25757a6abb If MaterialsModule unexpected sees a part with DefaultTexture of null, log this with a warning. 2014-06-17 16:44:27 +01:00
Justin Clark-Casey (justincc) 5a1017241f If processing a queued request fails up to the top of the stack, log the exception and move to the next request rather than terminate the simulator. 2014-06-17 16:44:23 +01:00
Justin Clark-Casey (justincc) 76ee671dc6 In materials module, if a texture entry somehow has no default entry then don't try to extract materials data rather than throw an exception 2014-06-17 16:44:06 +01:00
Diva Canto 2cdef143c4 Behavior change: only local users can set home in any parcel of a grid. Setting it for foreign users does not make sense, since cntrl+shift+H always teleports them back to their original grid. 2014-06-16 18:04:45 +01:00
Diva Canto 34a645efb6 Manual change as per patch in mantis #7212. (the patch failed to apply, but the fix was good) Thanks FreakyTech. 2014-06-16 18:04:39 +01:00
Robert Adams 02980336a3 Add [Startup]LogShowStatsSeconds=n parameter which controls the interval
that simulator statistics is output to the console. Setting to zero turns
stats logging off.
2014-06-16 18:04:35 +01:00
Justin Clark-Casey 8899f2e2bb Change release flavour to rc3 2014-06-10 23:12:41 +01:00
Justin Clark-Casey (justincc) 60d4b0999c Add rc3 flavour option 2014-06-10 23:12:08 +01:00
Diva Canto a8edc908e0 Don't try to package null invites. 2014-06-10 20:29:24 +01:00
Robert Adams 901602411c BulletSim: fix exceptions while rebuilding linksets with mesh children.
This should get around the exception reported in Mantis 7191 and 7204
by checking for the unbuilt child and rebuilding the linkset the next tick.
A warning message is output when this rebuild happens and this message is
clamped to 10 times in case there is a problem with a loop.
2014-06-10 20:29:05 +01:00
Michael Cerquoni d98a19b398 fix the comment section of max_distance setting to reflect default value 2014-06-10 20:29:00 +01:00
Diva Canto e8f363ff90 Missed this ini change in previous commit 2014-06-10 20:28:54 +01:00
Michael Cerquoni 5e4cf1b84c bump default teleport limit to 65535 regions 2014-06-10 20:28:50 +01:00
Diva Canto ffe07527fc Added simulation version compatibility check so that agents coming from 0.7.6 to a varregion running in 0.8 and above will be denied teleport, rather than be allowed and crash the viewer. 2014-06-10 20:28:47 +01:00
Diva Canto 72456f90a4 Better comment regarding SizeX and SizeY 2014-06-10 20:28:40 +01:00
Diva Canto 0cf5ea9420 Amend to previous commit -- write down the problematic Profile server URL. 2014-06-10 20:28:36 +01:00
Diva Canto becb949a33 May fix mantis #7133 2014-06-10 20:28:29 +01:00
Diva Canto 63a6998409 Updated Regions.ini.example to include var regions configs. 2014-06-10 20:27:40 +01:00
Michael Cerquoni 15f323295b add Alicia Raven to Contributors list, thanks for the patch! 2014-06-10 20:27:35 +01:00
AliciaRaven 2c823c9f72 Fix AutoBackupModule and include option to skip saving assets.
Signed-off-by: Michael Cerquoni <nebadon2025@gmail.com>
2014-06-10 20:27:31 +01:00
Diva Canto d541f150d0 Added a ResetLand method to RemoteAdmin, whereby all land is reset with the given parameters. 2014-06-10 20:27:10 +01:00
Diva Canto 4da471a5aa Fix a bug where estate not found would result in a dummy estate record with erroneous information.
Also, added conversion of EstateSettings from/to key-value pairs in preparation for robust net work connectors.
2014-06-10 20:22:18 +01:00
Diva Canto 75d21aa71a Added missing reference 2014-06-10 20:21:58 +01:00
Justin Clark-Casey (justincc) 88e9cd0eee minor: rename velocidyDiff -> velocityDiff 2014-06-10 20:21:52 +01:00
Justin Clark-Casey (justincc) 26ec918ec8 minor: Add some commented out logging to ScenePresence.SendTerseUpdateToAllClients() which is extremely helpful when investigating presence update triggers. 2014-06-10 20:21:48 +01:00
Justin Clark-Casey (justincc) 4bc2201453 Fix issue with BulletSim avatar level flight jitter by commenting out RawVelocity update threshold for now in BSCharacter.UpdateProperties().
For some reason as yet unidentified (feedback?) a threshold above 0.4 here causes the RawVelocity to move between a lower and upper bound rather than remaining constant.
The RawVelocity increased until it triggered the threshold update, at which point it started to decrease until it again triggered the threshhold update.
This delta-v was enough to exceed the checks in ScenePresence.SendTerseUpdateToAllClients() and produce jittery avatar flight because of the fluctuating velocity.
With a threshold of 0.4 (or 0, as with ODE), the RawVelocity remains constant in BulletSim and so avatar flight becomes mostly smooth - remaining occasional glitches appear to be a result of errors in distance extraploation.
There are no obvious problems with commenting out the threshold.
Misterblue, if this is wrong or I've missed some subtlety here, please feel free to revert and/or correct.
The same considerations may or may not apply to object velocity updates.
2014-06-10 20:21:44 +01:00
dahlia 344db4dc0b Add a 0 parameter overload for RestClient.Request() for use when no auth is required. This preserves API compatibility for external modules using this function. 2014-06-10 20:21:39 +01:00
Diva Canto de6e3edfbb Moved these two estate-related interfaces to the projects where they belong. 2014-06-10 20:21:33 +01:00
Justin Clark-Casey (justincc) a1e92dead2 minor: Comment out log line in Groups V2 GroupsServicePostHandler for now which logs every request it receives. 2014-06-10 20:21:24 +01:00
Justin Clark-Casey (justincc) 068cab94e0 Fix bug where setting a parcel in a varregion for sale would make sale bitmap generation in WorldMapModule throw an exception on next startup.
This commit replaces the hardcoded region sizes in WorldMapModule.GenerateOverlay() with numbers pulled from m_scene.RegionInfo
2014-06-10 20:21:15 +01:00
BlueWall 7b66ef44c3 Add some info about xbuild command line switches to clean and select between producing Debug or Release binaries 2014-06-10 20:21:09 +01:00
Justin Clark-Casey dcbe9d1ffb Merge branch 'master' into 0.8-post-fixes 2014-05-27 23:42:20 +01:00
Justin Clark-Casey 3a477a29d7 Change release flavour to RC2 2014-05-27 23:38:08 +01:00
Justin Clark-Casey 3f703ae1cb Merge branch 'master' into 0.8-post-fixes 2014-05-27 23:29:54 +01:00
Justin Clark-Casey c38736de82 Merge branch 'master' into 0.8-post-fixes 2014-05-06 19:57:31 +01:00
Justin Clark-Casey 766c94213c Change version flavour to RC1. Make version number more normal "0.8" rather than "0.8.0" 2014-05-06 19:04:44 +01:00
148 changed files with 3136 additions and 1355 deletions

1
.gitignore vendored
View File

@ -54,6 +54,7 @@ bin/Regions/*
bin/UserAssets
bin/assetcache
bin/maptiles
bin/bakes
bin/estate_settings.xml
bin/config-include/CenomeCache.ini
bin/config-include/FlotsamCache.ini

View File

@ -19,10 +19,14 @@ Prereqs:
From the distribution type:
* ./runprebuild.sh
* nant (or xbuild)
* nant (or !* xbuild)
* cd bin
* copy OpenSim.ini.example to OpenSim.ini and other appropriate files in bin/config-include
* run mono OpenSim.exe
!* xbuild option switches
!* clean: xbuild /target:clean
!* debug: (default) xbuild /property:Configuration=Debug
!* release: xbuild /property:Configuration=Release
# Using Monodevelop

View File

@ -68,6 +68,7 @@ what it is today.
* alex_carnell
* Alan Webb (IBM)
* Aleric
* Alicia Raven
* Allen Kerensky
* BigFootAg
* BlueWall Slade

View File

@ -174,7 +174,7 @@ namespace OpenSim.Groups
if (dict.ContainsKey("ServiceLocation") && dict["ServiceLocation"] != null)
grec.ServiceLocation = dict["ServiceLocation"].ToString();
else
grec.GroupName = string.Empty;
grec.ServiceLocation = string.Empty;
if (dict.ContainsKey("ShownInList") && dict["ShownInList"] != null)
grec.ShowInList = bool.Parse(dict["ShownInList"].ToString());

View File

@ -325,6 +325,13 @@ namespace OpenSim.Groups
im.RegionID = thisClient.Scene.RegionInfo.RegionID.Guid;
}
if ((im.binaryBucket == 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)
im.binaryBucket = Util.StringToBytes256(groupInfo.GroupName);
}
// Send to self first of all
im.toAgentID = im.fromAgentID;
im.fromGroup = true;

View File

@ -209,11 +209,13 @@ namespace OpenSim.Groups
string agentID = request["AgentID"].ToString();
string token = request["AccessToken"].ToString();
m_GroupsService.RemoveAgentFromGroup(agentID, agentID, groupID, token);
if (!m_GroupsService.RemoveAgentFromGroup(agentID, agentID, groupID, token))
NullResult(result, "Internal error");
else
result["RESULT"] = "true";
}
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
result["RESULT"] = "true";
return Util.UTF8NoBomEncoding.GetBytes(ServerUtils.BuildXmlResponse(result));
}

View File

@ -109,7 +109,7 @@ namespace OpenSim.Groups
string method = request["METHOD"].ToString();
request.Remove("METHOD");
m_log.DebugFormat("[Groups.Handler]: {0}", method);
// m_log.DebugFormat("[Groups.Handler]: {0}", method);
switch (method)
{
case "PUTGROUP":
@ -285,11 +285,13 @@ namespace OpenSim.Groups
string agentID = request["AgentID"].ToString();
string requestingAgentID = request["RequestingAgentID"].ToString();
m_GroupsService.RemoveAgentFromGroup(requestingAgentID, agentID, groupID);
if (!m_GroupsService.RemoveAgentFromGroup(requestingAgentID, agentID, groupID))
NullResult(result, string.Format("Insufficient permissions.", agentID));
else
result["RESULT"] = "true";
}
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
result["RESULT"] = "true";
return Util.UTF8NoBomEncoding.GetBytes(ServerUtils.BuildXmlResponse(result));
}
@ -665,7 +667,11 @@ namespace OpenSim.Groups
GroupInviteInfo invite = m_GroupsService.GetAgentToGroupInvite(request["RequestingAgentID"].ToString(),
new UUID(request["InviteID"].ToString()));
result["RESULT"] = GroupsDataUtils.GroupInviteInfo(invite);
if (invite != null)
result["RESULT"] = GroupsDataUtils.GroupInviteInfo(invite);
else
result["RESULT"] = "NULL";
return Util.UTF8NoBomEncoding.GetBytes(ServerUtils.BuildXmlResponse(result));
}

View File

@ -393,13 +393,15 @@ namespace OpenSim.Groups
return true;
}
public void RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
public bool RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// check perms
if (RequestingAgentID != AgentID && !HasPower(RequestingAgentID, GroupID, GroupPowers.Eject))
return;
return false;
_RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID);
return true;
}
public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, string agentID)

View File

@ -131,19 +131,27 @@ namespace OpenSim.Groups
return true;
}
public void RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID, string token)
public bool RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID, string token)
{
// check the token
MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID);
if (membership != null)
{
if (token != string.Empty && token.Equals(membership.Data["AccessToken"]))
RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID);
{
return RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID);
}
else
{
m_log.DebugFormat("[Groups.HGGroupsService]: access token {0} did not match stored one {1}", token, membership.Data["AccessToken"]);
return false;
}
}
else
{
m_log.DebugFormat("[Groups.HGGroupsService]: membership not found for {0}", AgentID);
return false;
}
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string groupName, string token)

View File

@ -215,18 +215,7 @@ namespace OpenSim.OfflineIM
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
return Util.DocToBytes(doc);
}
#endregion

View File

@ -32,6 +32,7 @@ using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
@ -45,6 +46,12 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Controls whether we load modules from Mono.Addins.
/// </summary>
/// <remarks>For debug purposes. Defaults to true.</remarks>
public bool LoadModulesFromAddins { get; set; }
// Config access
private OpenSimBase m_openSim;
@ -61,6 +68,11 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
private List<ISharedRegionModule> m_sharedInstances =
new List<ISharedRegionModule>();
public RegionModulesControllerPlugin()
{
LoadModulesFromAddins = true;
}
#region IApplicationPlugin implementation
public void Initialise (OpenSimBase openSim)
@ -69,6 +81,9 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this);
m_log.DebugFormat("[REGIONMODULES]: Initializing...");
if (!LoadModulesFromAddins)
return;
// Who we are
string id = AddinManager.CurrentAddin.Id;
@ -88,40 +103,8 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
Dictionary<RuntimeAddin, IList<int>> loadedModules = new Dictionary<RuntimeAddin, IList<int>>();
// Scan modules and load all that aren't disabled
foreach (TypeExtensionNode node in
AddinManager.GetExtensionNodes("/OpenSim/RegionModules"))
{
IList<int> loadedModuleData;
if (!loadedModules.ContainsKey(node.Addin))
loadedModules.Add(node.Addin, new List<int> { 0, 0, 0 });
loadedModuleData = loadedModules[node.Addin];
if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null)
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type);
m_sharedModules.Add(node);
loadedModuleData[0]++;
}
}
else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null)
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type);
m_nonSharedModules.Add(node);
loadedModuleData[1]++;
}
}
else
{
m_log.WarnFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type);
loadedModuleData[2]++;
}
}
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/OpenSim/RegionModules"))
AddNode(node, modulesConfig, loadedModules);
foreach (KeyValuePair<RuntimeAddin, IList<int>> loadedModuleData in loadedModules)
{
@ -194,6 +177,41 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
#region IPlugin implementation
private void AddNode(
TypeExtensionNode node, IConfig modulesConfig, Dictionary<RuntimeAddin, IList<int>> loadedModules)
{
IList<int> loadedModuleData;
if (!loadedModules.ContainsKey(node.Addin))
loadedModules.Add(node.Addin, new List<int> { 0, 0, 0 });
loadedModuleData = loadedModules[node.Addin];
if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null)
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type);
m_sharedModules.Add(node);
loadedModuleData[0]++;
}
}
else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null)
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type);
m_nonSharedModules.Add(node);
loadedModuleData[1]++;
}
}
else
{
m_log.WarnFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type);
loadedModuleData[2]++;
}
}
// We don't do that here
//
public void Initialise ()
@ -215,6 +233,7 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
m_sharedInstances[0].Close();
m_sharedInstances.RemoveAt(0);
}
m_sharedModules.Clear();
m_nonSharedModules.Clear();
}

View File

@ -162,6 +162,9 @@ namespace OpenSim.ApplicationPlugins.RemoteController
availableMethods["admin_acl_list"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListList);
availableMethods["admin_estate_reload"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcEstateReload);
// Land management
availableMethods["admin_reset_land"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcResetLand);
// Either enable full remote functionality or just selected features
string enabledMethods = m_config.GetString("enabled_methods", "all");
@ -2063,6 +2066,56 @@ namespace OpenSim.ApplicationPlugins.RemoteController
responseData["success"] = true;
}
private void XmlRpcResetLand(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable responseData = (Hashtable)response.Value;
string musicURL = string.Empty;
UUID groupID = UUID.Zero;
uint flags = 0;
bool set_group = false, set_music = false, set_flags = false;
if (requestData.Contains("group") && requestData["group"] != null)
set_group = UUID.TryParse(requestData["group"].ToString(), out groupID);
if (requestData.Contains("music") && requestData["music"] != null)
{
musicURL = requestData["music"].ToString();
set_music = true;
}
if (requestData.Contains("flags") && requestData["flags"] != null)
set_flags = UInt32.TryParse(requestData["flags"].ToString(), out flags);
m_log.InfoFormat("[RADMIN]: Received Reset Land Request group={0} musicURL={1} flags={2}",
(set_group ? groupID.ToString() : "unchanged"),
(set_music ? musicURL : "unchanged"),
(set_flags ? flags.ToString() : "unchanged"));
m_application.SceneManager.ForEachScene(delegate(Scene s)
{
List<ILandObject> parcels = s.LandChannel.AllParcels();
foreach (ILandObject p in parcels)
{
if (set_music)
p.LandData.MusicURL = musicURL;
if (set_group)
p.LandData.GroupID = groupID;
if (set_flags)
p.LandData.Flags = flags;
s.LandChannel.UpdateLandObject(p.LandData.LocalID, p.LandData);
}
}
);
responseData["success"] = true;
m_log.Info("[RADMIN]: Reset Land Request complete");
}
/// <summary>
/// Parse a float with the given parameter name from a request data hash table.
/// </summary>

View File

@ -52,7 +52,7 @@ namespace OpenSim.Capabilities.Handlers.GetTexture.Tests
// Overkill - we only really need the asset service, not a whole scene.
Scene scene = new SceneHelpers().SetupScene();
GetTextureHandler handler = new GetTextureHandler(null, scene.AssetService, "TestGetTexture", null, null);
GetTextureHandler handler = new GetTextureHandler("/gettexture", scene.AssetService, "TestGetTexture", null, null);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
req.Url = new Uri("http://localhost/?texture_id=00000000-0000-1111-9999-000000000012");

View File

@ -68,7 +68,10 @@ namespace OpenSim.Framework.Capabilities
/// <returns></returns>
public static object LLSDDeserialize(byte[] b)
{
return LLSDDeserialize(new MemoryStream(b, false));
using (MemoryStream ms = new MemoryStream(b, false))
{
return LLSDDeserialize(ms);
}
}
/// <summary>
@ -78,21 +81,23 @@ namespace OpenSim.Framework.Capabilities
/// <returns></returns>
public static object LLSDDeserialize(Stream st)
{
XmlTextReader reader = new XmlTextReader(st);
reader.Read();
SkipWS(reader);
using (XmlTextReader reader = new XmlTextReader(st))
{
reader.Read();
SkipWS(reader);
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd")
throw new LLSDParseException("Expected <llsd>");
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd")
throw new LLSDParseException("Expected <llsd>");
reader.Read();
object ret = LLSDParseOne(reader);
SkipWS(reader);
reader.Read();
object ret = LLSDParseOne(reader);
SkipWS(reader);
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd")
throw new LLSDParseException("Expected </llsd>");
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd")
throw new LLSDParseException("Expected </llsd>");
return ret;
return ret;
}
}
/// <summary>

View File

@ -29,7 +29,7 @@ using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Region.Framework.Interfaces
namespace OpenSim.Data
{
public interface IEstateDataStore
{

View File

@ -52,12 +52,12 @@ namespace OpenSim.Data
public int sizeY;
/// <summary>
/// Return the x-coordinate of this region.
/// Return the x-coordinate of this region in region units.
/// </summary>
public int coordX { get { return (int)Util.WorldToRegionLoc((uint)posX); } }
/// <summary>
/// Return the y-coordinate of this region.
/// Return the y-coordinate of this region in region units.
/// </summary>
public int coordY { get { return (int)Util.WorldToRegionLoc((uint)posY); } }

View File

@ -145,7 +145,11 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
return DoLoad(cmd, regionID, create);
EstateSettings e = DoLoad(cmd, regionID, create);
if (!create && e.EstateID == 0) // Not found
return null;
return e;
}
}
@ -427,7 +431,10 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?EstateID", estateID);
return DoLoad(cmd, UUID.Zero, false);
EstateSettings e = DoLoad(cmd, UUID.Zero, false);
if (e.EstateID != estateID)
return null;
return e;
}
}

View File

@ -250,7 +250,7 @@ namespace OpenSim.Data.MySQL
string query = string.Empty;
query += "DELETE FROM classifieds WHERE ";
query += "classifieduuid = ?ClasifiedId";
query += "classifieduuid = ?recordId";
try
{
@ -260,12 +260,8 @@ namespace OpenSim.Data.MySQL
using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
{
cmd.Parameters.AddWithValue("?ClassifiedId", recordId.ToString());
lock(Lock)
{
cmd.ExecuteNonQuery();
}
cmd.Parameters.AddWithValue("?recordId", recordId.ToString());
cmd.ExecuteNonQuery();
}
}
}

View File

@ -239,7 +239,7 @@ namespace OpenSim.Data.SQLite
if (inventoryRow == null)
{
if (! add)
m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID);
m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existent inventory folder: {0}", folder.ID);
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
@ -298,7 +298,7 @@ namespace OpenSim.Data.SQLite
if (inventoryRow == null)
{
if (!add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID);
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existent inventory item: {0}", item.ID);
inventoryRow = inventoryItemTable.NewRow();
fillItemRow(inventoryRow, item);

View File

@ -520,6 +520,12 @@ namespace OpenSim.Framework
if (!m_attachments.ContainsKey(attach.AttachPoint))
m_attachments[attach.AttachPoint] = new List<AvatarAttachment>();
foreach (AvatarAttachment prev in m_attachments[attach.AttachPoint])
{
if (prev.ItemID == attach.ItemID)
return;
}
m_attachments[attach.AttachPoint].Add(attach);
}
}

View File

@ -54,6 +54,7 @@ namespace OpenSim.Framework
public int assetThrottle;
public int textureThrottle;
public int totalThrottle;
public int maxThrottle;
public Dictionary<string, int> SyncRequests = new Dictionary<string,int>();
public Dictionary<string, int> AsyncRequests = new Dictionary<string,int>();

View File

@ -0,0 +1,256 @@
/*
* 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.Linq;
using System.Net;
using System.Reflection;
using log4net;
using LukeSkywalker.IPNetwork;
using Nini.Config;
namespace OpenSim.Framework.Communications
{
public class OutboundUrlFilter
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get; private set; }
private List<IPNetwork> m_blacklistNetworks;
private List<IPEndPoint> m_blacklistEndPoints;
private List<IPNetwork> m_blacklistExceptionNetworks;
private List<IPEndPoint> m_blacklistExceptionEndPoints;
public OutboundUrlFilter(
string name,
List<IPNetwork> blacklistNetworks, List<IPEndPoint> blacklistEndPoints,
List<IPNetwork> blacklistExceptionNetworks, List<IPEndPoint> blacklistExceptionEndPoints)
{
Name = name;
m_blacklistNetworks = blacklistNetworks;
m_blacklistEndPoints = blacklistEndPoints;
m_blacklistExceptionNetworks = blacklistExceptionNetworks;
m_blacklistExceptionEndPoints = blacklistExceptionEndPoints;
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenSim.Framework.Communications.OutboundUrlFilter"/> class.
/// </summary>
/// <param name="name">Name of the filter for logging purposes.</param>
/// <param name="config">Filter configuration</param>
public OutboundUrlFilter(string name, IConfigSource config)
{
Name = name;
string configBlacklist
= "0.0.0.0/8|10.0.0.0/8|100.64.0.0/10|127.0.0.0/8|169.254.0.0/16|172.16.0.0/12|192.0.0.0/24|192.0.2.0/24|192.88.99.0/24|192.168.0.0/16|198.18.0.0/15|198.51.100.0/24|203.0.113.0/24|224.0.0.0/4|240.0.0.0/4|255.255.255.255/32";
string configBlacklistExceptions = "";
IConfig networkConfig = config.Configs["Network"];
if (networkConfig != null)
{
configBlacklist = networkConfig.GetString("OutboundDisallowForUserScripts", configBlacklist);
configBlacklistExceptions
= networkConfig.GetString("OutboundDisallowForUserScriptsExcept", configBlacklistExceptions);
}
m_log.DebugFormat(
"[OUTBOUND URL FILTER]: OutboundDisallowForUserScripts for {0} is [{1}]", Name, configBlacklist);
m_log.DebugFormat(
"[OUTBOUND URL FILTER]: OutboundDisallowForUserScriptsExcept for {0} is [{1}]", Name, configBlacklistExceptions);
OutboundUrlFilter.ParseConfigList(
configBlacklist, Name, out m_blacklistNetworks, out m_blacklistEndPoints);
OutboundUrlFilter.ParseConfigList(
configBlacklistExceptions, Name, out m_blacklistExceptionNetworks, out m_blacklistExceptionEndPoints);
}
private static void ParseConfigList(
string fullConfigEntry, string filterName, out List<IPNetwork> networks, out List<IPEndPoint> endPoints)
{
// Parse blacklist
string[] configBlacklistEntries
= fullConfigEntry.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
configBlacklistEntries = configBlacklistEntries.Select(e => e.Trim()).ToArray();
networks = new List<IPNetwork>();
endPoints = new List<IPEndPoint>();
foreach (string configEntry in configBlacklistEntries)
{
if (configEntry.Contains("/"))
{
IPNetwork network;
if (!IPNetwork.TryParse(configEntry, out network))
{
m_log.ErrorFormat(
"[OUTBOUND URL FILTER]: Entry [{0}] is invalid network for {1}", configEntry, filterName);
continue;
}
networks.Add(network);
}
else
{
Uri configEntryUri;
if (!Uri.TryCreate("http://" + configEntry, UriKind.Absolute, out configEntryUri))
{
m_log.ErrorFormat(
"[OUTBOUND URL FILTER]: EndPoint entry [{0}] is invalid endpoint for {1}",
configEntry, filterName);
continue;
}
IPAddress[] addresses = Dns.GetHostAddresses(configEntryUri.Host);
foreach (IPAddress addr in addresses)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Found address [{0}] in config", addr);
IPEndPoint configEntryEp = new IPEndPoint(addr, configEntryUri.Port);
endPoints.Add(configEntryEp);
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Added blacklist exception [{0}]", configEntryEp);
}
}
}
}
}
/// <summary>
/// Determines if an url is in a list of networks and endpoints.
/// </summary>
/// <returns></returns>
/// <param name="url">IP address</param>
/// <param name="port"></param>
/// <param name="networks">Networks.</param>
/// <param name="endPoints">End points.</param>
/// <param name="filterName">Filter name.</param>
private static bool IsInNetwork(
IPAddress addr, int port, List<IPNetwork> networks, List<IPEndPoint> endPoints, string filterName)
{
foreach (IPNetwork ipn in networks)
{
// m_log.DebugFormat(
// "[OUTBOUND URL FILTER]: Checking [{0}] against network [{1}]", addr, ipn);
if (IPNetwork.Contains(ipn, addr))
{
// m_log.DebugFormat(
// "[OUTBOUND URL FILTER]: Found [{0}] in network [{1}]", addr, ipn);
return true;
}
}
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Found address [{0}]", addr);
foreach (IPEndPoint ep in endPoints)
{
// m_log.DebugFormat(
// "[OUTBOUND URL FILTER]: Checking [{0}:{1}] against endpoint [{2}]",
// addr, port, ep);
if (addr.Equals(ep.Address) && port == ep.Port)
{
// m_log.DebugFormat(
// "[OUTBOUND URL FILTER]: Found [{0}:{1}] in endpoint [{2}]", addr, port, ep);
return true;
}
}
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Did not find [{0}:{1}] in list", addr, port);
return false;
}
/// <summary>
/// Checks whether the given url is allowed by the filter.
/// </summary>
/// <returns></returns>
public bool CheckAllowed(Uri url)
{
bool allowed = true;
// Check that we are permitted to make calls to this endpoint.
bool foundIpv4Address = false;
IPAddress[] addresses = Dns.GetHostAddresses(url.Host);
foreach (IPAddress addr in addresses)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Found address [{0}]", addr);
foundIpv4Address = true;
// Check blacklist
if (OutboundUrlFilter.IsInNetwork(addr, url.Port, m_blacklistNetworks, m_blacklistEndPoints, Name))
{
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Found [{0}] in blacklist for {1}", url, Name);
// Check blacklist exceptions
allowed
= OutboundUrlFilter.IsInNetwork(
addr, url.Port, m_blacklistExceptionNetworks, m_blacklistExceptionEndPoints, Name);
// if (allowed)
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Found [{0}] in whitelist for {1}", url, Name);
}
}
// Found at least one address in a blacklist and not a blacklist exception
if (!allowed)
return false;
// else
// m_log.DebugFormat("[OUTBOUND URL FILTER]: URL [{0}] not in blacklist for {1}", url, Name);
}
// We do not know how to handle IPv6 securely yet.
if (!foundIpv4Address)
return false;
// m_log.DebugFormat("[OUTBOUND URL FILTER]: Allowing request [{0}]", url);
return allowed;
}
}
}

View File

@ -56,7 +56,7 @@ namespace OpenSim.Framework.Communications
/// other threads to execute, while it waits for a response from the web-service. RestClient itself can be
/// invoked by the caller in either synchronous mode or asynchronous modes.
/// </remarks>
public class RestClient
public class RestClient : IDisposable
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@ -148,6 +148,33 @@ namespace OpenSim.Framework.Communications
#endregion constructors
#region Dispose
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
_resource.Dispose();
}
disposed = true;
}
#endregion Dispose
/// <summary>
/// Add a path element to the query, e.g. assets
/// </summary>
@ -296,6 +323,14 @@ namespace OpenSim.Framework.Communications
#endregion Async communications with server
/// <summary>
/// Perform a synchronous request
/// </summary>
public Stream Request()
{
return Request(null);
}
/// <summary>
/// Perform a synchronous request
/// </summary>
@ -312,6 +347,10 @@ namespace OpenSim.Framework.Communications
if (auth != null)
auth.AddAuthorization(_request.Headers);
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
try
{
@ -358,6 +397,9 @@ namespace OpenSim.Framework.Communications
_resource.Seek(0, SeekOrigin.Begin);
}
if (WebUtil.DebugLevel >= 5)
WebUtil.LogResponseDetail(reqnum, _resource);
return _resource;
}
}
@ -374,16 +416,18 @@ namespace OpenSim.Framework.Communications
if (auth != null)
auth.AddAuthorization(_request.Headers);
m_log.InfoFormat("[REST]: Request Length {0}", _request.ContentLength);
m_log.InfoFormat("[REST]: Sending Web Request {0}", buildUri());
src.Seek(0, SeekOrigin.Begin);
m_log.Info("[REST]: Seek is ok");
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);
Stream dst = _request.GetRequestStream();
m_log.Info("[REST]: GetRequestStream is ok");
byte[] buf = new byte[1024];
int length = src.Read(buf, 0, 1024);
m_log.Info("[REST]: First Read is ok");
while (length > 0)
{
dst.Write(buf, 0, length);
@ -398,14 +442,29 @@ namespace OpenSim.Framework.Communications
{
m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}",
RequestMethod, _request.RequestUri, e.Status, e.Message);
return null;
}
catch (Exception e)
{
m_log.WarnFormat(
"[REST]: Request {0} {1} failed with exception {2} {3}",
RequestMethod, _request.RequestUri, e.Message, e.StackTrace);
return null;
}
if (WebUtil.DebugLevel >= 5)
{
using (Stream responseStream = _response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseStr = reader.ReadToEnd();
WebUtil.LogResponseDetail(reqnum, responseStr);
}
}
}
_response.Close();
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);

View File

@ -28,6 +28,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using OpenMetaverse;
namespace OpenSim.Framework
@ -411,5 +412,23 @@ namespace OpenSim.Framework
{
return l_EstateGroups.Contains(groupID);
}
public Dictionary<string, object> ToMap()
{
Dictionary<string, object> map = new Dictionary<string, object>();
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in properties)
map[p.Name] = p.GetValue(this, null);
return map;
}
public EstateSettings(Dictionary<string, object> map)
{
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in properties)
p.SetValue(this, map[p.Name], null);
}
}
}

View File

@ -141,19 +141,19 @@ namespace OpenSim.Framework.Monitoring
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, Util.IsWindows() ? 1 : -1); },
StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
RegisteredStats.Add(tempName, tempStat);
MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; });
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); });
MakeStat("UserProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().UserProcessorTime.TotalSeconds; });
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().UserProcessorTime.TotalSeconds, 3); });
MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds; });
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds, 3); });
MakeStat("Threads", null, "threads", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
@ -253,11 +253,8 @@ namespace OpenSim.Framework.Monitoring
// "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
// "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
private delegate double PerfCounterNextValue();
private void GetNextValue(Stat stat, PerfCounterControl perfControl)
{
GetNextValue(stat, perfControl, 1.0);
}
private void GetNextValue(Stat stat, PerfCounterControl perfControl, double factor)
{
if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
{
@ -265,16 +262,13 @@ namespace OpenSim.Framework.Monitoring
{
try
{
// Kludge for factor to run double duty. If -1, subtract the value from one
if (factor == -1)
stat.Value = 1 - perfControl.perfCounter.NextValue();
else
stat.Value = perfControl.perfCounter.NextValue() / factor;
stat.Value = Math.Round(perfControl.perfCounter.NextValue(), 3);
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
}
perfControl.lastFetch = Util.EnvironmentTickCount();
}
}

View File

@ -70,18 +70,18 @@ namespace OpenSim.Framework.Monitoring
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length != 4)
if (cmd.Length != 3)
{
con.Output("Usage: debug stats record start|stop");
con.Output("Usage: stats record start|stop");
return;
}
if (cmd[3] == "start")
if (cmd[2] == "start")
{
Start();
con.OutputFormat("Now recording all stats to file every {0}ms", m_statsLogIntervalMs);
}
else if (cmd[3] == "stop")
else if (cmd[2] == "stop")
{
Stop();
con.Output("Stopped recording stats to file.");

View File

@ -101,7 +101,6 @@ namespace OpenSim.Framework
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[REGION INFO]";
public bool commFailTF = false;
public string RegionFile = String.Empty;
public bool isSandbox = false;
public bool Persistent = true;
@ -147,8 +146,29 @@ namespace OpenSim.Framework
public uint WorldLocX = 0;
public uint WorldLocY = 0;
public uint WorldLocZ = 0;
/// <summary>
/// X dimension of the region.
/// </summary>
/// <remarks>
/// If this is a varregion then the default size set here will be replaced when we load the region config.
/// </remarks>
public uint RegionSizeX = Constants.RegionSize;
/// <summary>
/// X dimension of the region.
/// </summary>
/// <remarks>
/// If this is a varregion then the default size set here will be replaced when we load the region config.
/// </remarks>
public uint RegionSizeY = Constants.RegionSize;
/// <summary>
/// Z dimension of the region.
/// </summary>
/// <remarks>
/// XXX: Unknown if this accounts for regions with negative Z.
/// </remarks>
public uint RegionSizeZ = Constants.RegionHeight;
private Dictionary<String, String> m_extraSettings = new Dictionary<string, string>();
@ -860,11 +880,6 @@ namespace OpenSim.Framework
config.Set("MaptileStaticFile", MaptileStaticFile);
}
public bool ignoreIncomingConfiguration(string configuration_key, object configuration_result)
{
return true;
}
public void SaveRegionToFile(string description, string filename)
{
if (filename.ToLower().EndsWith(".ini"))

View File

@ -45,6 +45,7 @@ using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Timer=System.Timers.Timer;
using Nini.Config;
namespace OpenSim.Framework.Servers
{
@ -55,10 +56,16 @@ namespace OpenSim.Framework.Servers
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Used by tests to suppress Environment.Exit(0) so that post-run operations are possible.
/// </summary>
public bool SuppressExit { get; set; }
/// <summary>
/// This will control a periodic log printout of the current 'show stats' (if they are active) for this
/// server.
/// </summary>
private int m_periodDiagnosticTimerMS = 60 * 60 * 1000;
private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
/// <summary>
@ -77,8 +84,6 @@ namespace OpenSim.Framework.Servers
// Random uuid for private data
m_osSecret = UUID.Random().ToString();
m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
m_periodicDiagnosticsTimer.Enabled = true;
}
/// <summary>
@ -89,6 +94,16 @@ namespace OpenSim.Framework.Servers
StatsManager.SimExtraStats = new SimExtraStatsCollector();
RegisterCommonCommands();
RegisterCommonComponents(Config);
IConfig startupConfig = Config.Configs["Startup"];
int logShowStatsSeconds = startupConfig.GetInt("LogShowStatsSeconds", m_periodDiagnosticTimerMS / 1000);
m_periodDiagnosticTimerMS = logShowStatsSeconds * 1000;
m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
if (m_periodDiagnosticTimerMS != 0)
{
m_periodicDiagnosticsTimer.Interval = m_periodDiagnosticTimerMS;
m_periodicDiagnosticsTimer.Enabled = true;
}
}
protected override void ShutdownSpecific()
@ -99,7 +114,8 @@ namespace OpenSim.Framework.Servers
base.ShutdownSpecific();
Environment.Exit(0);
if (!SuppressExit)
Environment.Exit(0);
}
/// <summary>

View File

@ -832,28 +832,40 @@ namespace OpenSim.Framework.Servers.HttpServer
return; // never log these; they're just binary data
Stream inputStream = Util.Copy(request.InputStream);
if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
inputStream = new GZipStream(inputStream, System.IO.Compression.CompressionMode.Decompress);
using (StreamReader reader = new StreamReader(inputStream, Encoding.UTF8))
Stream innerStream = null;
try
{
string output;
if (DebugLevel == 5)
if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
{
char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed
int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1);
output = new string(chars, 0, Math.Min(len, WebUtil.MaxRequestDiagLength));
if (len > WebUtil.MaxRequestDiagLength)
output += "...";
}
else
{
output = reader.ReadToEnd();
innerStream = inputStream;
inputStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress);
}
m_log.DebugFormat("[LOGHTTP] {0}", Util.BinaryToASCII(output));
using (StreamReader reader = new StreamReader(inputStream, Encoding.UTF8))
{
string output;
if (DebugLevel == 5)
{
char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed
int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1);
output = new string(chars, 0, Math.Min(len, WebUtil.MaxRequestDiagLength));
if (len > WebUtil.MaxRequestDiagLength)
output += "...";
}
else
{
output = reader.ReadToEnd();
}
m_log.DebugFormat("[LOGHTTP] {0}", Util.BinaryToASCII(output));
}
}
finally
{
if (innerStream != null)
innerStream.Dispose();
inputStream.Dispose();
}
}
@ -981,19 +993,33 @@ namespace OpenSim.Framework.Servers.HttpServer
/// <param name="response"></param>
private byte[] HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
{
String requestBody;
Stream requestStream = request.InputStream;
Stream innerStream = null;
try
{
if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
{
innerStream = requestStream;
requestStream = new GZipStream(innerStream, System.IO.Compression.CompressionMode.Decompress);
}
if ((request.Headers["Content-Encoding"] == "gzip") || (request.Headers["X-Content-Encoding"] == "gzip"))
requestStream = new GZipStream(requestStream, System.IO.Compression.CompressionMode.Decompress);
using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8))
{
requestBody = reader.ReadToEnd();
}
}
finally
{
if (innerStream != null)
innerStream.Dispose();
requestStream.Dispose();
}
Encoding encoding = Encoding.UTF8;
StreamReader reader = new StreamReader(requestStream, encoding);
string requestBody = reader.ReadToEnd();
reader.Close();
requestStream.Close();
//m_log.Debug(requestBody);
requestBody = requestBody.Replace("<base64></base64>", "");
string responseString = String.Empty;
XmlRpcRequest xmlRprcRequest = null;
@ -1089,18 +1115,16 @@ namespace OpenSim.Framework.Servers.HttpServer
response.ContentType = "text/xml";
using (MemoryStream outs = new MemoryStream())
using (XmlTextWriter writer = new XmlTextWriter(outs, Encoding.UTF8))
{
using (XmlTextWriter writer = new XmlTextWriter(outs, Encoding.UTF8))
writer.Formatting = Formatting.None;
XmlRpcResponseSerializer.Singleton.Serialize(writer, xmlRpcResponse);
writer.Flush();
outs.Flush();
outs.Position = 0;
using (StreamReader sr = new StreamReader(outs))
{
writer.Formatting = Formatting.None;
XmlRpcResponseSerializer.Singleton.Serialize(writer, xmlRpcResponse);
writer.Flush();
outs.Flush();
outs.Position = 0;
using (StreamReader sr = new StreamReader(outs))
{
responseString = sr.ReadToEnd();
}
responseString = sr.ReadToEnd();
}
}
}

View File

@ -26,6 +26,7 @@
*/
using System;
using OpenSim.Framework.Monitoring;
namespace OpenSim.Framework.Servers.HttpServer
{
@ -61,6 +62,24 @@ namespace OpenSim.Framework.Servers.HttpServer
Description = description;
m_httpMethod = httpMethod;
m_path = path;
// FIXME: A very temporary measure to stop the simulator stats being overwhelmed with user CAPS info.
// Needs to be fixed properly in stats display
if (!path.StartsWith("/CAPS/"))
{
StatsManager.RegisterStat(
new Stat(
"requests",
"requests",
"Number of requests received by this service endpoint",
"requests",
"service",
string.Format("{0}:{1}", httpMethod, path),
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
s => s.Value = RequestsReceived,
StatVerbosity.Debug));
}
}
public virtual string Path

View File

@ -56,12 +56,17 @@ namespace OpenSim.Framework.Servers.HttpServer
string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
RequestsReceived++;
if (m_Auth != null && !m_Auth.Authenticate(httpRequest.Headers, httpResponse.AddHeader))
if (m_Auth != null)
{
httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
httpResponse.ContentType = "text/plain";
return new byte[0];
HttpStatusCode statusCode;
if (!m_Auth.Authenticate(httpRequest.Headers, httpResponse.AddHeader, out statusCode))
{
httpResponse.StatusCode = (int)statusCode;
httpResponse.ContentType = "text/plain";
return new byte[0];
}
}
byte[] result = ProcessRequest(path, request, httpRequest, httpResponse);

View File

@ -52,23 +52,25 @@ namespace OpenSim.Framework.Servers.HttpServer
request.Method = verb;
request.ContentType = "text/xml";
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
using (MemoryStream buffer = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer.ToArray(), 0, length);
}
int length = (int) buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
// IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
request.BeginGetResponse(AsyncCallback, request);
}

View File

@ -60,24 +60,25 @@ namespace OpenSim.Framework.Servers.HttpServer
request.ContentType = "text/xml";
request.Timeout = 10000;
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
using (MemoryStream buffer = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer.ToArray(), 0, length);
}
int length = (int) buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
// IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
request.BeginGetResponse(AsyncCallback, request);
}

View File

@ -77,26 +77,25 @@ namespace OpenSim.Framework.Servers.HttpServer
request.ContentType = "text/xml";
request.Timeout = 20000;
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
using (MemoryStream buffer = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, sobj);
writer.Flush();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, sobj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer.ToArray(), 0, length);
}
int length = (int)buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
buffer.Close();
requestStream.Close();
TResponse deserial = default(TResponse);
using (WebResponse resp = request.GetResponse())
{
@ -133,25 +132,25 @@ namespace OpenSim.Framework.Servers.HttpServer
request.ContentType = "text/xml";
request.Timeout = 10000;
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
using (MemoryStream buffer = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, sobj);
writer.Flush();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, sobj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer.ToArray(), 0, length);
}
buffer.Close();
int length = (int)buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
// IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
request.BeginGetResponse(AsyncCallback, request);
}

View File

@ -29,8 +29,8 @@ namespace OpenSim
{
public class VersionInfo
{
private const string VERSION_NUMBER = "0.8.0";
private const Flavour VERSION_FLAVOUR = Flavour.Dev;
private const string VERSION_NUMBER = "0.8.0.4";
private const Flavour VERSION_FLAVOUR = Flavour.Release;
public enum Flavour
{
@ -38,6 +38,7 @@ namespace OpenSim
Dev,
RC1,
RC2,
RC3,
Release,
Post_Fixes,
Extended

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
using Nini.Config;
@ -55,24 +56,28 @@ namespace OpenSim.Framework.ServiceAuth
return false;
}
public bool Authenticate(NameValueCollection requestHeaders, AddHeaderDelegate d)
public bool Authenticate(NameValueCollection requestHeaders, AddHeaderDelegate d, out HttpStatusCode statusCode)
{
//m_log.DebugFormat("[HTTP BASIC AUTH]: Authenticate in {0}", remove_me);
if (requestHeaders != null)
// m_log.DebugFormat("[HTTP BASIC AUTH]: Authenticate in {0}", "BasicHttpAuthentication");
string value = requestHeaders.Get("Authorization");
if (value != null)
{
string value = requestHeaders.Get("Authorization");
if (value != null)
value = value.Trim();
if (value.StartsWith("Basic "))
{
value = value.Trim();
if (value.StartsWith("Basic "))
value = value.Replace("Basic ", string.Empty);
if (Authenticate(value))
{
value = value.Replace("Basic ", string.Empty);
if (Authenticate(value))
return true;
statusCode = HttpStatusCode.OK;
return true;
}
}
}
d("WWW-Authenticate", "Basic realm = \"Asset Server\"");
statusCode = HttpStatusCode.Unauthorized;
return false;
}
}

View File

@ -0,0 +1,71 @@
/*
* 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.Collections.Specialized;
using System.Linq;
using System.Net;
namespace OpenSim.Framework.ServiceAuth
{
public class CompoundAuthentication : IServiceAuth
{
private List<IServiceAuth> m_authentications = new List<IServiceAuth>();
public int Count { get { return m_authentications.Count; } }
public void AddAuthenticator(IServiceAuth auth)
{
m_authentications.Add(auth);
}
public void RemoveAuthenticator(IServiceAuth auth)
{
m_authentications.Remove(auth);
}
public void AddAuthorization(NameValueCollection headers) {}
public bool Authenticate(string data)
{
return m_authentications.TrueForAll(a => a.Authenticate(data));
}
public bool Authenticate(NameValueCollection requestHeaders, AddHeaderDelegate d, out HttpStatusCode statusCode)
{
foreach (IServiceAuth auth in m_authentications)
{
if (!auth.Authenticate(requestHeaders, d, out statusCode))
return false;
}
statusCode = HttpStatusCode.OK;
return true;
}
}
}

View File

@ -0,0 +1,57 @@
/*
* 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.Specialized;
using System.Net;
namespace OpenSim.Framework.ServiceAuth
{
public class DisallowLlHttpRequest : IServiceAuth
{
public void AddAuthorization(NameValueCollection headers) {}
public bool Authenticate(string data)
{
return false;
}
public bool Authenticate(NameValueCollection requestHeaders, AddHeaderDelegate d, out HttpStatusCode statusCode)
{
// Console.WriteLine("DisallowLlHttpRequest");
if (requestHeaders["X-SecondLife-Shard"] != null)
{
statusCode = HttpStatusCode.Forbidden;
return false;
}
statusCode = HttpStatusCode.OK;
return true;
}
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
namespace OpenSim.Framework.ServiceAuth
{
@ -9,7 +10,7 @@ namespace OpenSim.Framework.ServiceAuth
public interface IServiceAuth
{
bool Authenticate(string data);
bool Authenticate(NameValueCollection headers, AddHeaderDelegate d);
bool Authenticate(NameValueCollection headers, AddHeaderDelegate d, out HttpStatusCode statusCode);
void AddAuthorization(NameValueCollection headers);
}
}

View File

@ -9,15 +9,27 @@ namespace OpenSim.Framework.ServiceAuth
{
public static IServiceAuth Create(IConfigSource config, string section)
{
CompoundAuthentication compoundAuth = new CompoundAuthentication();
bool allowLlHttpRequestIn
= Util.GetConfigVarFromSections<bool>(config, "AllowllHTTPRequestIn", new string[] { "Network", section }, false);
if (!allowLlHttpRequestIn)
compoundAuth.AddAuthenticator(new DisallowLlHttpRequest());
string authType = Util.GetConfigVarFromSections<string>(config, "AuthType", new string[] { "Network", section }, "None");
switch (authType)
{
case "BasicHttpAuthentication":
return new BasicHttpAuthentication(config, section);
compoundAuth.AddAuthenticator(new BasicHttpAuthentication(config, section));
break;
}
return null;
if (compoundAuth.Count > 0)
return compoundAuth;
else
return null;
}
}
}
}

View File

@ -0,0 +1,72 @@
/*
* 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;
namespace OpenSim.Framework
{
/// <summary>
/// A thread-safe Random since the .NET version is not.
/// See http://msdn.microsoft.com/en-us/library/system.random%28v=vs.100%29.aspx
/// </summary>
public class ThreadSafeRandom : Random
{
public ThreadSafeRandom() : base() {}
public ThreadSafeRandom(int seed): base (seed) {}
public override int Next()
{
lock (this)
return base.Next();
}
public override int Next(int maxValue)
{
lock (this)
return base.Next(maxValue);
}
public override int Next(int minValue, int maxValue)
{
lock (this)
return base.Next(minValue, maxValue);
}
public override void NextBytes(byte[] buffer)
{
lock (this)
base.NextBytes(buffer);
}
public override double NextDouble()
{
lock (this)
return base.NextDouble();
}
}
}

View File

@ -138,7 +138,7 @@ namespace OpenSim.Framework
}
private static uint nextXferID = 5000;
private static Random randomClass = new Random();
private static Random randomClass = new ThreadSafeRandom();
// Get a list of invalid file characters (OS dependent)
private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
@ -509,6 +509,19 @@ namespace OpenSim.Framework
return sb.ToString();
}
public static byte[] DocToBytes(XmlDocument doc)
{
using (MemoryStream ms = new MemoryStream())
using (XmlTextWriter xw = new XmlTextWriter(ms, null))
{
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
}
/// <summary>
/// Is the platform Windows?
/// </summary>
@ -1307,46 +1320,6 @@ namespace OpenSim.Framework
return ret;
}
public static string Compress(string text)
{
byte[] buffer = Util.UTF8.GetBytes(text);
MemoryStream memory = new MemoryStream();
using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
{
compressor.Write(buffer, 0, buffer.Length);
}
memory.Position = 0;
byte[] compressed = new byte[memory.Length];
memory.Read(compressed, 0, compressed.Length);
byte[] compressedBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
return Convert.ToBase64String(compressedBuffer);
}
public static string Decompress(string compressedText)
{
byte[] compressedBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream memory = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
memory.Position = 0;
using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
{
decompressor.Read(buffer, 0, buffer.Length);
}
return Util.UTF8.GetString(buffer);
}
}
/// <summary>
/// Copy data from one stream to another, leaving the read position of both streams at the beginning.
/// </summary>
@ -1964,10 +1937,15 @@ namespace OpenSim.Framework
{
if (maxThreads < 2)
throw new ArgumentOutOfRangeException("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");
if (m_ThreadPool != null)
throw new InvalidOperationException("SmartThreadPool is already initialized");
{
m_log.Warn("SmartThreadPool is already initialized. Ignoring request.");
return;
}
STPStartInfo startInfo = new STPStartInfo();
startInfo.ThreadPoolName = "Util";

View File

@ -69,7 +69,7 @@ namespace OpenSim.Framework
/// <summary>
/// Request number for diagnostic purposes.
/// </summary>
public static int RequestNumber { get; internal set; }
public static int RequestNumber { get; set; }
/// <summary>
/// Control where OSD requests should be serialized per endpoint.
@ -176,7 +176,8 @@ namespace OpenSim.Framework
public static void LogOutgoingDetail(string context, Stream outputStream)
{
using (StreamReader reader = new StreamReader(Util.Copy(outputStream), Encoding.UTF8))
using (Stream stream = Util.Copy(outputStream))
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string output;
@ -262,12 +263,12 @@ namespace OpenSim.Framework
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress))
using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true))
{
comp.Write(buffer, 0, buffer.Length);
// We need to close the gzip stream before we write it anywhere
// because apparently something important related to gzip compression
// gets written on the strteam upon Dispose()
// gets written on the stream upon Dispose()
}
byte[] buf = ms.ToArray();
request.ContentLength = buf.Length; //Count bytes to send

View File

@ -921,7 +921,7 @@ namespace OpenSim
foreach (IRegionModuleBase module in scene.RegionModules.Values)
{
if (module.GetType().GetInterface("ISharedRegionModule") != null)
if (module.GetType().GetInterface("ISharedRegionModule") == null)
nonSharedModules.Add(module);
else
sharedModules.Add(module);
@ -943,6 +943,7 @@ namespace OpenSim
cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize);
cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize);
cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize);
cdt.AddColumn("Size", 11);
cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize);
cdt.AddColumn("Ready?", 6);
cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize);
@ -951,8 +952,13 @@ namespace OpenSim
{
RegionInfo ri = scene.RegionInfo;
cdt.AddRow(
ri.RegionName, ri.RegionID, string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY),
ri.InternalEndPoint.Port, scene.Ready ? "Yes" : "No", ri.EstateSettings.EstateName);
ri.RegionName,
ri.RegionID,
string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY),
string.Format("{0}x{1}", ri.RegionSizeX, ri.RegionSizeY),
ri.InternalEndPoint.Port,
scene.Ready ? "Yes" : "No",
ri.EstateSettings.EstateName);
}
);

View File

@ -71,6 +71,20 @@ namespace OpenSim
// OpenSim.ini Section name for ESTATES Settings
public const string ESTATE_SECTION_NAME = "Estates";
/// <summary>
/// Allow all plugin loading to be disabled for tests/debug.
/// </summary>
/// <remarks>
/// true by default
/// </remarks>
public bool EnableInitialPluginLoad { get; set; }
/// <summary>
/// Control whether we attempt to load an estate data service.
/// </summary>
/// <remarks>For tests/debugging</remarks>
public bool LoadEstateDataService { get; set; }
protected string proxyUrl;
protected int proxyOffset = 0;
@ -96,7 +110,7 @@ namespace OpenSim
public ConsoleCommand CreateAccount = null;
protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();
public List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();
/// <value>
/// The config information passed into the OpenSimulator region server.
@ -135,6 +149,8 @@ namespace OpenSim
/// <param name="configSource"></param>
public OpenSimBase(IConfigSource configSource) : base()
{
EnableInitialPluginLoad = true;
LoadEstateDataService = true;
LoadConfigSettings(configSource);
}
@ -240,20 +256,25 @@ namespace OpenSim
if (String.IsNullOrEmpty(module))
throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] section");
m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { Config });
if (m_estateDataService == null)
throw new Exception(
string.Format(
"Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.",
module));
if (LoadEstateDataService)
{
m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { Config });
if (m_estateDataService == null)
throw new Exception(
string.Format(
"Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.",
module));
}
base.StartupSpecific();
LoadPlugins();
if (EnableInitialPluginLoad)
LoadPlugins();
// We still want to post initalize any plugins even if loading has been disabled since a test may have
// inserted them manually.
foreach (IApplicationPlugin plugin in m_plugins)
{
plugin.PostInitialise();
}
if (m_console != null)
AddPluginCommands(m_console);
@ -878,6 +899,9 @@ namespace OpenSim
try
{
SceneManager.Close();
foreach (IApplicationPlugin plugin in m_plugins)
plugin.Dispose();
}
catch (Exception e)
{

View File

@ -44,6 +44,7 @@ using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Client;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
@ -536,6 +537,42 @@ namespace OpenSim.Region.ClientStack.Linden
OSDArray texture_list = (OSDArray)request["texture_list"];
SceneObjectGroup grp = null;
InventoryFolderBase textureUploadFolder = null;
List<InventoryFolderBase> foldersToUpdate = new List<InventoryFolderBase>();
List<InventoryItemBase> itemsToUpdate = new List<InventoryItemBase>();
IClientInventory clientInv = null;
if (texture_list.Count > 0)
{
ScenePresence avatar = null;
IClientAPI client = null;
m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
if (avatar != null)
{
IClientCore core = (IClientCore)avatar.ControllingClient;
if (core.TryGet<IClientInventory>(out clientInv))
{
var systemTextureFolder = m_Scene.InventoryService.GetFolderForType(m_HostCapsObj.AgentID, AssetType.Texture);
textureUploadFolder = new InventoryFolderBase(UUID.Random(), assetName, m_HostCapsObj.AgentID, (short)AssetType.Unknown, systemTextureFolder.ID, 1);
if (m_Scene.InventoryService.AddFolder(textureUploadFolder))
{
foldersToUpdate.Add(textureUploadFolder);
m_log.DebugFormat(
"[BUNCH OF CAPS]: Created new folder '{0}' ({1}) for textures uploaded with mesh object {2}",
textureUploadFolder.Name, textureUploadFolder.ID, assetName);
}
else
{
textureUploadFolder = null;
}
}
}
}
List<UUID> textures = new List<UUID>();
for (int i = 0; i < texture_list.Count; i++)
{
@ -543,6 +580,38 @@ namespace OpenSim.Region.ClientStack.Linden
textureAsset.Data = texture_list[i].AsBinary();
m_assetService.Store(textureAsset);
textures.Add(textureAsset.FullID);
if (textureUploadFolder != null)
{
InventoryItemBase textureItem = new InventoryItemBase();
textureItem.Owner = m_HostCapsObj.AgentID;
textureItem.CreatorId = m_HostCapsObj.AgentID.ToString();
textureItem.CreatorData = String.Empty;
textureItem.ID = UUID.Random();
textureItem.AssetID = textureAsset.FullID;
textureItem.Description = assetDescription;
textureItem.Name = assetName + " - Texture " + (i + 1).ToString();
textureItem.AssetType = (int)AssetType.Texture;
textureItem.InvType = (int)InventoryType.Texture;
textureItem.Folder = textureUploadFolder.ID;
textureItem.CurrentPermissions
= (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
textureItem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
textureItem.EveryOnePermissions = 0;
textureItem.NextPermissions = (uint)PermissionMask.All;
textureItem.CreationDate = Util.UnixTimeSinceEpoch();
m_Scene.InventoryService.AddItem(textureItem);
itemsToUpdate.Add(textureItem);
m_log.DebugFormat(
"[BUNCH OF CAPS]: Created new inventory item '{0}' ({1}) for texture uploaded with mesh object {2}",
textureItem.Name, textureItem.ID, assetName);
}
}
if (clientInv != null && (foldersToUpdate.Count > 0 || itemsToUpdate.Count > 0))
{
clientInv.SendBulkUpdateInventory(foldersToUpdate.ToArray(), itemsToUpdate.ToArray());
}
for (int i = 0; i < mesh_list.Count; i++)

View File

@ -101,7 +101,7 @@ namespace OpenSim.Region.ClientStack.Linden
"debug eq [0|1|2]",
"Turn on event queue debugging\n"
+ " <= 0 - turns off all event queue logging\n"
+ " >= 1 - turns on outgoing event logging\n"
+ " >= 1 - turns on event queue setup and outgoing event logging\n"
+ " >= 2 - turns on poll notification",
HandleDebugEq);
@ -188,9 +188,11 @@ namespace OpenSim.Region.ClientStack.Linden
{
if (!queues.ContainsKey(agentId))
{
m_log.DebugFormat(
"[EVENTQUEUE]: Adding new queue for agent {0} in region {1}",
agentId, m_scene.RegionInfo.RegionName);
if (DebugLevel > 0)
m_log.DebugFormat(
"[EVENTQUEUE]: Adding new queue for agent {0} in region {1}",
agentId, m_scene.RegionInfo.RegionName);
queues[agentId] = new Queue<OSD>();
}
@ -302,9 +304,10 @@ namespace OpenSim.Region.ClientStack.Linden
{
// Register an event queue for the client
m_log.DebugFormat(
"[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}",
agentID, caps, m_scene.RegionInfo.RegionName);
if (DebugLevel > 0)
m_log.DebugFormat(
"[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}",
agentID, caps, m_scene.RegionInfo.RegionName);
// Let's instantiate a Queue for this agent right now
TryGetQueue(agentID);
@ -720,8 +723,9 @@ namespace OpenSim.Region.ClientStack.Linden
public virtual void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY)
{
m_log.DebugFormat("{0} EnableSimulator. handle={1}, avatarID={2}, regionSize={3},{4}>",
LogHeader, handle, avatarID, regionSizeX, regionSizeY);
if (DebugLevel > 0)
m_log.DebugFormat("{0} EnableSimulator. handle={1}, endPoint={2}, avatarID={3}",
LogHeader, handle, endPoint, avatarID, regionSizeX, regionSizeY);
OSD item = EventQueueHelper.EnableSimulator(handle, endPoint, regionSizeX, regionSizeY);
Enqueue(item, avatarID);
@ -730,8 +734,10 @@ namespace OpenSim.Region.ClientStack.Linden
public virtual void EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoint, string capsPath,
ulong regionHandle, int regionSizeX, int regionSizeY)
{
m_log.DebugFormat("{0} EstablishAgentCommunication. handle={1}, avatarID={2}, regionSize={3},{4}>",
LogHeader, regionHandle, avatarID, regionSizeX, regionSizeY);
if (DebugLevel > 0)
m_log.DebugFormat("{0} EstablishAgentCommunication. handle={1}, endPoint={2}, avatarID={3}",
LogHeader, regionHandle, endPoint, avatarID, regionSizeX, regionSizeY);
OSD item = EventQueueHelper.EstablishAgentCommunication(avatarID, endPoint.ToString(), capsPath, regionHandle, regionSizeX, regionSizeY);
Enqueue(item, avatarID);
}
@ -741,8 +747,9 @@ namespace OpenSim.Region.ClientStack.Linden
uint locationID, uint flags, string capsURL,
UUID avatarID, int regionSizeX, int regionSizeY)
{
m_log.DebugFormat("{0} TeleportFinishEvent. handle={1}, avatarID={2}, regionSize=<{3},{4}>",
LogHeader, regionHandle, avatarID, regionSizeX, regionSizeY);
if (DebugLevel > 0)
m_log.DebugFormat("{0} TeleportFinishEvent. handle={1}, endPoint={2}, avatarID={3}",
LogHeader, regionHandle, regionExternalEndPoint, avatarID, regionSizeX, regionSizeY);
OSD item = EventQueueHelper.TeleportFinishEvent(regionHandle, simAccess, regionExternalEndPoint,
locationID, flags, capsURL, avatarID, regionSizeX, regionSizeY);
@ -753,8 +760,9 @@ namespace OpenSim.Region.ClientStack.Linden
IPEndPoint newRegionExternalEndPoint,
string capsURL, UUID avatarID, UUID sessionID, int regionSizeX, int regionSizeY)
{
m_log.DebugFormat("{0} CrossRegion. handle={1}, avatarID={2}, regionSize={3},{4}>",
LogHeader, handle, avatarID, regionSizeX, regionSizeY);
if (DebugLevel > 0)
m_log.DebugFormat("{0} CrossRegion. handle={1}, avatarID={2}, regionSize={3},{4}>",
LogHeader, handle, avatarID, regionSizeX, regionSizeY);
OSD item = EventQueueHelper.CrossRegion(handle, pos, lookAt, newRegionExternalEndPoint,
capsURL, avatarID, sessionID, regionSizeX, regionSizeY);
@ -819,4 +827,4 @@ namespace OpenSim.Region.ClientStack.Linden
Enqueue(item, avatarID);
}
}
}
}

View File

@ -63,8 +63,7 @@ namespace OpenSim.Region.ClientStack.Linden
public List<UUID> folders;
}
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Control whether requests will be processed asynchronously.
@ -438,7 +437,18 @@ namespace OpenSim.Region.ClientStack.Linden
aPollRequest poolreq = m_queue.Dequeue();
if (poolreq != null && poolreq.thepoll != null)
poolreq.thepoll.Process(poolreq);
{
try
{
poolreq.thepoll.Process(poolreq);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[INVENTORY]: Failed to process queued inventory request {0} for {1} in {2}. Exception {3}",
poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", Scene.Name, e);
}
}
}
}
}

View File

@ -1467,10 +1467,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
mapReply.Data[i].Access = mapBlocks2[i].Access;
mapReply.Data[i].Agents = mapBlocks2[i].Agents;
// TODO: hookup varregion sim size here
mapReply.Size[i] = new MapBlockReplyPacket.SizeBlock();
mapReply.Size[i].SizeX = 256;
mapReply.Size[i].SizeY = 256;
mapReply.Size[i].SizeX = mapBlocks2[i].SizeX;
mapReply.Size[i].SizeY = mapBlocks2[i].SizeY;
}
OutPacket(mapReply, ThrottleOutPacketType.Land);
}
@ -11773,7 +11772,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <returns></returns>
protected bool HandleAgentTextureCached(IClientAPI simclient, Packet packet)
{
//m_log.Debug("texture cached: " + packet.ToString());
AgentCachedTexturePacket cachedtex = (AgentCachedTexturePacket)packet;
AgentCachedTextureResponsePacket cachedresp = (AgentCachedTextureResponsePacket)PacketPool.Instance.GetPacket(PacketType.AgentCachedTextureResponse);
@ -11789,24 +11787,22 @@ namespace OpenSim.Region.ClientStack.LindenUDP
cachedresp.WearableData =
new AgentCachedTextureResponsePacket.WearableDataBlock[cachedtex.WearableData.Length];
//IAvatarFactoryModule fac = m_scene.RequestModuleInterface<IAvatarFactoryModule>();
// var item = fac.GetBakedTextureFaces(AgentId);
//WearableCacheItem[] items = fac.GetCachedItems(AgentId);
IAssetService cache = m_scene.AssetService;
IBakedTextureModule bakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
//bakedTextureModule = null;
int maxWearablesLoop = cachedtex.WearableData.Length;
if (maxWearablesLoop > AvatarWearable.MAX_WEARABLES)
maxWearablesLoop = AvatarWearable.MAX_WEARABLES;
// Find the cached baked textures for this user, if they're available
IAssetService cache = m_scene.AssetService;
IBakedTextureModule bakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
WearableCacheItem[] cacheItems = null;
if (bakedTextureModule != null && cache != null)
{
// We need to make sure the asset stored in the bake is available on this server also by it's assetid before we map it to a Cacheid
WearableCacheItem[] cacheItems = null;
ScenePresence p = m_scene.GetScenePresence(AgentId);
if (p.Appearance != null)
{
if (p.Appearance.WearableCacheItems == null || p.Appearance.WearableCacheItemsDirty)
{
try
@ -11815,22 +11811,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
p.Appearance.WearableCacheItems = cacheItems;
p.Appearance.WearableCacheItemsDirty = false;
}
/*
* The following Catch types DO NOT WORK, it jumps to the General Packet Exception Handler if you don't catch Exception!
*
catch (System.Net.Sockets.SocketException)
{
cacheItems = null;
}
catch (WebException)
{
cacheItems = null;
}
catch (InvalidOperationException)
{
cacheItems = null;
} */
catch (Exception)
{
cacheItems = null;
@ -11841,87 +11821,54 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
cacheItems = p.Appearance.WearableCacheItems;
}
}
}
if (cache != null && cacheItems != null)
if (cacheItems != null)
{
// We need to make sure the asset stored in the bake is available on this server also by its assetid before we map it to a Cacheid.
// Copy the baked textures to the sim's assets cache (local only).
foreach (WearableCacheItem item in cacheItems)
{
foreach (WearableCacheItem item in cacheItems)
if (cache.GetCached(item.TextureID.ToString()) == null)
{
if (cache.GetCached(item.TextureID.ToString()) == null)
{
item.TextureAsset.Temporary = true;
cache.Store(item.TextureAsset);
}
item.TextureAsset.Temporary = true;
item.TextureAsset.Local = true;
cache.Store(item.TextureAsset);
}
}
if (cacheItems != null)
// Return the cached textures
for (int i = 0; i < maxWearablesLoop; i++)
{
WearableCacheItem item =
WearableCacheItem.SearchTextureIndex(cachedtex.WearableData[i].TextureIndex, cacheItems);
for (int i = 0; i < maxWearablesLoop; i++)
cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
cachedresp.WearableData[i].TextureIndex = cachedtex.WearableData[i].TextureIndex;
cachedresp.WearableData[i].HostName = new byte[0];
if (item != null && cachedtex.WearableData[i].ID == item.CacheId)
{
WearableCacheItem item =
WearableCacheItem.SearchTextureIndex(cachedtex.WearableData[i].TextureIndex,cacheItems);
cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
cachedresp.WearableData[i].TextureIndex= cachedtex.WearableData[i].TextureIndex;
cachedresp.WearableData[i].HostName = new byte[0];
if (item != null && cachedtex.WearableData[i].ID == item.CacheId)
{
cachedresp.WearableData[i].TextureID = item.TextureID;
}
else
{
cachedresp.WearableData[i].TextureID = UUID.Zero;
}
cachedresp.WearableData[i].TextureID = item.TextureID;
}
}
else
{
for (int i = 0; i < maxWearablesLoop; i++)
else
{
cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
cachedresp.WearableData[i].TextureIndex = cachedtex.WearableData[i].TextureIndex;
cachedresp.WearableData[i].TextureID = UUID.Zero;
//UUID.Parse("8334fb6e-c2f5-46ee-807d-a435f61a8d46");
cachedresp.WearableData[i].HostName = new byte[0];
}
}
}
else
{
if (cache == null)
// Cached textures not available
for (int i = 0; i < maxWearablesLoop; i++)
{
for (int i = 0; i < maxWearablesLoop; i++)
{
cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
cachedresp.WearableData[i].TextureIndex = cachedtex.WearableData[i].TextureIndex;
cachedresp.WearableData[i].TextureID = UUID.Zero;
//UUID.Parse("8334fb6e-c2f5-46ee-807d-a435f61a8d46");
cachedresp.WearableData[i].HostName = new byte[0];
}
}
else
{
for (int i = 0; i < maxWearablesLoop; i++)
{
cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
cachedresp.WearableData[i].TextureIndex = cachedtex.WearableData[i].TextureIndex;
if (cache.GetCached(cachedresp.WearableData[i].TextureID.ToString()) == null)
cachedresp.WearableData[i].TextureID = UUID.Zero;
//UUID.Parse("8334fb6e-c2f5-46ee-807d-a435f61a8d46");
else
cachedresp.WearableData[i].TextureID = UUID.Zero;
// UUID.Parse("8334fb6e-c2f5-46ee-807d-a435f61a8d46");
cachedresp.WearableData[i].HostName = new byte[0];
}
cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
cachedresp.WearableData[i].TextureIndex = cachedtex.WearableData[i].TextureIndex;
cachedresp.WearableData[i].TextureID = UUID.Zero;
cachedresp.WearableData[i].HostName = new byte[0];
}
}
cachedresp.Header.Zerocoded = true;
OutPacket(cachedresp, ThrottleOutPacketType.Task);

View File

@ -202,7 +202,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Create a token bucket throttle for this client that has the scene token bucket as a parent
m_throttleClient = new AdaptiveTokenBucket(parentThrottle, rates.Total, rates.AdaptiveThrottlesEnabled);
// Create a token bucket throttle for the total categary with the client bucket as a throttle
// Create a token bucket throttle for the total category with the client bucket as a throttle
m_throttleCategory = new TokenBucket(m_throttleClient, 0);
// Create an array of token buckets for this clients different throttle categories
m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT];
@ -262,6 +262,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate;
m_info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate;
m_info.totalThrottle = (int)m_throttleCategory.DripRate;
m_info.maxThrottle = (int)m_throttleClient.MaxDripRate;
return m_info;
}

View File

@ -674,7 +674,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
MainConsole.Instance.Commands.AddCommand(
"Debug", false, "debug lludp packet",
"debug lludp packet [--default] <level> [<avatar-first-name> <avatar-last-name>]",
"debug lludp packet [--default | --all] <level> [<avatar-first-name> <avatar-last-name>]",
"Turn on packet debugging",
"If level > 255 then all incoming and outgoing packets are logged.\n"
+ "If level <= 255 then incoming AgentUpdate and outgoing SimStats and SimulatorViewerTimeMessage packets are not logged.\n"
@ -683,7 +683,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
+ "If level <= 50 then outgoing ImprovedTerseObjectUpdate packets are not logged.\n"
+ "If level <= 0 then no packets are logged.\n"
+ "If --default is specified then the level becomes the default logging level for all subsequent agents.\n"
+ "In this case, you cannot also specify an avatar name.\n"
+ "If --all is specified then the level becomes the default logging level for all current and subsequent agents.\n"
+ "In these cases, you cannot also specify an avatar name.\n"
+ "If an avatar name is given then only packets from that avatar are logged.",
HandlePacketCommand);
@ -742,20 +743,23 @@ namespace OpenSim.Region.ClientStack.LindenUDP
return;
bool setAsDefaultLevel = false;
OptionSet optionSet = new OptionSet().Add("default", o => setAsDefaultLevel = o != null);
bool setAll = false;
OptionSet optionSet = new OptionSet()
.Add("default", o => setAsDefaultLevel = (o != null))
.Add("all", o => setAll = (o != null));
List<string> filteredArgs = optionSet.Parse(args);
string name = null;
if (filteredArgs.Count == 6)
{
if (!setAsDefaultLevel)
if (!(setAsDefaultLevel || setAll))
{
name = string.Format("{0} {1}", filteredArgs[4], filteredArgs[5]);
}
else
{
MainConsole.Instance.OutputFormat("ERROR: Cannot specify a user name when setting default logging level");
MainConsole.Instance.OutputFormat("ERROR: Cannot specify a user name when setting default/all logging level");
return;
}
}
@ -765,11 +769,25 @@ namespace OpenSim.Region.ClientStack.LindenUDP
int newDebug;
if (int.TryParse(filteredArgs[3], out newDebug))
{
if (setAsDefaultLevel)
if (setAsDefaultLevel || setAll)
{
DefaultClientPacketDebugLevel = newDebug;
MainConsole.Instance.OutputFormat(
"Debug packet debug for new clients set to {0} in {1}", DefaultClientPacketDebugLevel, m_scene.Name);
"Packet debug for {0} clients set to {1} in {2}",
(setAll ? "all" : "future"), DefaultClientPacketDebugLevel, m_scene.Name);
if (setAll)
{
m_scene.ForEachScenePresence(sp =>
{
MainConsole.Instance.OutputFormat(
"Packet debug for {0} ({1}) set to {2} in {3}",
sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_scene.Name);
sp.ControllingClient.DebugPacketLevel = newDebug;
});
}
}
else
{
@ -788,7 +806,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
else
{
MainConsole.Instance.Output("Usage: debug lludp packet [--default] 0..255 [<first-name> <last-name>]");
MainConsole.Instance.Output("Usage: debug lludp packet [--default | --all] 0..255 [<first-name> <last-name>]");
}
}
}
@ -973,7 +991,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
if (!SendPacketData(udpClient, data, packet.Type, category, method))
packetQueued = true;
}
@ -981,7 +998,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
else
{
byte[] data = packet.ToBytes();
packetQueued = SendPacketData(udpClient, data, packet.Type, category, method);
if (!SendPacketData(udpClient, data, packet.Type, category, method))
packetQueued = true;
}
PacketPool.Instance.ReturnPacket(packet);
@ -1065,8 +1083,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// If a Linden Lab 1.23.5 client receives an update packet after a kill packet for an object, it will
// continue to display the deleted object until relog. Therefore, we need to always queue a kill object
// packet so that it isn't sent before a queued update packet.
bool requestQueue = type == PacketType.KillObject;
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, requestQueue))
bool forceQueue = (type == PacketType.KillObject);
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, forceQueue))
{
SendPacketFinal(outgoingPacket);
return true;
@ -2305,4 +2324,4 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
}
}
}
}

View File

@ -233,7 +233,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP.Tests
// testLLUDPServer.RemoveClientCircuit(myCircuitCode);
// Assert.IsFalse(testLLUDPServer.HasCircuit(myCircuitCode));
//
// // Check that removing a non-existant circuit doesn't have any bad effects
// // Check that removing a non-existent circuit doesn't have any bad effects
// testLLUDPServer.RemoveClientCircuit(101);
// Assert.IsFalse(testLLUDPServer.HasCircuit(101));
// }

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
@ -335,13 +335,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// greater than this.
// </summary>
protected Int64 m_maxDripRate = 0;
protected Int64 MaxDripRate
public Int64 MaxDripRate
{
get { return (m_maxDripRate == 0 ? m_totalDripRequest : m_maxDripRate); }
set { m_maxDripRate = (value == 0 ? 0 : Math.Max(value,m_minimumFlow)); }
protected set { m_maxDripRate = (value == 0 ? 0 : Math.Max(value,m_minimumFlow)); }
}
private bool m_enabled = false;
public bool Enabled { get; private set; }
// <summary>
//
@ -362,9 +362,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// </summary>
public AdaptiveTokenBucket(TokenBucket parent, Int64 maxDripRate, bool enabled) : base(parent,maxDripRate)
{
m_enabled = enabled;
Enabled = enabled;
if (m_enabled)
if (Enabled)
{
// m_log.DebugFormat("[TOKENBUCKET] Adaptive throttle enabled");
MaxDripRate = maxDripRate;
@ -378,7 +378,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void ExpirePackets(Int32 count)
{
// m_log.WarnFormat("[ADAPTIVEBUCKET] drop {0} by {1} expired packets",AdjustedDripRate,count);
if (m_enabled)
if (Enabled)
AdjustedDripRate = (Int64) (AdjustedDripRate / Math.Pow(2,count));
}
@ -387,7 +387,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// </summary>
public void AcknowledgePackets(Int32 count)
{
if (m_enabled)
if (Enabled)
AdjustedDripRate = AdjustedDripRate + count;
}
}

View File

@ -39,6 +39,7 @@ using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.ClientStack
{

View File

@ -31,6 +31,7 @@ using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using PermissionMask = OpenSim.Framework.PermissionMask;
@ -376,6 +377,8 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
m_Scene.AssetService.Store(m_asset);
m_transactions.RemoveXferUploader(m_transactionID);
m_Scene.EventManager.TriggerOnNewInventoryItemUploadComplete(ourClient.AgentId, (AssetType)type, m_asset.FullID, m_asset.Name, 0);
}
/// <summary>
@ -422,5 +425,6 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
m_transactions.RemoveXferUploader(m_transactionID);
}
}
}

View File

@ -231,7 +231,11 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
try
{
List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));
List<int> layerStarts;
using (MemoryStream ms = new MemoryStream(j2kData))
{
layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms);
}
if (layerStarts != null && layerStarts.Count > 0)
{

View File

@ -316,9 +316,12 @@ namespace OpenSim.Region.CoreModules.Asset
/// </summary>
public void Close()
{
m_enabled = false;
m_cache.Clear();
m_cache = null;
if (m_enabled)
{
m_enabled = false;
m_cache.Clear();
m_cache = null;
}
}
/// <summary>

View File

@ -135,7 +135,7 @@ namespace OpenSim.Region.CoreModules.Avatar.BakedTextures
sr.ReadEndElement();
}
m_log.DebugFormat("[XBakes]: Ended reading");
m_log.DebugFormat("[XBakes]: read {0} textures for user {1}", ret.Count, id);
sr.Close();
s.Close();
@ -186,6 +186,7 @@ namespace OpenSim.Region.CoreModules.Avatar.BakedTextures
delegate
{
rc.Request(reqStream, m_Auth);
m_log.DebugFormat("[XBakes]: stored {0} textures for user {1}", data.Length, agentId);
}
);
}

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
@ -289,18 +289,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
return Util.DocToBytes(doc);
}
#endregion

View File

@ -1152,16 +1152,24 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}",assetServerURI, assetId.AsString()));
if (parameters.ContainsKey("result"))
{
OSDArray list = (OSDArray)parameters["result"];
foreach (OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}", assetServerURI, assetId.AsString()));
}
return true;
}
else
{
m_log.ErrorFormat("[PROFILES]: Problematic response for image_assets_request from {0}", profileServerURI);
return false;
}
return true;
}
/// <summary>

View File

@ -208,7 +208,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
protected virtual void InitialiseCommon(IConfigSource source)
{
string transferVersionName = "SIMULATION";
float maxTransferVersion = 0.2f;
float maxTransferVersion = 0.3f;
IConfig hypergridConfig = source.Configs["Hypergrid"];
if (hypergridConfig != null)
@ -760,8 +760,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
string reason;
string version;
string myversion = string.Format("{0}/{1}", OutgoingTransferVersionName, MaxOutgoingTransferVersion);
if (!Scene.SimulationService.QueryAccess(
finalDestination, sp.ControllingClient.AgentId, homeURI, true, position, out version, out reason))
finalDestination, sp.ControllingClient.AgentId, homeURI, true, position, myversion, out version, out reason))
{
sp.ControllingClient.SendTeleportFailed(reason);
@ -820,7 +821,10 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
agentCircuit.Id0 = currentAgentCircuit.Id0;
}
if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
// if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
float dist = (float)Math.Max(sp.Scene.DefaultDrawDistance,
(float)Math.Max(sp.Scene.RegionInfo.RegionSizeX, sp.Scene.RegionInfo.RegionSizeY));
if (NeedsNewAgent(dist, oldRegionX, newRegionX, oldRegionY, newRegionY))
{
// brand new agent, let's create a new caps seed
agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
@ -833,7 +837,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
if (versionComponents.Length >= 2)
float.TryParse(versionComponents[1], out versionNumber);
if (versionNumber == 0.2f && MaxOutgoingTransferVersion >= versionNumber)
if (versionNumber >= 0.2f && MaxOutgoingTransferVersion >= versionNumber)
TransferAgent_V2(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, oldRegionX, newRegionX, oldRegionY, newRegionY, version, out reason);
else
TransferAgent_V1(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, oldRegionX, newRegionX, oldRegionY, newRegionY, version, out reason);
@ -894,7 +898,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
IClientIPEndpoint ipepClient;
string capsPath = String.Empty;
if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
float dist = (float)Math.Max(sp.Scene.DefaultDrawDistance,
(float)Math.Max(sp.Scene.RegionInfo.RegionSizeX, sp.Scene.RegionInfo.RegionSizeY));
if (NeedsNewAgent(dist, oldRegionX, newRegionX, oldRegionY, newRegionY))
{
m_log.DebugFormat(
"[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} needs new child agent for incoming agent {3} from {4}",
@ -1140,7 +1146,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
IClientIPEndpoint ipepClient;
string capsPath = String.Empty;
if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
float dist = (float)Math.Max(sp.Scene.DefaultDrawDistance,
(float)Math.Max(sp.Scene.RegionInfo.RegionSizeX, sp.Scene.RegionInfo.RegionSizeY));
if (NeedsNewAgent(dist, oldRegionX, newRegionX, oldRegionY, newRegionY))
{
m_log.DebugFormat(
"[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} needs new child agent for agent {3} from {4}",
@ -1509,8 +1517,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
}
// Check to see if we have access to the target region.
string myversion = string.Format("{0}/{1}", OutgoingTransferVersionName, MaxOutgoingTransferVersion);
if (neighbourRegion != null
&& !scene.SimulationService.QueryAccess(neighbourRegion, agentID, homeURI, false, newpos, out version, out failureReason))
&& !scene.SimulationService.QueryAccess(neighbourRegion, agentID, homeURI, false, newpos, myversion, out version, out failureReason))
{
// remember banned
m_bannedRegionCache.Add(neighbourRegion.RegionHandle, agentID);
@ -1520,7 +1529,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
else
{
// The destination region just doesn't exist
failureReason = "Cannot cross into non-existant region";
failureReason = "Cannot cross into non-existent region";
}
if (neighbourRegion == null)
@ -1864,7 +1873,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
//foreach (ulong h in agent.ChildrenCapSeeds.Keys)
// m_log.DebugFormat("[XXX] --> {0}", h);
//m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);
if (agent.ChildrenCapSeeds.ContainsKey(region.RegionHandle))
{
m_log.WarnFormat(
"[ENTITY TRANSFER]: Overwriting caps seed {0} with {1} for region {2} (handle {3}) for {4} in {5}",
agent.ChildrenCapSeeds[region.RegionHandle], agent.CapsPath,
region.RegionName, region.RegionHandle, sp.Name, Scene.Name);
}
agent.ChildrenCapSeeds[region.RegionHandle] = agent.CapsPath;
if (sp.Scene.CapsModule != null)
{

View File

@ -130,7 +130,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
base.AddRegion(scene);
m_assMapper = new HGAssetMapper(scene, m_HomeURI);
scene.EventManager.OnNewInventoryItemUploadComplete += UploadInventoryItem;
scene.EventManager.OnNewInventoryItemUploadComplete += PostInventoryAsset;
scene.EventManager.OnTeleportStart += TeleportStart;
scene.EventManager.OnTeleportFail += TeleportFail;
@ -209,7 +209,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
}
}
public void UploadInventoryItem(UUID avatarID, AssetType type, UUID assetID, string name, int userlevel)
public void PostInventoryAsset(UUID avatarID, AssetType type, UUID assetID, string name, int userlevel)
{
if (type == AssetType.Link)
return;
@ -248,7 +248,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
UUID newAssetID = base.CapsUpdateInventoryItemAsset(remoteClient, itemID, data);
UploadInventoryItem(remoteClient.AgentId, AssetType.Unknown, newAssetID, "", 0);
PostInventoryAsset(remoteClient.AgentId, AssetType.Unknown, newAssetID, "", 0);
return newAssetID;
}
@ -260,7 +260,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
if (base.UpdateInventoryItemAsset(ownerID, item, asset))
{
UploadInventoryItem(ownerID, (AssetType)asset.Type, asset.FullID, asset.Name, 0);
PostInventoryAsset(ownerID, (AssetType)asset.Type, asset.FullID, asset.Name, 0);
return true;
}
@ -273,7 +273,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
protected override void ExportAsset(UUID agentID, UUID assetID)
{
if (!assetID.Equals(UUID.Zero))
UploadInventoryItem(agentID, AssetType.Unknown, assetID, "", 0);
PostInventoryAsset(agentID, AssetType.Unknown, assetID, "", 0);
else
m_log.Debug("[HGScene]: Scene.Inventory did not create asset");
}

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
@ -151,7 +151,7 @@ namespace OpenSim.Region.CoreModules.Framework.Statistics.Logging
string path = (m_logDirectory.Length > 0 ? m_logDirectory
+ System.IO.Path.DirectorySeparatorChar.ToString() : "")
+ String.Format("{0}{1}.log", LogFileHeader, now.ToString("yyyyMMddHHmmss"));
m_logFile = new StreamWriter(File.Open(path, FileMode.Append, FileAccess.Write));
m_logFile = new StreamWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
}
if (m_logFile != null)
{

View File

@ -40,6 +40,7 @@ using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
@ -94,10 +95,13 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private OutboundUrlFilter m_outboundUrlFilter;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
@ -156,7 +160,9 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
return UUID.Zero;
}
public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body)
public UUID StartHttpRequest(
uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
out HttpInitialRequestStatus status)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
@ -232,7 +238,8 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
}
}
}
htc.RequestModule = this;
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
@ -243,14 +250,43 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
// Same number as default HttpWebRequest.MaximumAutomaticRedirections
htc.MaxRedirects = 50;
if (StartHttpRequest(htc))
{
status = HttpInitialRequestStatus.OK;
return htc.ReqID;
}
else
{
status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
return UUID.Zero;
}
}
/// <summary>
/// Would a caller to this module be allowed to make a request to the given URL?
/// </summary>
/// <returns></returns>
public bool CheckAllowed(Uri url)
{
return m_outboundUrlFilter.CheckAllowed(url);
}
public bool StartHttpRequest(HttpRequestClass req)
{
if (!CheckAllowed(new Uri(req.Url)))
return false;
lock (HttpListLock)
{
m_pendingRequests.Add(reqID, htc);
m_pendingRequests.Add(req.ReqID, req);
}
htc.Process();
req.Process();
return reqID;
return true;
}
public void StopHttpRequestsForScript(UUID id)
@ -326,6 +362,8 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
}
@ -368,7 +406,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
#endregion
}
public class HttpRequestClass: IServiceRequest
public class HttpRequestClass : IServiceRequest
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@ -380,6 +418,12 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
// public const int HTTP_VERBOSE_THROTTLE = 4;
// public const int HTTP_CUSTOM_HEADER = 5;
// public const int HTTP_PRAGMA_NO_CACHE = 6;
/// <summary>
/// Module that made this request.
/// </summary>
public HttpRequestModule RequestModule { get; set; }
private bool _finished;
public bool Finished
{
@ -412,6 +456,17 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
/// <summary>
/// Number of HTTP redirects that this request has been through.
/// </summary>
public int Redirects { get; private set; }
/// <summary>
/// Maximum number of HTTP redirects allowed for this request.
/// </summary>
public int MaxRedirects { get; set; }
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
@ -419,7 +474,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
get { return _reqID; }
set { _reqID = value; }
}
public WebRequest Request;
public HttpWebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
@ -435,7 +490,8 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
try
{
Request = WebRequest.Create(Url);
Request = (HttpWebRequest)WebRequest.Create(Url);
Request.AllowAutoRedirect = false;
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
@ -450,16 +506,19 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
// {
// Request.ConnectionGroupName="Verify";
// }
if (!HttpPragmaNoCache)
{
Request.Headers.Add("Pragma", "no-cache");
}
if (HttpCustomHeaders != null)
{
for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
Request.Headers.Add(HttpCustomHeaders[i],
HttpCustomHeaders[i+1]);
}
if (!string.IsNullOrEmpty(proxyurl))
{
if (!string.IsNullOrEmpty(proxyexcepts))
@ -565,7 +624,52 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
if (response != null)
response.Close();
_finished = true;
// We need to resubmit
if (
(Status == (int)HttpStatusCode.MovedPermanently
|| Status == (int)HttpStatusCode.Found
|| Status == (int)HttpStatusCode.SeeOther
|| Status == (int)HttpStatusCode.TemporaryRedirect))
{
if (Redirects >= MaxRedirects)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "Number of redirects exceeded max redirects";
_finished = true;
}
else
{
string location = response.Headers["Location"];
if (location == null)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "HTTP redirect code but no location header";
_finished = true;
}
else if (!RequestModule.CheckAllowed(new Uri(location)))
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "URL from HTTP redirect blocked: " + location;
_finished = true;
}
else
{
Status = 0;
Url = response.Headers["Location"];
Redirects++;
ResponseBody = null;
// m_log.DebugFormat("Redirecting to [{0}]", Url);
Process();
}
}
}
else
{
_finished = true;
}
}
}
@ -583,4 +687,4 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
Request.Abort();
}
}
}
}

View File

@ -147,11 +147,11 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest.Tests
/// <summary>
/// Test what happens when we get a 404 response from a call.
/// </summary>
[Test]
// [Test]
public void Test404Response()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestHelpers.EnableLogging();
if (!Util.IsPlatformMono)
Assert.Ignore("Ignoring test since can only currently run on Mono");

View File

@ -32,6 +32,7 @@ using System.Net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework.Communications;
using OpenSim.Region.CoreModules.Scripting.DynamicTexture;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
@ -50,6 +51,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
private OutboundUrlFilter m_outboundUrlFilter;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
@ -88,8 +90,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
MakeHttpRequest(url, id);
return true;
return MakeHttpRequest(url, id);
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
@ -110,6 +111,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
public void Initialise(IConfigSource config)
{
m_outboundUrlFilter = new OutboundUrlFilter("Script dynamic texture image module", config);
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
}
@ -157,9 +159,13 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
#endregion
private void MakeHttpRequest(string url, UUID requestID)
private bool MakeHttpRequest(string url, UUID requestID)
{
WebRequest request = HttpWebRequest.Create(url);
if (!m_outboundUrlFilter.CheckAllowed(new Uri(url)))
return false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
if (!string.IsNullOrEmpty(m_proxyurl))
{
@ -174,12 +180,14 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
}
}
RequestState state = new RequestState((HttpWebRequest) request, requestID);
RequestState state = new RequestState(request, requestID);
// IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
state.TimeOfRequest = (int) t.TotalSeconds;
return true;
}
private void HttpRequestReturn(IAsyncResult result)
@ -195,10 +203,11 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
Stream stream = null;
byte[] imageJ2000 = new byte[0];
Size newSize = new Size(0, 0);
HttpWebResponse response = null;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
response = (HttpWebResponse)request.EndGetResponse(result);
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
@ -262,18 +271,32 @@ namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
finally
{
if (stream != null)
{
stream.Close();
if (response != null)
response.Close();
if (
response.StatusCode == HttpStatusCode.MovedPermanently
|| response.StatusCode == HttpStatusCode.Found
|| response.StatusCode == HttpStatusCode.SeeOther
|| response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
string redirectedUrl = response.Headers["Location"];
MakeHttpRequest(redirectedUrl, state.RequestID);
}
else
{
m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
imageJ2000.Length, state.RequestID);
m_textureManager.ReturnData(
state.RequestID,
new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
request.RequestUri, null, imageJ2000, newSize, false));
}
}
m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
imageJ2000.Length, state.RequestID);
m_textureManager.ReturnData(
state.RequestID,
new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
request.RequestUri, null, imageJ2000, newSize, false));
}
#region Nested type: RequestState

View File

@ -244,7 +244,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_InventoryURLs[userID] = inventoryURL;
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
return;
}

View File

@ -52,6 +52,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
/// Currently valid versions are "SIMULATION/0.1" and "SIMULATION/0.2"
/// </remarks>
public string ServiceVersion { get; set; }
private float m_VersionNumber = 0.3f;
/// <summary>
/// Map region ID to scene.
@ -84,15 +85,19 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
public void InitialiseService(IConfigSource configSource)
{
ServiceVersion = "SIMULATION/0.2";
ServiceVersion = "SIMULATION/0.3";
IConfig config = configSource.Configs["SimulationService"];
if (config != null)
{
ServiceVersion = config.GetString("ConnectorProtocolVersion", ServiceVersion);
if (ServiceVersion != "SIMULATION/0.1" && ServiceVersion != "SIMULATION/0.2")
if (ServiceVersion != "SIMULATION/0.1" && ServiceVersion != "SIMULATION/0.2" && ServiceVersion != "SIMULATION/0.3")
throw new Exception(string.Format("Invalid ConnectorProtocolVersion {0}", ServiceVersion));
string[] versionComponents = ServiceVersion.Split(new char[] { '/' });
if (versionComponents.Length >= 2)
float.TryParse(versionComponents[1], out m_VersionNumber);
m_log.InfoFormat(
"[LOCAL SIMULATION CONNECTOR]: Initialized with connector protocol version {0}", ServiceVersion);
}
@ -264,7 +269,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
return true;
}
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, out string version, out string reason)
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string theirversion, out string version, out string reason)
{
reason = "Communications failure";
version = ServiceVersion;
@ -276,6 +281,22 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// s.RegionInfo.RegionName, destination.RegionHandle);
uint size = m_scenes[destination.RegionID].RegionInfo.RegionSizeX;
float theirVersionNumber = 0f;
string[] versionComponents = theirversion.Split(new char[] { '/' });
if (versionComponents.Length >= 2)
float.TryParse(versionComponents[1], out theirVersionNumber);
// Var regions here, and the requesting simulator is in an older version.
// We will forbide this, because it crashes the viewers
if (theirVersionNumber < 0.3f && size > 256)
{
reason = "Destination is a variable-sized region, and source is an old simulator. Consider upgrading.";
m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Request to access this variable-sized region from {0} simulator was denied", theirVersionNumber);
return false;
}
return m_scenes[destination.RegionID].QueryAccess(agentID, agentHomeURI, viaTeleport, position, out reason);
}

View File

@ -207,7 +207,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
return m_remoteConnector.UpdateAgent(destination, cAgentData);
}
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, out string version, out string reason)
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string sversion, out string version, out string reason)
{
reason = "Communications failure";
version = "Unknown";
@ -216,12 +216,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
return false;
// Try local first
if (m_localBackend.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, out version, out reason))
if (m_localBackend.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, sversion, out version, out reason))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, out version, out reason);
return m_remoteConnector.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, sversion, out version, out reason);
return false;
}

View File

@ -91,13 +91,17 @@ namespace OpenSim.Region.CoreModules.World
public void AddRegion(Scene scene)
{
if (!m_SceneList.Contains(scene))
m_SceneList.Add(scene);
lock (m_SceneList)
{
if (!m_SceneList.Contains(scene))
m_SceneList.Add(scene);
}
}
public void RemoveRegion(Scene scene)
{
m_SceneList.Remove(scene);
lock (m_SceneList)
m_SceneList.Remove(scene);
}
public void RegionLoaded(Scene scene)

View File

@ -918,17 +918,18 @@ namespace OpenSim.Region.CoreModules.World.Archiver
{
ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
MemoryStream ms = new MemoryStream(data);
if (m_displacement != Vector3.Zero || m_rotation != 0f)
using (MemoryStream ms = new MemoryStream(data))
{
Vector2 rotationCenter = new Vector2(m_rotationCenter.X, m_rotationCenter.Y);
terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, rotationCenter, ms);
if (m_displacement != Vector3.Zero || m_rotation != 0f)
{
Vector2 rotationCenter = new Vector2(m_rotationCenter.X, m_rotationCenter.Y);
terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, rotationCenter, ms);
}
else
{
terrainModule.LoadFromStream(terrainPath, ms);
}
}
else
{
terrainModule.LoadFromStream(terrainPath, ms);
}
ms.Close();
m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);

View File

@ -569,10 +569,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver
string terrainPath = String.Format("{0}{1}{2}.r32",
regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName);
MemoryStream ms = new MemoryStream();
scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms);
m_archiveWriter.WriteFile(terrainPath, ms.ToArray());
ms.Close();
using (MemoryStream ms = new MemoryStream())
{
scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms);
m_archiveWriter.WriteFile(terrainPath, ms.ToArray());
}
m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive.");

View File

@ -1116,9 +1116,8 @@ namespace OpenSim.Region.CoreModules.World.Estate
{
try
{
MemoryStream terrainStream = new MemoryStream(terrainData);
terr.LoadFromStream(filename, terrainStream);
terrainStream.Close();
using (MemoryStream terrainStream = new MemoryStream(terrainData))
terr.LoadFromStream(filename, terrainStream);
FileInfo x = new FileInfo(filename);
remoteClient.SendAlertMessage("Your terrain was loaded as a " + x.Extension + " file. It may take a few moments to appear.");

View File

@ -281,18 +281,8 @@ namespace OpenSim.Region.CoreModules.World.Estate
rootElement.AppendChild(result);
return DocToBytes(doc);
return Util.DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
}
}

View File

@ -858,7 +858,7 @@ namespace OpenSim.Region.CoreModules.World.Land
return null;
else
throw new Exception(
String.Format("{0} GetLandObject for non-existant position. Region={1}, pos=<{2},{3}",
String.Format("{0} GetLandObject for non-existent position. Region={1}, pos=<{2},{3}",
LogHeader, m_scene.RegionInfo.RegionName, x, y)
);
}
@ -1985,15 +1985,17 @@ namespace OpenSim.Region.CoreModules.World.Land
telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject);
// Can the user set home here?
if (// (a) gods and land managers can set home
m_scene.Permissions.IsAdministrator(remoteClient.AgentId) ||
m_scene.Permissions.IsGod(remoteClient.AgentId) ||
// (b) land owners can set home
remoteClient.AgentId == land.LandData.OwnerID ||
// (c) members of the land-associated group in roles that can set home
((gpowers & (ulong)GroupPowers.AllowSetHome) == (ulong)GroupPowers.AllowSetHome) ||
// (d) parcels with telehubs can be the home of anyone
(telehub != null && land.ContainsPoint((int)telehub.AbsolutePosition.X, (int)telehub.AbsolutePosition.Y)))
if (// Required: local user; foreign users cannot set home
m_scene.UserManagementModule.IsLocalGridUser(remoteClient.AgentId) &&
(// (a) gods and land managers can set home
m_scene.Permissions.IsAdministrator(remoteClient.AgentId) ||
m_scene.Permissions.IsGod(remoteClient.AgentId) ||
// (b) land owners can set home
remoteClient.AgentId == land.LandData.OwnerID ||
// (c) members of the land-associated group in roles that can set home
((gpowers & (ulong)GroupPowers.AllowSetHome) == (ulong)GroupPowers.AllowSetHome) ||
// (d) parcels with telehubs can be the home of anyone
(telehub != null && land.ContainsPoint((int)telehub.AbsolutePosition.X, (int)telehub.AbsolutePosition.Y))))
{
if (m_scene.GridUserService.SetHome(remoteClient.AgentId.ToString(), land.RegionUUID, position, lookAt))
// FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.

View File

@ -54,13 +54,14 @@ namespace OpenSim.Region.CoreModules.World.Serialiser
{
string xmlstream = GetObjectXml(scene);
MemoryStream stream = ReformatXmlString(xmlstream);
using (MemoryStream stream = ReformatXmlString(xmlstream))
{
stream.Seek(0, SeekOrigin.Begin);
CreateXmlFile(stream, fileName);
stream.Seek(0, SeekOrigin.Begin);
CreateXmlFile(stream, fileName);
stream.Seek(0, SeekOrigin.Begin);
CreateCompressedXmlFile(stream, fileName);
stream.Seek(0, SeekOrigin.Begin);
CreateCompressedXmlFile(stream, fileName);
}
}
private static MemoryStream ReformatXmlString(string xmlstream)
@ -112,13 +113,16 @@ namespace OpenSim.Region.CoreModules.World.Serialiser
{
#region GZip Compressed Version
FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create);
MemoryStream gzipMSStream = new MemoryStream();
GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress);
xmlStream.WriteTo(gzipStream);
gzipMSStream.WriteTo(objectsFileCompressed);
objectsFileCompressed.Flush();
objectsFileCompressed.Close();
using (FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create))
using (MemoryStream gzipMSStream = new MemoryStream())
{
using (GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress, true))
{
xmlStream.WriteTo(gzipStream);
}
gzipMSStream.WriteTo(objectsFileCompressed);
}
#endregion
}

View File

@ -1029,7 +1029,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
block.X = (ushort)minX;
block.Y = (ushort)minY;
block.Access = (byte)SimAccess.Down; // means 'simulator is offline'
// block.Access = (byte)SimAccess.NonExistant;
// block.Access = (byte)SimAccess.NonExistent;
response.Add(block);
}
// The lower 16 bits are an unsigned int16
@ -1121,32 +1121,6 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
block.SizeX = (ushort)r.RegionSizeX;
block.SizeY = (ushort)r.RegionSizeY;
blocks.Add(block);
// If these are larger than legacy regions, create fake map entries for the covered
// regions. The map system only does legacy sized regions so we have to fake map
// entries for all the covered regions.
if (r.RegionSizeX > Constants.RegionSize || r.RegionSizeY > Constants.RegionSize)
{
for (int x = 0; x < r.RegionSizeX / Constants.RegionSize; x++)
{
for (int y = 0; y < r.RegionSizeY / Constants.RegionSize; y++)
{
if (x == 0 && y == 0)
continue;
block = new MapBlockData
{
Access = r.Access,
MapImageId = r.TerrainImage,
Name = r.RegionName,
X = (ushort)((r.RegionLocX / Constants.RegionSize) + x),
Y = (ushort)((r.RegionLocY / Constants.RegionSize) + y),
SizeX = (ushort)r.RegionSizeX,
SizeY = (ushort)r.RegionSizeY
};
//Child piece, so ignore it
blocks.Add(block);
}
}
}
}
return blocks;
}
@ -1171,7 +1145,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
if (myMapImageJPEG.Length == 0)
{
MemoryStream imgstream = new MemoryStream();
MemoryStream imgstream = null;
Bitmap mapTexture = new Bitmap(1,1);
ManagedImage managedImage;
Image image = (Image)mapTexture;
@ -1218,10 +1192,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
image.Dispose();
if (imgstream != null)
{
imgstream.Close();
imgstream.Dispose();
}
}
}
else
@ -1467,7 +1438,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
public void GenerateMaptile()
{
// Cannot create a map for a nonexistant heightmap
// Cannot create a map for a nonexistent heightmap
if (m_scene.Heightmap == null)
return;
@ -1578,12 +1549,20 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
private Byte[] GenerateOverlay()
{
using (Bitmap overlay = new Bitmap(256, 256))
// These need to be ints for bitmap generation
int regionSizeX = (int)m_scene.RegionInfo.RegionSizeX;
int regionSizeY = (int)m_scene.RegionInfo.RegionSizeY;
int landTileSize = LandManagementModule.LandUnit;
int regionLandTilesX = regionSizeX / landTileSize;
int regionLandTilesY = regionSizeY / landTileSize;
using (Bitmap overlay = new Bitmap(regionSizeX, regionSizeY))
{
bool[,] saleBitmap = new bool[64, 64];
for (int x = 0 ; x < 64 ; x++)
bool[,] saleBitmap = new bool[regionLandTilesX, regionLandTilesY];
for (int x = 0; x < regionLandTilesX; x++)
{
for (int y = 0 ; y < 64 ; y++)
for (int y = 0; y < regionLandTilesY; y++)
saleBitmap[x, y] = false;
}
@ -1596,8 +1575,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
using (Graphics g = Graphics.FromImage(overlay))
{
using (SolidBrush transparent = new SolidBrush(background))
g.FillRectangle(transparent, 0, 0, 256, 256);
g.FillRectangle(transparent, 0, 0, regionSizeX, regionSizeY);
foreach (ILandObject land in parcels)
{
@ -1620,12 +1598,16 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
using (SolidBrush yellow = new SolidBrush(Color.FromArgb(255, 249, 223, 9)))
{
for (int x = 0 ; x < 64 ; x++)
for (int x = 0 ; x < regionLandTilesX ; x++)
{
for (int y = 0 ; y < 64 ; y++)
for (int y = 0 ; y < regionLandTilesY ; y++)
{
if (saleBitmap[x, y])
g.FillRectangle(yellow, x * 4, 252 - (y * 4), 4, 4);
g.FillRectangle(
yellow, x * landTileSize,
regionSizeX - landTileSize - (y * landTileSize),
landTileSize,
landTileSize);
}
}
}

View File

@ -373,38 +373,41 @@ namespace OpenSim.Region.DataSnapshot
for (int i = 0; i < services.Length; i++)
{
string url = services[i].Trim();
RestClient cli = new RestClient(url);
cli.AddQueryParameter("service", serviceName);
cli.AddQueryParameter("host", m_hostname);
cli.AddQueryParameter("port", m_listener_port);
cli.AddQueryParameter("secret", m_Secret.ToString());
cli.RequestMethod = "GET";
try
using (RestClient cli = new RestClient(url))
{
reply = cli.Request(null);
cli.AddQueryParameter("service", serviceName);
cli.AddQueryParameter("host", m_hostname);
cli.AddQueryParameter("port", m_listener_port);
cli.AddQueryParameter("secret", m_Secret.ToString());
cli.RequestMethod = "GET";
try
{
reply = cli.Request(null);
}
catch (WebException)
{
m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url);
}
catch (Exception e)
{
m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString());
}
byte[] response = new byte[1024];
// int n = 0;
try
{
// n = reply.Read(response, 0, 1024);
reply.Read(response, 0, 1024);
}
catch (Exception e)
{
m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace);
}
// This is not quite working, so...
// string responseStr = Util.UTF8.GetString(response);
m_log.Info("[DATASNAPSHOT]: data service " + url + " notified. Secret: " + m_Secret);
}
catch (WebException)
{
m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url);
}
catch (Exception e)
{
m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString());
}
byte[] response = new byte[1024];
// int n = 0;
try
{
// n = reply.Read(response, 0, 1024);
reply.Read(response, 0, 1024);
}
catch (Exception e)
{
m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace);
}
// This is not quite working, so...
// string responseStr = Util.UTF8.GetString(response);
m_log.Info("[DATASNAPSHOT]: data service " + url + " notified. Secret: " + m_Secret);
}
}

View File

@ -25,6 +25,7 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
@ -41,10 +42,44 @@ namespace OpenSim.Region.Framework.Interfaces
HTTP_PRAGMA_NO_CACHE = 6
}
/// <summary>
/// The initial status of the request before it is placed on the wire.
/// </summary>
/// <remarks>
/// The request may still fail later on, in which case the normal HTTP status is set.
/// </remarks>
[Flags]
public enum HttpInitialRequestStatus
{
OK = 1,
DISALLOWED_BY_FILTER = 2
}
public interface IHttpRequestModule
{
UUID MakeHttpRequest(string url, string parameters, string body);
UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body);
/// <summary>
/// Starts the http request.
/// </summary>
/// <remarks>
/// This is carried out asynchronously unless it fails initial checks. Results are fetched by the script engine
/// HTTP requests module to be distributed back to scripts via a script event.
/// </remarks>
/// <returns>The ID of the request. If the requested could not be performed then this is UUID.Zero</returns>
/// <param name="localID">Local ID of the object containing the script making the request.</param>
/// <param name="itemID">Item ID of the script making the request.</param>
/// <param name="url">Url to request.</param>
/// <param name="parameters">LSL parameters for the request.</param>
/// <param name="headers">Extra headers for the request.</param>
/// <param name="body">Body of the request.</param>
/// <param name="status">
/// Initial status of the request. If OK then the request is actually made to the URL. Subsequent status is
/// then returned via IServiceRequest when the response is asynchronously fetched.
/// </param>
UUID StartHttpRequest(
uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
out HttpInitialRequestStatus status);
/// <summary>
/// Stop and remove all http requests for the given script.

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
@ -113,31 +113,34 @@ namespace OpenSim.Region.Framework.Scenes.Animation
public byte[] ToBytes()
{
byte[] outputbytes = new byte[0];
byte[] outputbytes;
BinaryWriter iostream = new BinaryWriter(new MemoryStream());
iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown0)));
iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown1)));
iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(Length)));
iostream.Write(BinBVHUtil.WriteNullTerminatedString(ExpressionName));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(InPoint)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(OutPoint)));
iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Loop ? 1 : 0)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseInTime)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseOutTime)));
iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes(HandPose)));
iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes((uint)(Joints.Length))));
for (int i = 0; i < Joints.Length; i++)
using (MemoryStream ms = new MemoryStream())
using (BinaryWriter iostream = new BinaryWriter(ms))
{
Joints[i].WriteBytesToStream(iostream, InPoint, OutPoint);
iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown0)));
iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown1)));
iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(Length)));
iostream.Write(BinBVHUtil.WriteNullTerminatedString(ExpressionName));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(InPoint)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(OutPoint)));
iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Loop ? 1 : 0)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseInTime)));
iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseOutTime)));
iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes(HandPose)));
iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes((uint)(Joints.Length))));
for (int i = 0; i < Joints.Length; i++)
{
Joints[i].WriteBytesToStream(iostream, InPoint, OutPoint);
}
iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(0)));
using (MemoryStream ms2 = (MemoryStream)iostream.BaseStream)
outputbytes = ms2.ToArray();
}
iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(0)));
MemoryStream ms = (MemoryStream)iostream.BaseStream;
outputbytes = ms.ToArray();
ms.Close();
iostream.Close();
return outputbytes;
}

View File

@ -280,7 +280,7 @@ namespace OpenSim.Region.Framework.Scenes
if (!m_selected)
{
StopTimer();
m_serializedPosition = m_group.AbsolutePosition;
m_serializedPosition = m_group.AbsolutePosition;
}
}
}
@ -308,10 +308,11 @@ namespace OpenSim.Region.Framework.Scenes
try
{
MemoryStream ms = new MemoryStream(data);
BinaryFormatter fmt = new BinaryFormatter();
newMotion = (KeyframeMotion)fmt.Deserialize(ms);
using (MemoryStream ms = new MemoryStream(data))
{
BinaryFormatter fmt = new BinaryFormatter();
newMotion = (KeyframeMotion)fmt.Deserialize(ms);
}
newMotion.m_group = grp;
@ -345,26 +346,26 @@ namespace OpenSim.Region.Framework.Scenes
return;
m_group = grp;
m_scene = grp.Scene;
m_scene = grp.Scene;
Vector3 grppos = grp.AbsolutePosition;
Vector3 offset = grppos - m_serializedPosition;
Vector3 offset = grppos - m_serializedPosition;
// avoid doing it more than once
// current this will happen dragging a prim to other region
m_serializedPosition = grppos;
m_basePosition += offset;
m_nextPosition += offset;
m_currentFrame.StartPosition += offset;
m_currentFrame.Position += offset;
m_currentFrame.Position += offset;
for (int i = 0; i < m_frames.Count; i++)
{
Keyframe k = m_frames[i];
k.StartPosition += offset;
k.Position += offset;
m_frames[i]=k;
m_frames[i]=k;
}
if (m_running)
@ -527,7 +528,7 @@ namespace OpenSim.Region.Framework.Scenes
{
k.Position = pos;
// k.Velocity = Vector3.Zero;
}
}
k.StartRotation = rot;
if (k.Rotation.HasValue)
@ -764,19 +765,22 @@ namespace OpenSim.Region.Framework.Scenes
public Byte[] Serialize()
{
StopTimer();
MemoryStream ms = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
SceneObjectGroup tmp = m_group;
m_group = null;
if (!m_selected && tmp != null)
m_serializedPosition = tmp.AbsolutePosition;
fmt.Serialize(ms, this);
m_group = tmp;
if (m_running && !m_waitingCrossing)
StartTimer();
m_group = null;
if (!m_selected && tmp != null)
m_serializedPosition = tmp.AbsolutePosition;
return ms.ToArray();
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(ms, this);
m_group = tmp;
if (m_running && !m_waitingCrossing)
StartTimer();
return ms.ToArray();
}
}
public void StartCrossingCheck()

View File

@ -1226,16 +1226,21 @@ namespace OpenSim.Region.Framework.Scenes
agentItem.BasePermissions = taskItem.BasePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
if (taskItem.InvType == (int)InventoryType.Object)
{
uint perms = taskItem.CurrentPermissions;
// Bake the new base permissions from folded permissions
// The folded perms are in the lowest 3 bits of the current perms
// We use base permissions here to avoid baking the "Locked" status
// into the item as it is passed.
uint perms = taskItem.BasePermissions & taskItem.NextPermissions;
PermissionsUtil.ApplyFoldedPermissions(taskItem.CurrentPermissions, ref perms);
// Avoid the "lock trap" - move must always be enabled but the above may remove it
// Add it back here.
agentItem.BasePermissions = perms | (uint)PermissionMask.Move;
agentItem.CurrentPermissions = agentItem.BasePermissions;
}
else
{
agentItem.CurrentPermissions = agentItem.BasePermissions & taskItem.CurrentPermissions;
// Newly given items cannot be "locked" on rez. Make sure by
// setting current equal to base.
}
agentItem.CurrentPermissions = agentItem.BasePermissions;
agentItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
agentItem.NextPermissions = taskItem.NextPermissions;
agentItem.EveryOnePermissions = taskItem.EveryonePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
@ -1934,8 +1939,11 @@ namespace OpenSim.Region.Framework.Scenes
/// Rez a script into a prim's inventory from another prim
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"> </param>
/// <param name="localID"></param>
/// <param name="srcPart"> </param>
/// <param name="destId"> </param>
/// <param name="pin"></param>
/// <param name="running"></param>
/// <param name="start_param"></param>
public void RezScriptFromPrim(UUID srcId, SceneObjectPart srcPart, UUID destId, int pin, int running, int start_param)
{
TaskInventoryItem srcTaskItem = srcPart.Inventory.GetInventoryItem(srcId);
@ -1955,12 +1963,11 @@ namespace OpenSim.Region.Framework.Scenes
if (destPart == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Could not find script for ID {0}",
destId);
"[PRIM INVENTORY]: Could not find part {0} to insert script item {1} from {2} {3} in {4}",
destId, srcId, srcPart.Name, srcPart.UUID, Name);
return;
}
// Must own the object, and have modify rights
if (srcPart.OwnerID != destPart.OwnerID)
{
@ -1968,12 +1975,14 @@ namespace OpenSim.Region.Framework.Scenes
if ((destPart.GroupID == UUID.Zero) || (destPart.GroupID != srcPart.GroupID) ||
((destPart.GroupMask & (uint)PermissionMask.Modify) == 0))
return;
} else {
}
else
{
if ((destPart.OwnerMask & (uint)PermissionMask.Modify) == 0)
return;
}
if (destPart.ScriptAccessPin != pin)
if (destPart.ScriptAccessPin == 0 || destPart.ScriptAccessPin != pin)
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +

View File

@ -192,7 +192,7 @@ namespace OpenSim.Region.Framework.Scenes
/// <summary>
/// Maximum value of the size of a physical prim in each axis
/// </summary>
public float m_maxPhys = 10;
public float m_maxPhys = 64;
/// <summary>
/// Max prims an object will hold
@ -201,7 +201,7 @@ namespace OpenSim.Region.Framework.Scenes
public bool m_clampPrimSize;
public bool m_trustBinaries;
public bool m_allowScriptCrossings;
public bool m_allowScriptCrossings = true;
public bool m_useFlySlow;
public bool m_useTrashOnDelete = true;
@ -1069,18 +1069,22 @@ namespace OpenSim.Region.Framework.Scenes
/// <returns>True after all operations complete, throws exceptions otherwise.</returns>
public override void OtherRegionUp(GridRegion otherRegion)
{
uint xcell = Util.WorldToRegionLoc((uint)otherRegion.RegionLocX);
uint ycell = Util.WorldToRegionLoc((uint)otherRegion.RegionLocY);
//m_log.InfoFormat("[SCENE]: (on region {0}): Region {1} up in coords {2}-{3}",
// RegionInfo.RegionName, otherRegion.RegionName, xcell, ycell);
if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
{
// If these are cast to INT because long + negative values + abs returns invalid data
int resultX = Math.Abs((int)xcell - (int)RegionInfo.RegionLocX);
int resultY = Math.Abs((int)ycell - (int)RegionInfo.RegionLocY);
if (resultX <= 1 && resultY <= 1)
//// If these are cast to INT because long + negative values + abs returns invalid data
//int resultX = Math.Abs((int)xcell - (int)RegionInfo.RegionLocX);
//int resultY = Math.Abs((int)ycell - (int)RegionInfo.RegionLocY);
//if (resultX <= 1 && resultY <= 1)
float dist = (float)Math.Max(DefaultDrawDistance,
(float)Math.Max(RegionInfo.RegionSizeX, RegionInfo.RegionSizeY));
uint newRegionX, newRegionY, thisRegionX, thisRegionY;
Util.RegionHandleToRegionLoc(otherRegion.RegionHandle, out newRegionX, out newRegionY);
Util.RegionHandleToRegionLoc(RegionInfo.RegionHandle, out thisRegionX, out thisRegionY);
//m_log.InfoFormat("[SCENE]: (on region {0}): Region {1} up in coords {2}-{3}",
// RegionInfo.RegionName, otherRegion.RegionName, newRegionX, newRegionY);
if (!Util.IsOutsideView(dist, thisRegionX, newRegionX, thisRegionY, newRegionY))
{
// Let the grid service module know, so this can be cached
m_eventManager.TriggerOnRegionUp(otherRegion);
@ -1894,6 +1898,7 @@ namespace OpenSim.Region.Framework.Scenes
RegionInfo.RegionID,
RegionInfo.RegionLocX, RegionInfo.RegionLocY,
RegionInfo.RegionSizeX, RegionInfo.RegionSizeY);
if (error != String.Empty)
throw new Exception(error);
}
@ -3214,10 +3219,6 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
else
{
m_authenticateHandler.RemoveCircuit(agentID);
}
// TODO: Can we now remove this lock?
lock (acd)
@ -3233,7 +3234,8 @@ namespace OpenSim.Region.Framework.Scenes
{
m_log.ErrorFormat(
"[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in the scene.", agentID);
m_authenticateHandler.RemoveCircuit(agentID);
return;
}
@ -3310,6 +3312,7 @@ namespace OpenSim.Region.Framework.Scenes
// Always clean these structures up so that any failure above doesn't cause them to remain in the
// scene with possibly bad effects (e.g. continually timing out on unacked packets and triggering
// the same cleanup exception continually.
m_authenticateHandler.RemoveCircuit(agentID);
m_sceneGraph.RemoveScenePresence(agentID);
m_clientManager.Remove(agentID);
@ -3462,7 +3465,7 @@ namespace OpenSim.Region.Framework.Scenes
{
foreach (string viewer in m_AllowedViewers)
{
if (viewer == curViewer.Substring(0, viewer.Length).Trim().ToLower())
if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
{
ViewerDenied = false;
break;
@ -3479,7 +3482,7 @@ namespace OpenSim.Region.Framework.Scenes
{
foreach (string viewer in m_BannedViewers)
{
if (viewer == curViewer.Substring(0, viewer.Length).Trim().ToLower())
if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
{
ViewerDenied = true;
break;

View File

@ -1906,7 +1906,7 @@ namespace OpenSim.Region.Framework.Scenes
if (original == null)
{
m_log.WarnFormat(
"[SCENEGRAPH]: Attempt to duplicate nonexistant prim id {0} by {1}", originalPrimID, AgentID);
"[SCENEGRAPH]: Attempt to duplicate nonexistent prim id {0} by {1}", originalPrimID, AgentID);
return null;
}

View File

@ -568,7 +568,7 @@ namespace OpenSim.Region.Framework.Scenes
}
else
{
m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar alreasy in transit {0} to {1}", av.Name, val);
m_log.DebugFormat("[SCENE OBJECT]: Not crossing avatar {0} to {1} because it's already in transit", av.Name, val);
}
}

View File

@ -870,8 +870,8 @@ namespace OpenSim.Region.Framework.Scenes
int type = m_items[itemID].InvType;
if (type == 10) // Script
{
m_part.RemoveScriptEvents(itemID);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
// route it through here, to handle script cleanup tasks
RemoveScriptInstance(itemID, false);
}
m_items.Remove(itemID);
m_inventorySerial++;

View File

@ -1192,19 +1192,17 @@ namespace OpenSim.Region.Framework.Scenes
// and it has already rezzed the attachments and started their scripts.
// We do the following only for non-login agents, because their scripts
// haven't started yet.
if (PresenceType == PresenceType.Npc || (TeleportFlags & TeleportFlags.ViaLogin) != 0)
if (PresenceType == PresenceType.Npc || IsRealLogin(m_teleportFlags))
{
// Viewers which have a current outfit folder will actually rez their own attachments. However,
// viewers without (e.g. v1 viewers) will not, so we still need to make this call.
if (Scene.AttachmentsModule != null)
Util.FireAndForget(
o =>
{
// if (PresenceType != PresenceType.Npc && Util.FireAndForgetMethod != FireAndForgetMethod.None)
// System.Threading.Thread.Sleep(7000);
Scene.AttachmentsModule.RezAttachments(this);
});
{
Util.FireAndForget(o =>
{
Scene.AttachmentsModule.RezAttachments(this);
});
}
}
else
{
@ -1266,6 +1264,11 @@ namespace OpenSim.Region.Framework.Scenes
return true;
}
private static bool IsRealLogin(TeleportFlags teleportFlags)
{
return ((teleportFlags & TeleportFlags.ViaLogin) != 0) && ((teleportFlags & TeleportFlags.ViaHGLogin) == 0);
}
/// <summary>
/// Force viewers to show the avatar's current name.
/// </summary>
@ -1691,109 +1694,122 @@ namespace OpenSim.Region.Framework.Scenes
"[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
client.Name, Scene.Name, AbsolutePosition);
// Make sure it's not a login agent. We don't want to wait for updates during login
if (PresenceType != PresenceType.Npc && (m_teleportFlags & TeleportFlags.ViaLogin) == 0)
bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0); // Get this ahead of time because IsInTransit modifies 'm_AgentControlFlags'
IsInTransit = true;
try
{
// Let's wait until UpdateAgent (called by departing region) is done
if (!WaitForUpdateAgent(client))
// The sending region never sent the UpdateAgent data, we have to refuse
// Make sure it's not a login agent. We don't want to wait for updates during login
if (!(PresenceType == PresenceType.Npc || IsRealLogin(m_teleportFlags)))
{
// Let's wait until UpdateAgent (called by departing region) is done
if (!WaitForUpdateAgent(client))
// The sending region never sent the UpdateAgent data, we have to refuse
return;
}
Vector3 look = Velocity;
// if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
if ((Math.Abs(look.X) < 0.1) && (Math.Abs(look.Y) < 0.1) && (Math.Abs(look.Z) < 0.1))
{
look = new Vector3(0.99f, 0.042f, 0);
}
// Prevent teleporting to an underground location
// (may crash client otherwise)
//
Vector3 pos = AbsolutePosition;
float ground = m_scene.GetGroundHeight(pos.X, pos.Y);
if (pos.Z < ground + 1.5f)
{
pos.Z = ground + 1.5f;
AbsolutePosition = pos;
}
if (!MakeRootAgent(AbsolutePosition, flying))
{
m_log.DebugFormat(
"[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
Name, Scene.Name);
return;
}
// Tell the client that we're totally ready
ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
// Remember in HandleUseCircuitCode, we delayed this to here
if (m_teleportFlags > 0)
SendInitialDataToMe();
// m_log.DebugFormat("[SCENE PRESENCE] Completed movement");
if (!string.IsNullOrEmpty(m_callbackURI))
{
// We cannot sleep here since this would hold up the inbound packet processing thread, as
// CompleteMovement() is executed synchronously. However, it might be better to delay the release
// here until we know for sure that the agent is active in this region. Sending AgentMovementComplete
// is not enough for Imprudence clients - there appears to be a small delay (<200ms, <500ms) until they regard this
// region as the current region, meaning that a close sent before then will fail the teleport.
// System.Threading.Thread.Sleep(2000);
m_log.DebugFormat(
"[SCENE PRESENCE]: Releasing {0} {1} with callback to {2}",
client.Name, client.AgentId, m_callbackURI);
UUID originID;
lock (m_originRegionIDAccessLock)
originID = m_originRegionID;
Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
m_callbackURI = null;
}
// else
// {
// m_log.DebugFormat(
// "[SCENE PRESENCE]: No callback provided on CompleteMovement of {0} {1} to {2}",
// client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
// }
ValidateAndSendAppearanceAndAgentData();
// Create child agents in neighbouring regions
if (openChildAgents && !IsChildAgent)
{
IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
if (m_agentTransfer != null)
{
// Note: this call can take a while, because it notifies each of the simulator's neighbours.
// It's important that we don't allow the avatar to cross regions meanwhile, as that will
// cause serious errors. We've prevented that from happening by setting IsInTransit=true.
m_agentTransfer.EnableChildAgents(this);
}
IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
if (friendsModule != null)
friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
}
// XXX: If we force an update here, then multiple attachments do appear correctly on a destination region
// If we do it a little bit earlier (e.g. when converting the child to a root agent) then this does not work.
// This may be due to viewer code or it may be something we're not doing properly simulator side.
lock (m_attachments)
{
foreach (SceneObjectGroup sog in m_attachments)
sog.ScheduleGroupForFullUpdate();
}
// m_log.DebugFormat(
// "[SCENE PRESENCE]: Completing movement of {0} into region {1} took {2}ms",
// client.Name, Scene.RegionInfo.RegionName, (DateTime.Now - startTime).Milliseconds);
}
Vector3 look = Velocity;
// if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
if ((Math.Abs(look.X) < 0.1) && (Math.Abs(look.Y) < 0.1) && (Math.Abs(look.Z) < 0.1))
finally
{
look = new Vector3(0.99f, 0.042f, 0);
IsInTransit = false;
}
// Prevent teleporting to an underground location
// (may crash client otherwise)
//
Vector3 pos = AbsolutePosition;
float ground = m_scene.GetGroundHeight(pos.X, pos.Y);
if (pos.Z < ground + 1.5f)
{
pos.Z = ground + 1.5f;
AbsolutePosition = pos;
}
bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
if (!MakeRootAgent(AbsolutePosition, flying))
{
m_log.DebugFormat(
"[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
Name, Scene.Name);
return;
}
// Tell the client that we're totally ready
ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
// Remember in HandleUseCircuitCode, we delayed this to here
if (m_teleportFlags > 0)
SendInitialDataToMe();
// m_log.DebugFormat("[SCENE PRESENCE] Completed movement");
if (!string.IsNullOrEmpty(m_callbackURI))
{
// We cannot sleep here since this would hold up the inbound packet processing thread, as
// CompleteMovement() is executed synchronously. However, it might be better to delay the release
// here until we know for sure that the agent is active in this region. Sending AgentMovementComplete
// is not enough for Imprudence clients - there appears to be a small delay (<200ms, <500ms) until they regard this
// region as the current region, meaning that a close sent before then will fail the teleport.
// System.Threading.Thread.Sleep(2000);
m_log.DebugFormat(
"[SCENE PRESENCE]: Releasing {0} {1} with callback to {2}",
client.Name, client.AgentId, m_callbackURI);
UUID originID;
lock (m_originRegionIDAccessLock)
originID = m_originRegionID;
Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
m_callbackURI = null;
}
// else
// {
// m_log.DebugFormat(
// "[SCENE PRESENCE]: No callback provided on CompleteMovement of {0} {1} to {2}",
// client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
// }
ValidateAndSendAppearanceAndAgentData();
// Create child agents in neighbouring regions
if (openChildAgents && !IsChildAgent)
{
IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
if (m_agentTransfer != null)
m_agentTransfer.EnableChildAgents(this);
IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
if (friendsModule != null)
friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
}
// XXX: If we force an update here, then multiple attachments do appear correctly on a destination region
// If we do it a little bit earlier (e.g. when converting the child to a root agent) then this does not work.
// This may be due to viewer code or it may be something we're not doing properly simulator side.
lock (m_attachments)
{
foreach (SceneObjectGroup sog in m_attachments)
sog.ScheduleGroupForFullUpdate();
}
// m_log.DebugFormat(
// "[SCENE PRESENCE]: Completing movement of {0} into region {1} took {2}ms",
// client.Name, Scene.RegionInfo.RegionName, (DateTime.Now - startTime).Milliseconds);
}
/// <summary>
@ -3257,7 +3273,11 @@ namespace OpenSim.Region.Framework.Scenes
float distanceError = Vector3.Distance(OffsetPosition, expectedPosition);
float speed = Velocity.Length();
float velocidyDiff = Vector3.Distance(lastVelocitySentToAllClients, Velocity);
float velocityDiff = Vector3.Distance(lastVelocitySentToAllClients, Velocity);
// m_log.DebugFormat(
// "[SCENE PRESENCE]: Delta-v {0}, lastVelocity {1}, Velocity {2} for {3} in {4}",
// velocidyDiff, lastVelocitySentToAllClients, Velocity, Name, Scene.Name);
// assuming 5 ms. worst case precision for timer, use 2x that
// for distance error threshold
@ -3265,8 +3285,12 @@ namespace OpenSim.Region.Framework.Scenes
if (speed < 0.01f // allow rotation updates if avatar position is unchanged
|| Math.Abs(distanceError) > distanceErrorThreshold
|| velocidyDiff > 0.01f) // did velocity change from last update?
|| velocityDiff > 0.01f) // did velocity change from last update?
{
// m_log.DebugFormat(
// "[SCENE PRESENCE]: Update triggered with speed {0}, distanceError {1}, distanceThreshold {2}, delta-v {3} for {4} in {5}",
// speed, distanceError, distanceErrorThreshold, velocidyDiff, Name, Scene.Name);
lastVelocitySentToAllClients = Velocity;
lastTerseUpdateToAllClientsTick = currentTick;
lastPositionSentToAllClients = OffsetPosition;
@ -3579,65 +3603,50 @@ namespace OpenSim.Region.Framework.Scenes
if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
return;
if (!IsInTransit)
if (IsInTransit)
return;
Vector3 pos2 = AbsolutePosition;
Vector3 origPosition = pos2;
Vector3 vel = Velocity;
// Compute the avatar position in the next physics tick.
// If the avatar will be crossing, we force the crossing to happen now
// in the hope that this will make the avatar movement smoother when crossing.
float timeStep = 0.1f;
pos2.X = pos2.X + (vel.X * timeStep);
pos2.Y = pos2.Y + (vel.Y * timeStep);
pos2.Z = pos2.Z + (vel.Z * timeStep);
if (m_scene.PositionIsInCurrentRegion(pos2))
return;
m_log.DebugFormat("{0} CheckForBorderCrossing: position outside region. {1} in {2} at pos {3}",
LogHeader, Name, Scene.Name, pos2);
// Disconnect from the current region
bool isFlying = Flying;
RemoveFromPhysicalScene();
// pos2 is the forcasted position so make that the 'current' position so the crossing
// code will move us into the newly addressed region.
m_pos = pos2;
if (CrossToNewRegion())
{
Vector3 pos2 = AbsolutePosition;
Vector3 origPosition = pos2;
Vector3 vel = Velocity;
// Compute the avatar position in the next physics tick.
// If the avatar will be crossing, we force the crossing to happen now
// in the hope that this will make the avatar movement smoother when crossing.
float timeStep = 0.1f;
pos2.X = pos2.X + (vel.X * timeStep);
pos2.Y = pos2.Y + (vel.Y * timeStep);
pos2.Z = pos2.Z + (vel.Z * timeStep);
if (!IsInTransit)
AddToPhysicalScene(isFlying);
}
else
{
// Tried to make crossing happen but it failed.
if (m_requestedSitTargetUUID == UUID.Zero)
{
if (!m_scene.PositionIsInCurrentRegion(pos2))
{
m_log.DebugFormat("{0} CheckForBorderCrossing: position outside region. {1} in {2} at pos {3}",
LogHeader, Name, Scene.Name, pos2);
m_log.DebugFormat("{0} CheckForBorderCrossing: Crossing failed. Restoring old position.", LogHeader);
// Disconnect from the current region
bool isFlying = Flying;
RemoveFromPhysicalScene();
// pos2 is the forcasted position so make that the 'current' position so the crossing
// code will move us into the newly addressed region.
m_pos = pos2;
if (CrossToNewRegion())
{
AddToPhysicalScene(isFlying);
}
else
{
// Tried to make crossing happen but it failed.
if (m_requestedSitTargetUUID == UUID.Zero)
{
m_log.DebugFormat("{0} CheckForBorderCrossing: Crossing failed. Restoring old position.", LogHeader);
Velocity = Vector3.Zero;
AbsolutePosition = EnforceSanityOnPosition(origPosition);
Velocity = Vector3.Zero;
AbsolutePosition = EnforceSanityOnPosition(origPosition);
AddToPhysicalScene(isFlying);
}
}
}
AddToPhysicalScene(isFlying);
}
else
{
// This constant has been inferred from experimentation
// I'm not sure what this value should be, so I tried a few values.
timeStep = 0.04f;
pos2 = AbsolutePosition;
pos2.X = pos2.X + (vel.X * timeStep);
pos2.Y = pos2.Y + (vel.Y * timeStep);
// Don't touch the Z
m_pos = pos2;
m_log.DebugFormat("[SCENE PRESENCE]: In transit m_pos={0}", m_pos);
}
}
}
}
// Given a position, make sure it is within the current region.
@ -3725,7 +3734,9 @@ namespace OpenSim.Region.Framework.Scenes
// m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX)));
// m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY)));
if (Util.IsOutsideView(DrawDistance, x, newRegionX, y, newRegionY))
float dist = (float)Math.Max(Scene.DefaultDrawDistance,
(float)Math.Max(Scene.RegionInfo.RegionSizeX, Scene.RegionInfo.RegionSizeY));
if (Util.IsOutsideView(dist, x, newRegionX, y, newRegionY))
{
byebyeRegions.Add(handle);
}

View File

@ -0,0 +1,249 @@
/*
* 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.Net;
using Mono.Addins;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim;
using OpenSim.ApplicationPlugins.RegionModulesController;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.Framework.Scenes.Tests
{
public class SharedRegionModuleTests : OpenSimTestCase
{
// [Test]
public void TestLifecycle()
{
TestHelpers.InMethod();
TestHelpers.EnableLogging();
UUID estateOwnerId = TestHelpers.ParseTail(0x1);
UUID regionId = TestHelpers.ParseTail(0x10);
IConfigSource configSource = new IniConfigSource();
configSource.AddConfig("Startup");
configSource.AddConfig("Modules");
// // We use this to skip estate questions
// Turns out not to be needed is estate owner id is pre-set in region information.
// IConfig estateConfig = configSource.AddConfig(OpenSimBase.ESTATE_SECTION_NAME);
// estateConfig.Set("DefaultEstateOwnerName", "Zaphod Beeblebrox");
// estateConfig.Set("DefaultEstateOwnerUUID", estateOwnerId);
// estateConfig.Set("DefaultEstateOwnerEMail", "zaphod@galaxy.com");
// estateConfig.Set("DefaultEstateOwnerPassword", "two heads");
// For grid servic
configSource.AddConfig("GridService");
configSource.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
configSource.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData");
configSource.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
configSource.Configs["GridService"].Set("ConnectionString", "!static");
LocalGridServicesConnector gridService = new LocalGridServicesConnector();
//
OpenSim sim = new OpenSim(configSource);
sim.SuppressExit = true;
sim.EnableInitialPluginLoad = false;
sim.LoadEstateDataService = false;
sim.NetServersInfo.HttpListenerPort = 0;
IRegistryCore reg = sim.ApplicationRegistry;
RegionInfo ri = new RegionInfo();
ri.RegionID = regionId;
ri.EstateSettings.EstateOwner = estateOwnerId;
ri.InternalEndPoint = new IPEndPoint(0, 0);
MockRegionModulesControllerPlugin rmcp = new MockRegionModulesControllerPlugin();
sim.m_plugins = new List<IApplicationPlugin>() { rmcp };
reg.RegisterInterface<IRegionModulesController>(rmcp);
// XXX: Have to initialize directly for now
rmcp.Initialise(sim);
rmcp.AddNode(gridService);
TestSharedRegion tsr = new TestSharedRegion();
rmcp.AddNode(tsr);
// FIXME: Want to use the real one eventually but this is currently directly tied into Mono.Addins
// which has been written in such a way that makes it impossible to use for regression tests.
// RegionModulesControllerPlugin rmcp = new RegionModulesControllerPlugin();
// rmcp.LoadModulesFromAddins = false;
//// reg.RegisterInterface<IRegionModulesController>(rmcp);
// rmcp.Initialise(sim);
// rmcp.PostInitialise();
// TypeExtensionNode node = new TypeExtensionNode();
// node.
// rmcp.AddNode(node, configSource.Configs["Modules"], new Dictionary<RuntimeAddin, IList<int>>());
sim.Startup();
IScene scene;
sim.CreateRegion(ri, out scene);
sim.Shutdown();
List<string> co = tsr.CallOrder;
int expectedEventCount = 6;
Assert.AreEqual(
expectedEventCount,
co.Count,
"Expected {0} events but only got {1} ({2})",
expectedEventCount, co.Count, string.Join(",", co));
Assert.AreEqual("Initialise", co[0]);
Assert.AreEqual("PostInitialise", co[1]);
Assert.AreEqual("AddRegion", co[2]);
Assert.AreEqual("RegionLoaded", co[3]);
Assert.AreEqual("RemoveRegion", co[4]);
Assert.AreEqual("Close", co[5]);
}
}
class TestSharedRegion : ISharedRegionModule
{
// FIXME: Should really use MethodInfo
public List<string> CallOrder = new List<string>();
public string Name { get { return "TestSharedRegion"; } }
public Type ReplaceableInterface { get { return null; } }
public void PostInitialise()
{
CallOrder.Add("PostInitialise");
}
public void Initialise(IConfigSource source)
{
CallOrder.Add("Initialise");
}
public void Close()
{
CallOrder.Add("Close");
}
public void AddRegion(Scene scene)
{
CallOrder.Add("AddRegion");
}
public void RemoveRegion(Scene scene)
{
CallOrder.Add("RemoveRegion");
}
public void RegionLoaded(Scene scene)
{
CallOrder.Add("RegionLoaded");
}
}
class MockRegionModulesControllerPlugin : IRegionModulesController, IApplicationPlugin
{
// List of shared module instances, for adding to Scenes
private List<ISharedRegionModule> m_sharedInstances = new List<ISharedRegionModule>();
// Config access
private OpenSimBase m_openSim;
public string Version { get { return "0"; } }
public string Name { get { return "MockRegionModulesControllerPlugin"; } }
public void Initialise() {}
public void Initialise(OpenSimBase sim)
{
m_openSim = sim;
}
/// <summary>
/// Called when the application loading is completed
/// </summary>
public void PostInitialise()
{
foreach (ISharedRegionModule module in m_sharedInstances)
module.PostInitialise();
}
public void AddRegionToModules(Scene scene)
{
List<ISharedRegionModule> sharedlist = new List<ISharedRegionModule>();
foreach (ISharedRegionModule module in m_sharedInstances)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
sharedlist.Add(module);
}
foreach (ISharedRegionModule module in sharedlist)
{
module.RegionLoaded(scene);
}
}
public void RemoveRegionFromModules(Scene scene)
{
foreach (IRegionModuleBase module in scene.RegionModules.Values)
{
// m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}",
// scene.RegionInfo.RegionName, module.Name);
module.RemoveRegion(scene);
}
scene.RegionModules.Clear();
}
public void AddNode(ISharedRegionModule module)
{
m_sharedInstances.Add(module);
module.Initialise(m_openSim.ConfigSource.Source);
}
public void Dispose()
{
// We expect that all regions have been removed already
while (m_sharedInstances.Count > 0)
{
m_sharedInstances[0].Close();
m_sharedInstances.RemoveAt(0);
}
}
}
}

View File

@ -458,35 +458,36 @@ namespace OpenSim.Region.Framework.Scenes
if (null == assetBase)
return;
MemoryStream ms = new MemoryStream(assetBase.Data);
StreamReader sr = new StreamReader(ms);
sr.ReadLine(); // Unknown (Version?)
sr.ReadLine(); // Unknown
sr.ReadLine(); // Unknown
sr.ReadLine(); // Name
sr.ReadLine(); // Comment ?
int count = Convert.ToInt32(sr.ReadLine()); // Item count
for (int i = 0 ; i < count ; i++)
using (MemoryStream ms = new MemoryStream(assetBase.Data))
using (StreamReader sr = new StreamReader(ms))
{
string type = sr.ReadLine();
if (type == null)
break;
string name = sr.ReadLine();
if (name == null)
break;
string id = sr.ReadLine();
if (id == null)
break;
string unknown = sr.ReadLine();
if (unknown == null)
break;
sr.ReadLine(); // Unknown (Version?)
sr.ReadLine(); // Unknown
sr.ReadLine(); // Unknown
sr.ReadLine(); // Name
sr.ReadLine(); // Comment ?
int count = Convert.ToInt32(sr.ReadLine()); // Item count
// If it can be parsed as a UUID, it is an asset ID
UUID uuid;
if (UUID.TryParse(id, out uuid))
assetUuids[uuid] = (sbyte)AssetType.Animation;
for (int i = 0 ; i < count ; i++)
{
string type = sr.ReadLine();
if (type == null)
break;
string name = sr.ReadLine();
if (name == null)
break;
string id = sr.ReadLine();
if (id == null)
break;
string unknown = sr.ReadLine();
if (unknown == null)
break;
// If it can be parsed as a UUID, it is an asset ID
UUID uuid;
if (UUID.TryParse(id, out uuid))
assetUuids[uuid] = (sbyte)AssetType.Animation; // the asset is either an Animation or a Sound, but this distinction isn't important
}
}
}

View File

@ -487,7 +487,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden
report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding));
report.AppendFormat(
"{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}\n",
"{0,8} {1,7} {2,8} {3,7} {4,7} {5,7} {6,7} {7,9} {8,7}\n",
"Max",
"Total",
"Resend",
"Land",
@ -499,7 +500,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden
report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", "");
report.AppendFormat(
"{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}",
"{0,8} {1,7} {2,8} {3,7} {4,7} {5,7} {6,7} {7,9} {8,7}\n",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
@ -548,7 +550,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden
report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding));
report.AppendFormat(
"{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}",
"{0,8} {1,7} {2,8} {3,7} {4,7} {5,7} {6,7} {7,9} {8,7}",
(ci.maxThrottle * 8) / 1000,
(ci.totalThrottle * 8) / 1000,
(ci.resendThrottle * 8) / 1000,
(ci.landThrottle * 8) / 1000,
@ -584,7 +587,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden
ThrottleRates throttleRates = udpServer.ThrottleRates;
report.AppendFormat(
"{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}",
"{0,8} {1,7} {2,8} {3,7} {4,7} {5,7} {6,7} {7,9} {8,7}",
"-",
(throttleRates.Total * 8) / 1000,
(throttleRates.Resend * 8) / 1000,
(throttleRates.Land * 8) / 1000,

View File

@ -216,7 +216,12 @@ namespace OpenSim.Region.OptionalModules.Materials
GetLegacyStoredMaterialsInPart(part);
GetStoredMaterialInFace(part, te.DefaultTexture);
if (te.DefaultTexture != null)
GetStoredMaterialInFace(part, te.DefaultTexture);
else
m_log.WarnFormat(
"[Materials]: Default texture for part {0} (part of object {1)) in {2} unexpectedly null. Ignoring.",
part.Name, part.ParentGroup.Name, m_scene.Name);
foreach (Primitive.TextureEntryFace face in te.FaceTextures)
{

View File

@ -465,13 +465,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE));
}
// Test for non-existant path
// Test for non-existent path
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, "foo");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
}
// Test for non-existant store
// Test for non-existent store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int result = (int)InvokeOp("JsonGetNodeType", fakeStoreId, ".");
@ -898,4 +898,4 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests
public object DummyTestMethod(object o1, object o2, object o3, object o4, object o5) { return null; }
}
}
}

View File

@ -76,6 +76,8 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// AutoBackupBusyCheck: True/False. Default: True.
/// If True, we will only take an auto-backup if a set of conditions are met.
/// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
/// AutoBackupSkipAssets
/// If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
/// AutoBackupScript: String. Default: not specified (disabled).
/// File path to an executable script or binary to run when an automatic backup is taken.
/// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
@ -258,6 +260,8 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
AutoBackupModuleState abms = this.ParseConfig(scene, false);
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
m_states.Add(scene, abms);
}
/// <summary>
@ -334,7 +338,7 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
double interval =
this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
config, regionConfig) * 60000.0;
if (state == null && interval != this.m_defaultState.IntervalMinutes*60000.0)
if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
{
state = new AutoBackupModuleState();
}
@ -412,6 +416,19 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
state.BusyCheck = tmpBusyCheck;
}
// Included Option To Skip Assets
bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
this.m_defaultState.SkipAssets, config, regionConfig);
if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.SkipAssets = tmpSkipAssets;
}
// Set file naming algorithm
string stmpNamingType = ResolveString("AutoBackupNaming",
this.m_defaultState.NamingType.ToString(), config, regionConfig);
@ -488,6 +505,9 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
}
}
if(state == null)
return m_defaultState;
return state;
}
@ -640,7 +660,7 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// <param name="scene"></param>
private void DoRegionBackup(IScene scene)
{
if (scene.RegionStatus != RegionStatus.Up)
if (!scene.Ready)
{
// We won't backup a region that isn't operating normally.
m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName +
@ -662,7 +682,16 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
m_pendingSaves.Add(guid, scene);
state.LiveRequests.Add(guid, savePath);
((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
iram.ArchiveRegion(savePath, guid, null);
m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
// Must pass options, even if dictionary is empty!
Dictionary<string, object> options = new Dictionary<string, object>();
if (state.SkipAssets)
options["noassets"] = true;
iram.ArchiveRegion(savePath, guid, options);
}
/// <summary>

View File

@ -45,6 +45,7 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
this.Enabled = false;
this.BackupDir = ".";
this.BusyCheck = true;
this.SkipAssets = false;
this.Timer = null;
this.NamingType = NamingType.Time;
this.Script = null;
@ -91,6 +92,12 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
set;
}
public bool SkipAssets
{
get;
set;
}
public string Script
{
get;

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
@ -205,6 +205,17 @@ public class BSActorAvatarMove : BSActor
// Flying and not colliding and velocity nearly zero.
m_controllingPrim.ZeroMotion(true /* inTaintTime */);
}
else
{
//We are falling but are not touching any keys make sure not falling too fast
if (m_controllingPrim.RawVelocity.Z < BSParam.AvatarTerminalVelocity)
{
OMV.Vector3 slowingForce = new OMV.Vector3(0f, 0f, BSParam.AvatarTerminalVelocity - m_controllingPrim.RawVelocity.Z) * m_controllingPrim.Mass;
m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, slowingForce);
}
}
}
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,taint,stopping,target={1},colliding={2}",
@ -227,7 +238,6 @@ public class BSActorAvatarMove : BSActor
stepVelocity.Z = m_controllingPrim.RawVelocity.Z;
}
// Colliding and not flying with an upward force. The avatar must be trying to jump.
if (!m_controllingPrim.Flying && m_controllingPrim.IsColliding && stepVelocity.Z > 0)
{
@ -253,12 +263,34 @@ public class BSActorAvatarMove : BSActor
}
else
{
// Since we're not affected by anything, whatever vertical motion the avatar has, continue that.
stepVelocity.Z = m_controllingPrim.RawVelocity.Z;
// Since we're not affected by anything, the avatar must be falling and we do not want that to be too fast.
if (m_controllingPrim.RawVelocity.Z < BSParam.AvatarTerminalVelocity)
{
stepVelocity.Z = BSParam.AvatarTerminalVelocity;
}
else
{
stepVelocity.Z = m_controllingPrim.RawVelocity.Z;
}
}
// DetailLog("{0},BSCharacter.MoveMotor,taint,overrideStepZWithWorldZ,stepVel={1}", LocalID, stepVelocity);
}
//Alicia: Maintain minimum height when flying.
// SL has a flying effect that keeps the avatar flying above the ground by some margin
if (m_controllingPrim.Flying)
{
float hover_height = m_physicsScene.TerrainManager.GetTerrainHeightAtXYZ(m_controllingPrim.RawPosition)
+ BSParam.AvatarFlyingGroundMargin;
if( m_controllingPrim.Position.Z < hover_height)
{
stepVelocity.Z += BSParam.AvatarFlyingGroundUpForce;
}
}
// 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force.
OMV.Vector3 moveForce = (stepVelocity - m_controllingPrim.RawVelocity) * m_controllingPrim.Mass;

View File

@ -744,7 +744,18 @@ public sealed class BSCharacter : BSPhysObject
// and will send agent updates to the clients if velocity changes by more than
// 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
// extra updates.
if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
//
// XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to
// avatar movement rather than removes it. The larger the threshold, the bigger the jitter.
// This is most noticeable in level flight and can be seen with
// the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower
// bound and an upper bound, where the difference between the two is enough to trigger a large delta v update
// and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?)
// has not yet been identified.
//
// If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra
// updates are not triggered in ScenePresence.SendTerseUpdateToAllClients().
// if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
RawVelocity = entprop.Velocity;
_acceleration = entprop.Acceleration;

View File

@ -305,6 +305,10 @@ public sealed class BSLinksetCompound : BSLinkset
// Note that this works for rebuilding just the root after a linkset is taken apart.
// Called at taint time!!
private bool UseBulletSimRootOffsetHack = false; // Attempt to have Bullet track the coords of root compound shape
// Number of times to perform rebuilds on broken linkset children. This should only happen when
// a linkset is initially being created and should happen only one or two times at the most.
// This exists to cause a looping problem to be reported while not rebuilding a linkset forever.
private static int LinksetRebuildFailureLoopPrevention = 10;
private void RecomputeLinksetCompound()
{
try
@ -376,18 +380,42 @@ public sealed class BSLinksetCompound : BSLinkset
OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation;
// Add the child shape to the compound shape being built
m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Since we are borrowing the shape of the child, disable the origional child body
if (!IsRoot(cPrim))
if (childShape.physShapeInfo.HasPhysicalShape)
{
m_physicsScene.PE.AddToCollisionFlags(cPrim.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
m_physicsScene.PE.ForceActivationState(cPrim.PhysBody, ActivationState.DISABLE_SIMULATION);
// We don't want collisions from the old linkset children.
m_physicsScene.PE.RemoveFromCollisionFlags(cPrim.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
cPrim.PhysBody.collisionType = CollisionType.LinksetChild;
m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Since we are borrowing the shape of the child, disable the origional child body
if (!IsRoot(cPrim))
{
m_physicsScene.PE.AddToCollisionFlags(cPrim.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
m_physicsScene.PE.ForceActivationState(cPrim.PhysBody, ActivationState.DISABLE_SIMULATION);
// We don't want collisions from the old linkset children.
m_physicsScene.PE.RemoveFromCollisionFlags(cPrim.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
cPrim.PhysBody.collisionType = CollisionType.LinksetChild;
}
}
else
{
// The linkset must be in an intermediate state where all the children have not yet
// been constructed. This sometimes happens on startup when everything is getting
// built and some shapes have to wait for assets to be read in.
// Just skip this linkset for the moment and cause the shape to be rebuilt next tick.
// One problem might be that the shape is broken somehow and it never becomes completely
// available. This might cause the rebuild to happen over and over.
LinksetRoot.ForceBodyShapeRebuild(false);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChildWithNoShape,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Output an annoying warning. It should only happen once but if it keeps coming out,
// the user knows there is something wrong and will report it.
m_physicsScene.Logger.WarnFormat("{0} Linkset rebuild warning. If this happens more than one or two times, please report in Mantis 7191", LogHeader);
m_physicsScene.Logger.WarnFormat("{0} pName={1}, childIdx={2}, shape={3}",
LogHeader, LinksetRoot.Name, cPrim.LinksetChildIndex, childShape);
// This causes the loop to bail on building the rest of this linkset.
// The rebuild operation should fix it up or declare the object unbuildable.
return true;
}
return false; // 'false' says to move onto the next child in the list

View File

@ -136,6 +136,9 @@ public static class BSParam
public static float AvatarHeightLowFudge { get; private set; }
public static float AvatarHeightMidFudge { get; private set; }
public static float AvatarHeightHighFudge { get; private set; }
public static float AvatarFlyingGroundMargin { get; private set; }
public static float AvatarFlyingGroundUpForce { get; private set; }
public static float AvatarTerminalVelocity { get; private set; }
public static float AvatarContactProcessingThreshold { get; private set; }
public static float AvatarStopZeroThreshold { get; private set; }
public static int AvatarJumpFrames { get; private set; }
@ -583,6 +586,12 @@ public static class BSParam
0f ),
new ParameterDefn<float>("AvatarHeightHighFudge", "A fudge factor to make tall avatars stand on the ground",
0f ),
new ParameterDefn<float>("AvatarFlyingGroundMargin", "Meters avatar is kept above the ground when flying",
5f ),
new ParameterDefn<float>("AvatarFlyingGroundUpForce", "Upward force applied to the avatar to keep it at flying ground margin",
2.0f ),
new ParameterDefn<float>("AvatarTerminalVelocity", "Terminal Velocity of falling avatar",
-54.0f ),
new ParameterDefn<float>("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions",
0.1f ),
new ParameterDefn<float>("AvatarStopZeroThreshold", "Movement velocity below which avatar is assumed to be stopped",

View File

@ -159,6 +159,11 @@ public abstract class BSPhysObject : PhysicsActor
Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched
}
public PrimAssetCondition PrimAssetState { get; set; }
public virtual bool AssetFailed()
{
return ( (this.PrimAssetState == PrimAssetCondition.FailedAssetFetch)
|| (this.PrimAssetState == PrimAssetCondition.FailedMeshing) );
}
// The objects base shape information. Null if not a prim type shape.
public PrimitiveBaseShape BaseShape { get; protected set; }
@ -462,7 +467,10 @@ public abstract class BSPhysObject : PhysicsActor
// If someone has subscribed for collision events log the collision so it will be reported up
if (SubscribedEvents()) {
CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
lock (PhysScene.CollisionLock)
{
CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
}
DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5},colliderMoving={6}",
LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth, ColliderIsMoving);
@ -474,12 +482,14 @@ public abstract class BSPhysObject : PhysicsActor
// Send the collected collisions into the simulator.
// Called at taint time from within the Step() function thus no locking problems
// with CollisionCollection and ObjectsWithNoMoreCollisions.
// Called with BSScene.CollisionLock locked to protect the collision lists.
// Return 'true' if there were some actual collisions passed up
public virtual bool SendCollisions()
{
bool ret = true;
// If the 'no collision' call, force it to happen right now so quick collision_end
// If no collisions this call but there were collisions last call, force the collision
// event to be happen right now so quick collision_end.
bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0);
// throttle the collisions to the number of milliseconds specified in the subscription

View File

@ -705,7 +705,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters
// this is is under UpdateLock.
public void PostUpdate(BSPhysObject updatee)
{
ObjectsWithUpdates.Add(updatee);
lock (UpdateLock)
{
ObjectsWithUpdates.Add(updatee);
}
}
// The simulator thinks it is physics time so return all the collisions and position
@ -803,7 +806,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters
if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration))
{
// If a collision was 'good', remember to send it to the simulator
ObjectsWithCollisions.Add(collider);
lock (CollisionLock)
{
ObjectsWithCollisions.Add(collider);
}
}
}

Some files were not shown because too many files have changed in this diff Show More