Compare commits

..

558 Commits

Author SHA1 Message Date
lickx
79cf77043a Merge branch 'lickx' into presfix 2025-05-08 20:45:43 +02:00
lickx
d8b47797d4 Merge branch 'master' into lickx 2025-05-06 03:22:22 +02:00
lickx
a7231176ba Merge branch 'master' into terfix 2025-05-05 02:38:37 +02:00
lickx
e387bc42ee Reapply "remove option ClampNegativeZ"
This reverts commit 667695b393.
2025-05-05 02:38:16 +02:00
lickx
7c062d5949 Reapply "mantis 9133 replace some z < 0 checks by < Constants.MinSimulationHeight (-100)"
This reverts commit cb1bde70db.
2025-05-05 02:37:54 +02:00
lickx
c72d04600f Reapply "a few more changes on terrain"
This reverts commit ce1f31864f.
2025-05-05 02:37:24 +02:00
lickx
66aca6e308 Reapply "Fix SmoothArea to be uniform again"
This reverts commit 1d92dee88c.
2025-05-05 02:37:00 +02:00
lickx
68258367e7 Reapply "try to fix some terrain issues, Add some more locking"
This reverts commit 103e21f3ed.
2025-05-05 02:36:41 +02:00
lickx
db65440674 Comment out debug message for animation overrides 2025-05-04 17:15:09 +02:00
lickx
57c140d9a5 Merge branch 'master' into lickx 2025-05-04 04:16:34 +02:00
lickx
9860e99a53 Only work on imap when connected 2025-05-01 11:27:45 +02:00
lickx
2922c59de9 Merge branch 'master' into lickx 2025-05-01 10:40:20 +02:00
lickx
78d1eb15b9 Add crontab example, update a readme for mutes 2025-04-27 13:07:00 +02:00
lickx
103e21f3ed Revert "try to fix some terrain issues, Add some more locking"
This reverts commit e5d10bf127.
2025-04-24 08:14:16 +02:00
lickx
1d92dee88c Revert "Fix SmoothArea to be uniform again"
This reverts commit b1a2773de9.
2025-04-24 08:13:50 +02:00
lickx
ce1f31864f Revert "a few more changes on terrain"
This reverts commit 9a02b55bf2.
2025-04-24 08:13:29 +02:00
lickx
cb1bde70db Revert "mantis 9133 replace some z < 0 checks by < Constants.MinSimulationHeight (-100)"
This reverts commit f2379dc785.
2025-04-24 08:11:48 +02:00
lickx
667695b393 Revert "remove option ClampNegativeZ"
This reverts commit 9a92d94e99.
2025-04-24 08:11:22 +02:00
lickx
4999a8e926 Merge branch 'master' into lickx 2025-04-23 14:47:45 +02:00
lickx
35aa56566e Merge branch 'master' into lickx 2025-04-21 03:02:59 +02:00
lickx
3d61fb9c08 Add administrator check in HGEntityTransferModule 2025-04-18 06:41:18 +02:00
lickx
92a845e192 Merge branch 'master' into lickx 2025-04-18 06:28:57 +02:00
lickx
73e5ff9868 Add support files for search and mutelist module 2025-04-14 10:36:03 +02:00
lickx
03ab7627bc Merge branch 'master' into lickx 2025-04-14 10:03:11 +02:00
lickx
f521cc201a Merge branch 'master' into lickx 2025-04-12 11:17:04 +02:00
lickx
d54d841571 Merge branch 'master' into lickx 2025-04-04 16:05:39 +02:00
lickx
0162fc1d4b Merge branch 'master' into lickx 2025-04-04 11:43:22 +02:00
lickx
dafe5275b5 Merge branch 'master' into lickx 2025-03-30 05:50:26 +02:00
lickx
1480c97de1 Name zip opensimcurrency instead of moneymodule
But really i use a seperate mkdist for packing opensim.currency
which also includes working helper scripts
2025-03-29 11:50:34 +01:00
lickx
6e399e5971 Merge branch 'master' into lickx 2025-03-29 11:43:51 +01:00
lickx
02f5f46eed Make the finished loading message more useful 2025-03-28 13:30:28 +01:00
lickx
c8d6444cc6 Merge branch 'master' into lickx 2025-03-25 15:45:02 +01:00
lickx
7bdd4c1215 Sync with master version 2025-03-25 07:04:00 +01:00
lickx
c1f1d2e5eb Reapply "some changes to PresenceServerPostHandler"
This reverts commit a688ea7018.
2025-03-24 15:54:49 +01:00
lickx
8e99ed7c40 Set attachments to group and resume scripts for XmlRpcGroups 2025-03-24 06:01:21 +01:00
lickx
e4d4ba0d0e Add opensim.currency support to mkdist 2025-03-24 05:48:46 +01:00
lickx
85a3a112b3 Also update grouptag for XmlRpcGroups 2025-03-24 05:47:37 +01:00
lickx
423b9034d4 Merge branch 'master' into lickx 2025-03-19 08:28:48 +01:00
lickx
b90a1b94c0 Fix grouptag not updating after active role change 2025-03-19 08:24:12 +01:00
lickx
2ca89cae1d Merge branch 'master' into lickx 2025-03-16 14:40:26 +01:00
lickx
da9e0498fe Merge branch 'master' into lickx 2025-03-13 04:27:08 +01:00
lickx
0ffe739692 Merge branch 'master' into lickx 2025-03-12 11:53:46 +01:00
lickx
552b1d52b7 Merge branch 'master' into lickx 2025-02-21 10:31:52 +01:00
lickx
d74be8f606 Merge branch 'master' into lickx 2025-02-16 03:47:07 +01:00
lickx
0998a8c4ff Merge branch 'master' into lickx 2025-02-12 09:21:27 +01:00
lickx
6c89054ab7 Merge branch 'master' into lickx 2025-02-11 03:36:10 +01:00
lickx
e31b17565a Merge branch 'master' into lickx 2025-02-07 13:44:30 +01:00
lickx
160adff017 Merge branch 'master' into lickx 2025-02-06 03:31:27 +01:00
lickx
0546231a91 Correct version string length 2025-01-16 06:04:39 +01:00
lickx
5adecfe5cd compile.* will be generated by prebuild 2025-01-10 09:02:51 +01:00
lickx
6b3b9cd901 Merge branch 'master' into lickx 2025-01-05 04:21:09 +01:00
lickx
b2e1e0d123 Add save oar --tenant= option for saving stuff
This is mainly useful for multi tenancy sims where a user requests an oar
of their stuff, and where you don't want to pass out other people's stuff.
2025-01-04 14:42:15 +01:00
lickx
6ce42168ff Merge branch 'master' into lickx 2024-12-26 06:44:00 +01:00
lickx
21611d3da5 Merge branch 'master' into lickx 2024-12-22 06:44:05 +01:00
lickx
f17db633bc Make default slurl prefix more opensim-like
While still remaining compatible with declined RLVa inventory offers
2024-12-09 13:47:39 +01:00
lickx
b6e08a6a9b null check, not everyone runs with a group module 2024-12-09 13:38:18 +01:00
lickx
f1f833f0a2 Merge branch 'master' into lickx 2024-12-01 03:36:24 +01:00
lickx
2f810c71ec Merge branch 'master' into lickx 2024-11-30 06:49:46 +01:00
lickx
4890ca2765 Revert folder version to ushort as in upstream
A signed int was a bad idea because of rollover
into the negative -sizeof(int)

To illustrate, my 'Current Outfits' folder version
is now, about 1 year after born, version 33000
2024-11-29 14:25:24 +01:00
lickx
7a05050c93 Merge branch 'master' into lickx 2024-11-27 04:20:43 +01:00
lickx
db590aa229 Correct offset clamp for PRIM_NORMAL 2024-11-26 19:17:34 +01:00
lickx
112349e78b Merge branch 'master' into lickx 2024-11-23 07:54:20 +01:00
lickx
196ab7e5af Do include *.pdb files in zips 2024-11-23 07:51:35 +01:00
lickx
cf27856c26 Make cache an option, for issue #25 2024-11-20 10:19:27 +01:00
lickx
fdf58bc890 Merge branch 'master' into lickx 2024-11-20 05:29:25 +01:00
lickx
79e0f120b2 Merge branch 'master' into lickx 2024-11-19 07:48:13 +01:00
lickx
4dd7a0e8d8 Merge branch 'master' into lickx 2024-11-17 04:50:39 +01:00
lickx
e9155e833b Merge branch 'master' into lickx 2024-11-16 15:18:54 +01:00
lickx
20760c35ae Merge branch 'master' into lickx 2024-11-09 07:25:35 +01:00
lickx
68bb990f22 Re-introduce SIGTERM signal handling
According to the .NET 6/8 docs, this is handled on Windows as well
2024-11-02 12:59:56 +01:00
lickx
23abc64a5d Merge branch 'master' into lickx 2024-10-24 14:06:47 +02:00
lickx
9bd91eba81 Rework incoming attachments (HGEntityTransfer)
Avatar will progressively load now instead of waiting until all attached
assets are complete. Also optimize, cleanup etc.
2024-10-24 10:43:54 +02:00
lickx
aca3d0f320 Merge branch 'master' into lickx 2024-10-21 06:47:21 +02:00
lickx
5a05a45dcf Merge branch 'master' into lickx 2024-10-17 04:59:46 +02:00
lickx
5f37f77734 Merge branch 'master' into lickx 2024-10-10 11:30:15 +02:00
lickx
6f0aef668a llGetTimeOfDay() and llGetRegionTimeOfDay based on Environment
llGetTimeOfDay() is based on the current parcel environment, while
llGetRegionTimeOfDay() is based on the region environment

With a fallback on the hardcoded way we did this if no environment module
is active
2024-10-10 08:02:39 +02:00
lickx
988446fb6f Merge branch 'master' into lickx 2024-10-09 16:23:42 +02:00
lickx
d40b3c9e03 Allow defining path where to store generated MAP-uuid.png
Defaults to the folder containing OpenSim.dll/.exe for legacy compatibility
2024-10-09 16:15:00 +02:00
lickx
32e1839f5c Use the shorthand 'mailname' from now on
objectmail_hostname will be deprecated but will still work
2024-09-24 04:37:11 +02:00
lickx
c3611ed4fe Merge branch 'master' into lickx 2024-09-23 10:40:11 +02:00
lickx
b69a0ea279 Merge branch 'master' into lickx 2024-09-21 04:49:19 +02:00
lickx
902e14ca5a Revert "Revert "do not do chained hg teleports""
This reverts commit 7319328a78.
2024-09-21 04:48:55 +02:00
lickx
a688ea7018 Revert "some changes to PresenceServerPostHandler"
This reverts commit 81cfd6e956.
2024-09-19 18:58:59 +02:00
lickx
c7f2aab58b Merge branch 'master' into lickx 2024-09-19 14:08:47 +02:00
lickx
450b3e7f1b Merge branch 'master' into lickx 2024-09-18 15:45:57 +02:00
lickx
d405b71f20 Add examples of bad viewers in line with the Wiki 2024-09-08 11:06:26 +02:00
lickx
7503d1a23f Always allow http requests to prim webservers 2024-09-06 16:04:15 +02:00
lickx
c1942f70c5 Merge branch 'master' into lickx 2024-09-04 04:06:49 +02:00
user
bd663a823b Update build files 2024-09-02 03:31:03 +02:00
user
ce3aff2237 Simplify loading attachments message 2024-09-02 03:14:14 +02:00
lickx
eb324ae342 Fix mkdist.sh for OpenSimMutelist 2024-08-25 18:06:44 +02:00
lickx
d6f74f26b7 Merge branch 'master' into lickx 2024-08-22 08:00:47 +02:00
lickx
62b0580361 Add scripts to make binary zips for distribution 2024-08-22 07:59:42 +02:00
lickx
efc0f3dea6 Add OpenSimSearch to the addons
It is used by nearly everyone
2024-08-22 07:53:35 +02:00
lickx
42decad1ee Default to false for enabling certs 2024-08-19 02:58:57 +02:00
lickx
832edd880e Merge branch 'master' into lickx 2024-08-17 06:33:49 +02:00
lickx
e83c21fea9 Merge branch 'master' into lickx 2024-08-15 06:11:37 +02:00
lickx
5aa342e570 Merge branch 'master' into lickx 2024-08-08 16:41:49 +02:00
lickx
585d128035 Reject hypergrid visitors with just an IP address as homeURI 2024-08-02 10:29:50 +02:00
lickx
838414b63b Merge branch 'master' into lickx 2024-08-02 09:28:55 +02:00
lickx
d02f1e529a Merge branch 'master' into lickx 2024-07-21 04:01:42 +02:00
lickx
152fbee376 Properly update lastowner info
In that Other Grid, it used to be done on inventory detach too, but that
seems no longer to be the case.
2024-07-09 11:24:17 +02:00
lickx
758f7464fc Do fire the dataserver event for PAYINFO on hypergridders 2024-07-06 08:20:17 +02:00
lickx
843810ddae Merge branch 'master' into lickx 2024-07-04 04:21:11 +02:00
lickx
afb29e1909 Merge branch 'master' into lickx 2024-07-03 07:56:10 +02:00
lickx
4a5c44aacd Merge branch 'master' into lickx 2024-06-27 08:24:52 +02:00
lickx
77262731c9 Merge branch 'master' into lickx 2024-06-24 05:59:00 +02:00
lickx
ae37c27034 Implement lxGetAgentViewer
This was an old request
2024-06-22 00:19:00 +02:00
lickx
f78eb6c8af Merge branch 'master' into lickx 2024-06-20 07:04:01 +02:00
lickx
e163391c90 Merge branch 'master' into lickx 2024-06-19 17:39:43 +02:00
lickx
8a146e7805 Revert DefaultWater
I forgot my motivation I once had to modify it, but with the master
version I can create AND open a new Water setting in my inv again.

You might have to issue 'fcache deletedefaultassets' in your simulator,
AND clear your viewer cache.
2024-06-15 15:49:08 +02:00
lickx
81b3081f00 Merge branch 'master' into lickx 2024-06-15 09:35:15 +02:00
lickx
0e6cdcb356 Merge branch 'master' into lickx 2024-06-14 05:36:49 +02:00
lickx
d35ff5dcd9 Merge branch 'master' into lickx 2024-06-12 05:43:58 +02:00
lickx
10d9461d99 Merge branch 'master' into lickx 2024-06-09 06:48:15 +02:00
lickx
f06f3c889c Merge branch 'master' into lickx 2024-06-05 11:56:31 +02:00
lickx
817a87330c Enable sim-local mail by default
This is safe. With this setup mail addressed to outside destinations
(any address not ending in internal_object_host) is silently discarded.
By default the internal_object_host is defined as lsl.opensim.local
2024-06-05 11:52:17 +02:00
lickx
466e92047a Add "objectmail_hostname" to llGetEnv()
It returns the part after the @ for an object's email address
2024-06-01 15:48:29 +02:00
lickx
c13e1aac27 Merge branch 'master' into lickx 2024-05-30 15:01:56 +02:00
lickx
fbf9f0ef29 Merge branch 'master' into lickx 2024-05-21 06:07:44 +02:00
lickx
9fcebdefe0 Merge branch 'master' into lickx 2024-05-18 02:20:20 +02:00
lickx
6e8b823508 Merge branch 'master' into lickx 2024-05-17 04:51:15 +02:00
lickx
e597578c05 Merge branch 'master' into lickx 2024-05-12 13:45:46 +02:00
lickx
01e11f5161 Merge branch 'master' into lickx 2024-05-11 08:00:02 +02:00
lickx
3e027250d5 Merge branch 'master' into lickx 2024-05-10 05:07:46 +02:00
lickx
a04af02c91 Merge branch 'master' into lickx 2024-05-09 13:44:32 +02:00
lickx
8376a9a444 Merge branch 'master' into lickx 2024-05-03 11:14:17 +02:00
lickx
433ce41c61 Merge branch 'master' into lickx 2024-05-01 07:30:12 +02:00
lickx
a8e6c6c81d Merge branch 'master' into lickx 2024-04-29 15:56:29 +02:00
lickx
7fecf837db Merge branch 'master' into lickx 2024-04-28 08:11:50 +02:00
lickx
424d209516 Merge branch 'master' into lickx 2024-04-25 07:37:22 +02:00
lickx
43300d36cc Merge branch 'master' into lickx 2024-04-23 07:41:09 +02:00
lickx
5466118445 Merge branch 'master' into lickx 2024-04-21 15:17:02 +02:00
lickx
8a882f2415 Revert "update mysql.data.dll to 8.3.0"
This reverts commit 68bfdddae5.

Because MariaDB doesn't like this at all!
2024-04-21 13:44:15 +02:00
lickx
324a57a53e Merge branch 'master' into lickx 2024-04-21 13:21:04 +02:00
lickx
c7705c6314 Merge branch 'master' into lickx 2024-04-21 03:40:56 +02:00
lickx
9487a34450 Merge branch 'master' into lickx 2024-04-18 09:32:47 +02:00
lickx
7b6810c286 Merge branch 'master' into lickx 2024-04-15 06:48:08 +02:00
lickx
e70f6b9d44 Merge branch 'master' into lickx 2024-04-13 09:31:11 +02:00
lickx
c580ffcfeb Merge branch 'master' into lickx 2024-04-11 08:15:48 +02:00
lickx
d6c81ac0c7 Merge branch 'master' into lickx 2024-04-08 05:31:52 +02:00
lickx
7319328a78 Revert "do not do chained hg teleports"
This reverts commit 0d1b14c78f.
2024-04-07 06:05:28 +02:00
lickx
d50a31f7f1 Merge branch 'master' into lickx 2024-04-07 05:12:01 +02:00
lickx
123289e5d2 Merge branch 'master' into lickx 2024-04-03 10:54:50 +02:00
lickx
770e5b110f Merge branch 'master' into lickx 2024-04-02 05:31:13 +02:00
lickx
8e2a582efc Merge branch 'master' into lickx 2024-03-31 12:04:44 +02:00
lickx
f0298ba08c Merge branch 'master' into lickx 2024-03-30 04:06:24 +01:00
lickx
359020d4e6 Merge branch 'master' into lickx 2024-03-29 04:22:43 +01:00
lickx
37a3dd615f Merge branch 'master' into lickx 2024-03-27 11:03:39 +01:00
lickx
243bab823e Merge branch 'master' into lickx 2024-03-24 18:00:47 +01:00
lickx
fceedaa80c Merge branch 'master' into lickx 2024-03-12 08:36:50 +01:00
lickx
5fe5f98cdd Addressing an force-tp edge case, closes #22 2024-03-07 14:03:20 +01:00
lickx
5d99e33009 Merge branch 'master' into lickx 2024-03-06 06:07:26 +01:00
lickx
2578fd1b25 Merge branch 'master' into lickx 2024-03-03 05:17:31 +01:00
lickx
42e2cd5760 SMTPConfig -> EmailConfig 2024-03-01 06:19:29 +01:00
lickx
b3479bcb06 Merge branch 'master' into lickx 2024-02-28 10:35:42 +01:00
lickx
a44ca25589 Merge branch 'master' into lickx 2024-02-27 03:34:54 +01:00
lickx
4919bb8067 Merge branch 'master' into lickx 2024-02-24 19:48:21 +01:00
lickx
5616128a88 Merge branch 'master' into lickx 2024-02-23 18:51:35 +01:00
lickx
0e6dc2d968 Change SMTP section to the more descriptive Email 2024-02-23 05:34:28 +01:00
lickx
2f6a026b5a Merge branch 'master' into lickx 2024-02-22 04:50:01 +01:00
lickx
e708b309af Merge branch 'master' into lickx 2024-02-17 08:10:46 +01:00
lickx
9fe56711ec Merge branch 'master' into lickx 2024-02-16 07:05:12 +01:00
lickx
f304a881b2 Merge branch 'master' into lickx 2024-02-15 05:07:46 +01:00
lickx
a7d635967e Implement "region_rating" and "grid" in llGetEnv() 2024-02-12 15:28:14 +01:00
lickx
67f3b24ae1 Make this work correctly 2024-02-12 13:36:48 +01:00
lickx
3aadd18418 Remove feature for now
This caused land sales for more than 0L to not work for local users,
at least with Gloebit. This check will probably need to happen elsewhere
but idk where yet
2024-02-10 21:15:38 +01:00
lickx
db227ab5e9 Merge branch 'master' into lickx 2024-02-08 03:42:58 +01:00
lickx
67974184c9 Merge branch 'master' into lickx 2024-02-07 10:13:11 +01:00
lickx
621dafa222 Merge branch 'master' into lickx 2024-02-06 05:59:04 +01:00
lickx
2064a3caed Neater 2024-02-06 05:58:14 +01:00
lickx
c345a13dea Merge branch 'master' into lickx 2024-02-04 05:33:01 +01:00
lickx
9f61683603 Merge branch 'master' into lickx 2024-02-01 07:43:05 +01:00
lickx
0ccd0dd45b Revert "Only allow local residents to create groups"
This reverts commit df59617648.
Duplicate code, see CreateGroup() in GroupsServiceHGConnectorModule.cs
2024-01-29 04:15:59 +01:00
lickx
ffbeda5c38 Merge branch 'master' into lickx 2024-01-27 05:42:06 +01:00
lickx
bcf2a5f929 Merge branch 'master' into lickx 2024-01-24 05:39:15 +01:00
lickx
8dfa6c3b11 Merge branch 'master' into lickx 2024-01-23 16:15:09 +01:00
lickx
423d8c88e3 Merge branch 'master' into lickx 2024-01-22 04:13:42 +01:00
lickx
bcfeeadebd Implement a request for a custom ban message 2024-01-21 17:25:43 +01:00
lickx
f0ee56bf70 Unbreak 18+/PIOF access restrictions for parcels
(Was already OK for estates)
2024-01-15 19:54:04 +01:00
lickx
4590eb535e Add the PAYMENT_* constants as well 2024-01-15 18:32:27 +01:00
lickx
b9784df0e8 Make ALL llRequestAgentData requests working
Before, only DATA_ONLINE worked and DATA_PAYINFO wasn't implemented
2024-01-15 18:06:18 +01:00
lickx
feabd5e537 Merge branch 'master' into lickx 2024-01-11 06:10:36 +01:00
lickx
57b5db3467 Merge branch 'master' into lickx 2024-01-03 04:56:17 +01:00
lickx
ac9f16365c Check for the full address, not just the key 2023-12-20 19:03:35 +01:00
lickx
4ad8dca196 Clean up a bit 2023-12-20 08:10:24 +01:00
lickx
c2bfe69f33 Merge branch 'master' into lickx 2023-12-19 06:36:55 +01:00
lickx
2dda244390 Syntax 2023-12-19 06:36:19 +01:00
lickx
58d10aa79a Avoid double messages 2023-12-14 08:46:22 +01:00
lickx
8c1ce17bdb Fix filtered e-mail search 2023-12-14 08:34:44 +01:00
lickx
dbf79e9716 Merge branch 'master' into lickx 2023-12-13 04:30:12 +01:00
lickx
7fbf7f0675 Comment typo in the new IMAP config 2023-12-13 04:24:49 +01:00
lickx
b08f456a13 Implement intersim object2object e-mail for LSL 2023-12-12 19:17:49 +01:00
lickx
7cff935649 Merge branch 'master' into lickx 2023-12-11 05:40:11 +01:00
lickx
5f124e3420 Merge branch 'master' into lickx 2023-12-07 04:36:49 +01:00
lickx
945ee5b500 Merge branch 'master' into lickx 2023-12-06 06:51:01 +01:00
lickx
6685756f30 Merge branch 'master' into lickx 2023-12-02 15:11:47 +01:00
lickx
990cf3e56e Merge branch 'master' into lickx 2023-11-30 04:33:14 +01:00
lickx
29bdac8a66 Merge branch 'master' into lickx 2023-11-28 07:34:55 +01:00
lickx
1a4b444c24 Merge branch 'lickx' of https://github.com/lickx/opensim-lickx into lickx 2023-11-28 07:12:01 +01:00
lickx
a221e2d3db Fix one compile error 2023-11-28 06:53:17 +01:00
lickx
f32e361174 Merge remote-tracking branch 'origin/lickx' into lickx-dotnet6 2023-11-28 06:45:29 +01:00
lickx
b9b86468fc Merge branch 'dotnet6' into lickx-dotnet6 2023-11-28 04:43:45 +01:00
lickx
ced4b7c528 More informative message to HG visitors, closes #20 2023-11-23 13:01:41 +01:00
lickx
717dad94c3 Merge branch 'dotnet6' into lickx-dotnet6 2023-11-19 03:21:55 +01:00
lickx
6594702c8a Inform foreign visitors the HGTP is complete
And thus their avi should be fully rezzed, and attachments working
2023-11-16 04:32:41 +01:00
lickx
bea24c55d4 Re-implement per-friend notifications, closes #19
Slightly less performant than per-domain, but it works well
2023-11-15 13:01:42 +01:00
lickx
e6f0affac6 Merge branch 'dotnet6' into lickx-dotnet6 2023-11-08 09:02:24 +01:00
lickx
bd2f10f350 Use groupname if the abandoned parcel was group-owned 2023-10-25 08:55:53 +02:00
lickx
997caae560 One oops 2023-10-21 16:34:44 +02:00
lickx
e87b380280 Testing code from nani 2023-10-21 16:20:29 +02:00
lickx
a6828818ad Improve new take_copy_restricted functionality 2023-10-21 16:17:05 +02:00
lickx
ce87e5fd87 Do away with cache
It doesn't work well with multiple instances behind a proxy
2023-10-21 16:16:08 +02:00
lickx
335753e92f This is a better place for it 2023-10-21 16:15:42 +02:00
lickx
82da0f77b7 Implement functional per-domain status notifications
See commit
2023-10-21 16:15:19 +02:00
lickx
e40f507dae Mantis 8366: logins have GotAttachmentsData true 2023-10-21 15:57:33 +02:00
lickx
98b6b58598 Folder version should be int 2023-10-21 15:56:44 +02:00
lickx
bc74ad52b2 Fixes #14 2023-10-21 15:48:41 +02:00
lickx
dd45ff7a0c Revert "Description column should be 127 bytes UTF-8 string"
This reverts commit 27e0684cbc.
2023-10-21 15:46:08 +02:00
lickx
01cc050a2d Revert "Update MAX_ASSET_DESC also"
This reverts commit 25ff65ae05.
2023-10-21 15:45:41 +02:00
lickx
5eb13c4cb3 Update comment info on texture asset 2023-10-21 15:45:09 +02:00
lickx
894fff9cfb Shorten expiry time 2023-10-21 15:44:47 +02:00
lickx
b83c999cf4 Correct IMG_BLOOM1 2023-10-21 15:44:28 +02:00
lickx
63d36c5546 Provide detailed info in abandoned land desc..
..which is handy for estate owner/managers and their land administration

Also set back autoreturn to 0 on reclaimed land, because in this case
the estate owner/manager will manually deal with the cleanup themselves
and might decide to leave (some) objects of the previous owner rezzed out.
2023-10-21 15:43:53 +02:00
lickx
dde182e1cc Make allowing HG residents to buy parcels an option
By default this option is true (like in vanilla OpenSim)
2023-10-21 15:41:10 +02:00
lickx
df59617648 Only allow local residents to create groups 2023-10-21 15:36:56 +02:00
lickx
efd33e8563 Mark version as being from our repo, to avoid confusion 2023-10-21 15:36:26 +02:00
lickx
748afbd7f5 Add to help the new bit about parcels for --default-user 2023-10-21 15:34:30 +02:00
lickx
d66548acde Safe perms for abandoned and reclaimed land 2023-10-21 15:34:10 +02:00
lickx
8d4c21c3e2 This is in minutes, not seconds
Already found a caveat: this only works with new regions,
abandoning land uses 0 minutes autoreturn and fully permissive.
2023-10-21 15:29:52 +02:00
lickx
0507750245 Besides objects, also let default user be parcel owner
Because parcel owner and estate owner may differ
2023-10-21 15:28:46 +02:00
lickx
e6f926607b Convert category to int from classifieds
Thanks OpenSim-NGC
2023-10-21 15:28:24 +02:00
lickx
6761b1ab0c Improve new take_copy_restricted functionality 2023-10-14 09:22:18 +02:00
lickx
e443815405 Improve .ini comments 2023-10-14 09:05:38 +02:00
lickx
2ac52e9274 Revert "Addendum to 7a6e51552eac81ca5c527f2749c74e983276ab1b"
This reverts commit c5b3697eaa.
2023-09-28 20:08:06 +02:00
lickx
c5b3697eaa Addendum to 7a6e51552e 2023-09-28 13:29:37 +02:00
lickx
b8cac979d1 Merge branch 'dotnet6' into lickx-dotnet6 2023-09-27 06:16:26 +02:00
lickx
dee6701318 Do away with cache
It doesn't work well with multiple instances behind a proxy
2023-09-17 08:28:50 +02:00
lickx
534c3c1c5c This is a better place for it 2023-09-17 08:28:12 +02:00
lickx
7dab1682a0 Implement functional per-domain status notifications
See commit
2023-09-16 15:53:32 +02:00
lickx
db06b2f1ad Use per- HG friend notify for now in HGStatusNotifier
The domain based Notify never worked; It would notify the wrong grids.
Will look later if the domain based notify can be fixed somehow, since
it would save overhead.

Also, revert most of Nani's friendmodules changes back to upstream since
that is not where the culprit was.

So yay, we have working online/offline notifications for HG friends!
2023-09-14 08:56:41 +02:00
lickx
7ded9a2c0f Mantis 8366: logins have GotAttachmentsData true 2023-09-12 10:25:24 +02:00
lickx
4883c1d80f Addendum to 7a9c591f99 2023-09-12 09:48:49 +02:00
lickx
076fe94388 Merge pull request #15 from lickx/14-entity-transfer-on-slow-dest-grids-scripts-can-break-if-tp-away-too-early
Fixes #14
2023-09-10 09:46:35 +02:00
lickx
45bd03ad2b Fixes #14 2023-09-10 09:42:02 +02:00
lickx
74b66b8bdb Revert "Description column should be 127 bytes UTF-8 string"
This reverts commit 4e3b0129fe.
2023-09-06 02:22:11 +02:00
lickx
f725245040 Revert "Update MAX_ASSET_DESC also"
This reverts commit d98b77a229.
2023-09-06 02:21:47 +02:00
lickx
83c14a5ce3 Update comment info on texture asset 2023-09-05 11:34:17 +02:00
lickx
73fb461607 Use FireAndForget with logout, be less verbose on login
Again, all credits to Nani
2023-09-05 10:17:03 +02:00
lickx
2ded4a4956 More work from Nani on HG friends notifications 2023-09-04 16:08:41 +02:00
lickx
c76667b47c Shorten expiry time 2023-09-03 16:29:28 +02:00
lickx
df729b4e76 Merge branch 'dotnet6' into lickx-dotnet6 2023-08-28 06:46:37 +00:00
lickx
00e932933f Correct IMG_BLOOM1 2023-08-28 04:36:32 +00:00
lickx
dc957ba4b3 Merge branch 'dotnet6' into lickx-dotnet6 2023-08-23 04:52:27 +00:00
lickx
8b14a70473 Update ubode for linux x86_64 2023-08-16 14:21:32 +00:00
lickx
aae0d872de Provide detailed info in abandoned land desc..
..which is handy for estate owner/managers and their land administration

Also set back autoreturn to 0 on reclaimed land, because in this case
the estate owner/manager will manually deal with the cleanup themselves
and might decide to leave (some) objects of the previous owner rezzed out.
2023-08-16 06:50:44 +00:00
lickx
813ccf39b7 Make allowing HG residents to buy parcels an option
By default this option is true (like in vanilla OpenSim)
2023-08-16 05:50:26 +00:00
lickx
3b39c985bf Only allow local residents to create groups 2023-08-16 05:49:25 +00:00
lickx
0a7d3ebf2d Update libubode for ARM64 arch 2023-08-16 02:58:47 +00:00
lickx
086261de20 Merge branch 'dotnet6' into lickx-dotnet6 2023-08-16 02:57:00 +00:00
lickx
d03b8ac712 Mark version as being from our repo, to avoid confusion 2023-08-14 11:39:55 +00:00
lickx
0eddd6e5ee Merge pull request #11 from lickx/issue10
Fixes #10
2023-08-13 20:40:57 +02:00
lickx
df287a1603 Add to help the new bit about parcels for --default-user 2023-08-13 18:28:01 +00:00
lickx
75c46ffb1e Safe perms for abandoned and reclaimed land 2023-08-13 18:25:50 +00:00
lickx
8dd08dfaad This is in minutes, not seconds
Already found a caveat: this only works with new regions,
abandoning land uses 0 minutes autoreturn and fully permissive.
2023-08-13 17:54:41 +00:00
lickx
c38bb9d025 Besides objects, also let default user be parcel owner
Because parcel owner and estate owner may differ
2023-08-13 17:53:20 +00:00
lickx
e8654343c1 Convert category to int from classifieds
Thanks OpenSim-NGC
2023-08-10 07:10:43 +00:00
lickx
32a6cc851f Merge branch 'dotnet6' into lickx-dotnet6 2023-08-09 04:08:41 +00:00
lickx
a08105338e Merge branch 'dotnet6' into lickx-dotnet6 2023-08-02 05:13:40 +00:00
lickx
8d1fa1efd1 Merge branch 'nanipresence' into lickx-dotnet6 2023-07-30 11:18:07 +00:00
lickx
eed17c716f Merge branch 'dotnet6' into nanipresence 2023-07-27 07:50:13 +00:00
lickx
c667858d22 Merge branch 'dotnet6' into lickx-dotnet6 2023-07-27 07:47:39 +00:00
lickx
66280e982f Testing code from nani 2023-07-22 15:33:21 +02:00
lickx
6802f0acb8 Merge branch 'dotnet6' into lickx-dotnet6 2023-07-19 09:20:10 +02:00
lickx
7a2c8f688f Add ARM64 support for sqlite and ubODE 2023-07-12 14:06:42 +00:00
lickx
bf15a31a57 Merge branch 'dotnet6' into lickx-dotnet6 2023-07-07 06:44:37 +02:00
lickx
8137562074 Merge branch 'dotnet6' into lickx-dotnet6 2023-07-06 07:53:56 +02:00
lickx
7b59f4d76d Merge branch 'dotnet6' into lickx-dotnet6 2023-07-01 06:49:09 +02:00
lickx
68c12024fe Merge branch 'dotnet6' into lickx-dotnet6 2023-06-23 06:42:10 +02:00
lickx
258efc97af Resolves directional error with trains etc 2023-06-21 14:52:12 +02:00
lickx
10ac92f6a0 Merge branch 'dotnet6' into lickx-dotnet6 2023-06-21 09:43:43 +02:00
lickx
1940dea666 Merge branch 'dotnet6' into lickx-dotnet6 2023-06-18 16:42:17 +02:00
lickx
9b5844ed26 Merge branch 'dotnet6' into lickx-dotnet6 2023-06-03 07:10:33 +02:00
lickx
125e84431e Merge branch 'dotnet6' into lickx-dotnet6 2023-06-01 04:53:27 +02:00
lickx
b5bc45f7a7 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-27 07:39:58 +02:00
lickx
646ae05206 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-25 07:09:55 +02:00
lickx
37832b9c87 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-24 08:52:16 +02:00
lickx
605391fc3a Merge branch 'dotnet6' into lickx-dotnet6 2023-05-22 12:23:24 +02:00
lickx
a9428458d7 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-18 06:32:14 +02:00
lickx
d1a9c122f0 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-14 11:04:43 +02:00
lickx
f5b5cb46c1 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-09 06:06:26 +02:00
lickx
a519de3dfc Merge branch 'dotnet6' into lickx-dotnet6 2023-05-06 03:48:53 +02:00
lickx
b258108d17 Merge branch 'dotnet6' into lickx-dotnet6 2023-05-01 08:54:54 +02:00
lickx
c1e7f951a1 Merge branch 'dotnet6' into lickx-dotnet6 2023-04-28 05:39:31 +02:00
lickx
048b2670c5 Merge branch 'dotnet6' into lickx-dotnet6 2023-04-26 06:20:14 +02:00
lickx
0fe8b426d8 One more check 2023-04-21 08:00:55 +02:00
lickx
2fa28d6ce3 Only attempt to resume scripts when they exist 2023-04-21 08:00:41 +02:00
lickx
72332de1ad Remove obsolete map throttle for FS
That was for one specific very old Firestorm, which is no longer allowed on OsGrid and other grids
2023-04-21 08:00:11 +02:00
lickx
1d14fee2c7 Lowercase some asset UUID's, include water texture in setting 2023-04-21 07:57:37 +02:00
lickx
5f62c49450 Merge branch 'dotnet6' into lickx-dotnet6 2023-04-19 04:22:50 +02:00
lickx
e6dbd8b477 Merge branch 'dotnet6' into lickx-dotnet6 2023-04-17 11:05:35 +02:00
lickx
b392cd9d2d Lowercase some asset UUID's, include water texture in setting 2023-04-17 10:58:51 +02:00
lickx
f7e899c6b7 Merge branch 'dotnet6' into lickx-dotnet6 2023-04-14 09:04:43 +02:00
lickx
933b1e97f9 Remove obsolete map throttle for FS
That was for one specific very old Firestorm, which is no longer allowed on OsGrid and other grids
2023-04-13 11:12:23 +02:00
lickx
8db177e76f One more check 2023-04-08 06:48:52 +02:00
lickx
2a5f01bfd2 Only attempt to resume scripts when they exist 2023-04-04 13:00:12 +02:00
lickx
3fbac63c3b Merge branch 'dotnet6' into lickx-dotnet6 2023-03-30 13:40:27 +02:00
lickx
c3d562ce61 Merge branch 'master' into lickx 2023-03-27 15:30:01 +02:00
lickx
fe1a79a878 Merge branch 'dotnet6' into lickx-dotnet6 2023-03-24 04:16:46 +01:00
lickx
7a6e51552e Apply revert again, it is needed to unbreak scripted objects
That change causes more breakage! So we undo it.
Expect some mantises from people on that one lol
2023-03-20 18:54:30 +01:00
lickx
9c2bf18565 Merge branch 'lickx' of https://github.com/lickx/opensim-lickx into lickx 2023-03-16 17:37:33 +01:00
lickx
20cebb7770 Merge branch 'master' into lickx 2023-03-16 17:37:14 +01:00
lickx
5cd4fdb8ff Merge branch 'dotnet6' into lickx-dotnet6 2023-03-16 09:01:11 +01:00
lickx
07b7d947c8 Merge branch 'dotnet6' into lickx-dotnet6 2023-03-15 06:02:46 +01:00
lickx
1e0789b06b Merge branch 'master' into lickx 2023-03-11 12:00:05 +01:00
lickx
793f94027d Merge branch 'dotnet6' into lickx-dotnet6 2023-03-10 17:19:59 +01:00
lickx
10c04e3d71 Revert "Revert an upstream change"
This reverts commit c971a55f48.

The issue that the revert solved, was caused by a bad script
2023-03-10 17:17:24 +01:00
lickx
eeffce3e44 Merge branch 'dotnet6' into lickx-dotnet6 2023-03-08 07:48:14 +01:00
lickx
d9f0cdee5c Merge branch 'dotnet6' into lickx-dotnet6 2023-03-02 08:15:38 +01:00
lickx
e2ecd04e9a Cleanup 2023-03-01 11:18:14 +01:00
lickx
bdbf95d1ca Move incoming agent from debug to info logging 2023-03-01 10:57:24 +01:00
lickx
b1cd284b5d Stop resume scripts if HG user left the scene early 2023-03-01 10:52:36 +01:00
lickx
ace2f0bdcb Stop resume scripts if HG user left the scene early 2023-03-01 05:49:16 +01:00
lickx
0ddd30c1d8 Merge branch 'master' into lickx 2023-02-28 18:52:16 +01:00
lickx
4d91349a92 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-25 05:06:16 +01:00
lickx
d3a842852f Merge branch 'dotnet6' into lickx-dotnet6 2023-02-23 07:12:24 +01:00
lickx
fddc9eac26 Revert "Revert "change lsl integer parsing""
This reverts commit b1f64a2dd0.
2023-02-23 07:11:16 +01:00
lickx
b1f64a2dd0 Revert "change lsl integer parsing"
This reverts commit 92e25a9377.
2023-02-21 04:42:28 +01:00
lickx
4907534173 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-18 08:48:55 +01:00
lickx
a5fc6752f6 Move incoming agent from debug to info logging 2023-02-16 08:28:02 +01:00
lickx
55fbe537c7 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-15 19:24:49 +01:00
lickx
fc736b2f62 There is no classifieds datastore 2023-02-15 05:12:16 +01:00
lickx
e30926e8b3 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-15 04:58:04 +01:00
lickx
def073f6c8 Add missing classifieds table 2023-02-15 04:56:52 +01:00
lickx
02be06a439 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-11 05:33:35 +01:00
lickx
1b05e71f54 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-10 05:32:48 +01:00
lickx
a5a78ef165 Merge branch 'master' into lickx 2023-02-09 20:22:54 +01:00
lickx
c971a55f48 Revert an upstream change
That caused issues with button positioning on HUDs and possibly
other objects
2023-02-09 20:10:29 +01:00
lickx
4ef49f70cb Merge branch 'dotnet6' into lickx-dotnet6 2023-02-09 19:57:02 +01:00
lickx
236e80f5c3 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-08 06:57:31 +01:00
lickx
e55ce0cdf4 Merge branch 'dotnet6' into lickx-dotnet6 2023-02-07 05:40:04 +01:00
lickx
f2e3787424 Merge branch 'master' into lickx 2023-02-06 15:46:01 +01:00
lickx
fb24eab5bc Merge branch 'dotnet6' into lickx-dotnet6 2023-02-02 04:05:52 +01:00
lickx
8199a62091 Merge branch 'master' into lickx 2023-01-27 03:50:28 +01:00
lickx
06c232f20f Merge branch 'dotnet6' into lickx-dotnet6 2023-01-27 03:40:50 +01:00
lickx
b1acf760d1 XEngine is no longer an option, so remove config 2023-01-26 17:48:30 +01:00
lickx
21e5c84ba6 Merge branch 'dotnet6' into lickx-dotnet6 2023-01-26 03:00:16 +01:00
lickx
b002256496 Remove an unused optional feature for code clarity 2023-01-23 11:43:06 +01:00
lickx
5c618d2986 Remove an unused optional feature for code clarity 2023-01-23 05:11:11 +01:00
lickx
69af836523 Also set attachments to group on HG entity transfer
(We already sorted starting their scripts in another patch, mantis 8366)
2023-01-22 05:25:22 +01:00
lickx
3f047f53a0 Change attachments group and start scripts on group change 2023-01-22 05:25:04 +01:00
lickx
6fbdb47f5b Also set attachments to group on HG entity transfer
(We already sorted starting their scripts in another patch, mantis 8366)
2023-01-20 10:57:24 +01:00
lickx
d58864c86c Change attachments group and start scripts on group change 2023-01-19 13:39:14 +01:00
lickx
25ff65ae05 Update MAX_ASSET_DESC also 2023-01-17 09:28:16 +01:00
lickx
27e0684cbc Description column should be 127 bytes UTF-8 string 2023-01-17 09:28:02 +01:00
lickx
6d31514719 Better (safer) land defaults 2023-01-17 09:27:35 +01:00
lickx
04a78df6f7 Make llGiveInventory work for HG recipients 2023-01-17 09:26:12 +01:00
lickx
7de334ccbd Update log strings 2023-01-17 09:25:00 +01:00
lickx
ef0b17113d Put back god stuff in OpenSim.ini
Note that on our branch region_owner_is_god defaults to false,
so it will only be enabled by setting that line to true in the ini!
2023-01-17 09:24:36 +01:00
lickx
b1e8b76d59 ubODE and yEngine as defaults 2023-01-17 09:24:13 +01:00
lickx
55c2c08e3b Merge branch 'master' into lickx 2023-01-17 09:21:21 +01:00
lickx
d98b77a229 Update MAX_ASSET_DESC also 2023-01-16 07:24:51 +01:00
lickx
4e3b0129fe Description column should be 127 bytes UTF-8 string 2023-01-16 05:22:49 +01:00
lickx
21c42357c1 Merge branch 'dotnet6' into lickx-dotnet6 2023-01-14 16:46:30 +01:00
lickx
ea7f84f0ff Better (safer) land defaults 2023-01-14 16:41:25 +01:00
lickx
a91e68c609 Merge branch 'dotnet6' into lickx-dotnet6 2023-01-12 04:29:13 +01:00
lickx
abd2a5c76c Merge branch 'dotnet6' into lickx-dotnet6 2023-01-09 16:29:37 +01:00
lickx
03f67418b2 Make llGiveInventory work for HG receipants 2023-01-05 18:28:38 +01:00
lickx
de69662138 Merge branch 'dotnet6' into lickx-dotnet6 2022-12-30 12:10:31 +01:00
lickx
40c90fdca6 Merge branch 'master' into lickx 2022-12-29 04:58:12 +01:00
lickx
1af18b201e Merge branch 'dotnet6' into lickx-dotnet6 2022-12-29 04:53:37 +01:00
lickx
85dc3c6e2a Merge branch 'master' into lickx 2022-12-27 05:39:03 +01:00
lickx
1c22b2a531 Mantis 9042 allow llStopAnimation with overridden animations 2022-12-27 05:36:02 +01:00
lickx
2aab323e56 Merge branch 'dotnet6' into lickx-dotnet6 2022-12-24 06:46:15 +01:00
lickx
4d6e3b1133 Allow llStopAnimation to work for all overridden anims 2022-12-23 12:38:38 +01:00
lickx
2d0006014c Mantis 9042 stopping default "sit" doesn't work 2022-12-22 15:15:39 +01:00
lickx
9e5c81b4cd Merge branch 'dotnet6' into lickx-dotnet6 2022-12-19 04:40:19 +01:00
lickx
d9c1624327 Merge branch 'dotnet6' into lickx-dotnet6 2022-12-17 16:58:31 +01:00
lickx
910050b382 Update log strings 2022-12-13 12:40:01 +01:00
lickx
08b0d1fdfb Merge branch 'dotnet6' of https://github.com/opensim/opensim into lickx-dotnet6 2022-12-10 09:03:29 +01:00
lickx
b4a4190f53 Put back god stuff in OpenSim.ini
Note that on our branch region_owner_is_god defaults to false,
so it will only be enabled by setting that line to true in the ini!
2022-12-10 02:09:37 +01:00
lickx
5aa4ea9d71 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-12-09 14:33:02 +01:00
lickx
72a5f17ed1 Merge branch 'lickx-dotnet6' of https://github.com/lickx/opensim-lickx into lickx-dotnet6 2022-12-05 04:46:13 +01:00
lickx
eb0a516c32 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-12-05 04:45:30 +01:00
lickx
7a470457c8 Revert "Test"
This reverts commit d7474630b0.
2022-11-28 15:26:27 +01:00
lickx
991c8d08c6 Merge branch 'lickx-dotnet6' of https://github.com/lickx/opensim-lickx into lickx-dotnet6 2022-11-28 15:03:49 +01:00
lickx
d7474630b0 Test 2022-11-28 15:02:59 +01:00
lickx
49c5f5e70c Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-27 10:10:36 +01:00
lickx
07dc6b3ec0 No that didn't work for the Bento issue 2022-11-27 10:10:02 +01:00
lickx
4d20dfc65a Merge pull request #6 from lickx/lickx-testspc
Lickx testspc
2022-11-26 13:26:48 +01:00
lickx
4c4925d758 Merge branch 'lickx-dotnet6' into lickx-testspc 2022-11-26 13:09:07 +01:00
lickx
e452d141ac Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-26 13:08:07 +01:00
lickx
743091fe94 Merge branch 'lickx-dotnet6' into lickx-testspc 2022-11-25 12:48:03 +01:00
lickx
eed9169708 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-25 06:00:22 +01:00
lickx
0ed19f6ed9 Merge branch 'master' into lickx 2022-11-18 06:47:05 +01:00
lickx
a80f14a705 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-18 06:37:35 +01:00
lickx
0e886b85f1 Merge branch 'master' into lickx 2022-11-15 06:11:29 +01:00
lickx
032c981cbd Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-13 10:49:28 +01:00
lickx
2f56acf6ea Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-11 13:00:57 +01:00
lickx
d9b1fce36e Merge branch 'master' into lickx 2022-11-10 04:40:36 +01:00
lickx
d9c7abfcd1 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-10 04:25:19 +01:00
lickx
264cc7ce34 ubODE and yEngine as defaults 2022-11-07 08:57:40 +01:00
lickx
d23667eaf9 Merge branch 'master' into lickx 2022-11-07 07:52:47 +01:00
lickx
6f90f98ab3 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-06 12:47:49 +01:00
lickx
6b3f7be469 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-05 06:40:24 +01:00
lickx
9256cfe326 Merge branch 'master' into lickx 2022-11-01 03:40:28 +01:00
lickx
6538ab9694 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-11-01 03:36:52 +01:00
lickx
b4a1d3b496 Merge branch 'master' into lickx 2022-10-29 20:43:32 +02:00
lickx
58a5d4dab6 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-29 05:04:31 +02:00
lickx
337e2d6cb1 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-27 07:35:08 +02:00
lickx
7a58d49693 Merge branch 'master' into lickx 2022-10-24 19:02:00 +02:00
lickx
51fea3fd6b Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-24 03:53:43 +02:00
lickx
a635f3f284 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-23 17:18:47 +02:00
lickx
3cc7afc511 Merge branch 'master' into lickx 2022-10-23 07:10:34 +02:00
lickx
e03d15cff6 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-22 19:54:52 +02:00
lickx
c55507857b Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-20 12:04:39 +02:00
lickx
b28fd6a0a6 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-19 07:42:42 +02:00
lickx
9ce83e46e4 Try this the old way 2022-10-18 14:42:56 +02:00
lickx
9f954d0c41 Merge branch 'master' into lickx 2022-10-18 05:52:02 +02:00
lickx
bca88d85a9 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-18 05:47:25 +02:00
lickx
0a8bc87903 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-17 05:29:58 +02:00
lickx
1ea930749a Merge branch 'master' into lickx 2022-10-16 06:10:54 +02:00
lickx
797b5d005a Merge branch 'dotnet6' of https://github.com/opensim/opensim into lickx-dotnet6 2022-10-16 06:08:21 +02:00
lickx
6a2c1801de Merge branch 'master' into lickx 2022-10-10 05:40:08 +02:00
lickx
b868072ac0 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-10 05:10:21 +02:00
lickx
81a6391633 Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-09 06:49:14 +02:00
lickx
1b39a376fc Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-08 09:36:19 +02:00
lickx
3727520d7a Merge branch 'dotnet6' into lickx-dotnet6 2022-10-05 10:25:05 +02:00
lickx
ff41bede4a Fix robust logging 2022-10-04 13:01:06 +02:00
lickx
530fe86a8a Merge branch 'dotnet6' of git://opensimulator.org/git/opensim into lickx-dotnet6 2022-10-04 08:07:04 +02:00
lickx
e5a16c97fb Merge branch 'master' into consolestuff 2022-09-30 14:16:36 +02:00
lickx
87657699ac Revert "Revert "mantis 9025: reduce latency a bit""
This reverts commit 5670b03208.
2022-09-30 14:16:28 +02:00
lickx
3a17aeceef Revert "Revert "a few changes to local console; add pooling of Console.KeyAvailable instead of waiting on keyread, that has treading issues. Thanks ALicia for some ideas on this""
This reverts commit 752d871e44.
2022-09-30 14:16:08 +02:00
lickx
aa20cf751c Merge branch 'master' into lickx 2022-09-28 19:59:34 +02:00
lickx
05b84d661e Merge branch 'master' into lickx 2022-09-25 10:01:59 +02:00
lickx
edb40ba944 Merge branch 'master' into lickx 2022-09-23 08:22:43 +02:00
lickx
752d871e44 Revert "a few changes to local console; add pooling of Console.KeyAvailable instead of waiting on keyread, that has treading issues. Thanks ALicia for some ideas on this"
This reverts commit 87ba2d7b43.
2022-09-23 08:14:20 +02:00
lickx
5670b03208 Revert "mantis 9025: reduce latency a bit"
This reverts commit 086fcc7ff7.
2022-09-23 08:08:57 +02:00
lickx
2b510f2ced Merge branch 'master' into lickx 2022-09-19 07:39:07 +02:00
lickx
8ce5e0122a Merge branch 'master' into lickx 2022-09-16 14:25:56 +02:00
lickx
d4b7a24ffb Change release notes link 2022-09-12 08:55:26 +02:00
lickx
9851848d12 Add pre-EEP sun, issue 2 2022-09-01 05:55:32 +02:00
lickx
29f80da12d Merge branch 'master' into lickx 2022-08-31 07:03:22 +02:00
lickx
e0a8c9ce12 Merge branch 'master' into lickx 2022-08-28 04:48:27 +02:00
lickx
43273fa24f Merge branch 'master' into lickx 2022-08-26 16:45:08 +02:00
lickx
bf4f218e0e Merge branch 'master' into lickx 2022-08-25 04:50:12 +02:00
lickx
11ddb82aa1 Merge branch 'master' into lickx 2022-08-22 10:26:03 +02:00
lickx
6299fd8dd1 Merge branch 'master' into lickx 2022-08-18 08:37:06 +02:00
lickx
1c95722b70 Merge branch 'master' into lickx 2022-08-17 14:22:32 +02:00
lickx
1e84dfe8c9 Merge pull request #4 from lickx/ground-textures
Upgrade ground textures, closes #1
2022-08-17 14:20:11 +02:00
lickx
ea5926b946 Merge pull request #3 from lickx/missing-assets
Add missing assets, closes #2
2022-08-17 14:19:25 +02:00
lickx
51df696e64 Upgrade ground textures, closes #1 2022-08-17 14:17:19 +02:00
lickx
cca0f4e607 Add missing assets, closes #2 2022-08-17 14:12:45 +02:00
lickx
343dd5350d Merge branch 'master' into lickx 2022-08-15 13:02:43 +02:00
lickx
1d62ad9080 Merge branch 'master' into lickx 2022-08-12 06:06:15 +02:00
lickx
49db05a1a8 Merge branch 'master' into lickx 2022-08-10 11:58:02 +02:00
lickx
adf3752eb6 Merge branch 'master' into lickx 2022-08-09 11:30:50 +02:00
lickx
b69889220f Merge branch 'master' into lickx 2022-07-20 08:04:38 +02:00
lickx
9178068d57 Merge branch 'master' into lickx 2022-07-17 07:28:28 +02:00
lickx
465814f0e5 Merge branch 'master' into lickx 2022-07-12 13:44:56 +02:00
lickx
8a930cfae8 Merge branch 'master' into lickx 2022-07-07 15:43:13 +02:00
lickx
84d056a07a Merge branch 'master' into lickx 2022-07-03 19:01:49 +02:00
lickx
0b743c6495 Merge branch 'master' into lickx 2022-06-24 05:16:42 +02:00
lickx
e832126e3d Merge branch 'master' into lickx 2022-06-21 09:34:27 +02:00
lickx
df3e69d425 Merge branch 'master' into lickx 2022-06-20 11:20:51 +02:00
lickx
06db60e46b Merge branch 'master' into lickx 2022-06-19 07:27:45 +02:00
lickx
5f0dfd7b57 Try to fix mousewalk 2022-06-17 14:48:46 +02:00
lickx
5308cc6c92 Preserve formatting from master, for cleaner diffs
Also rephrase the slurl stuff
2022-06-16 15:44:10 +02:00
lickx
8b74d85b4e Merge branch 'master' into lickx 2022-06-11 08:14:06 +02:00
lickx
66e2a98068 Merge branch 'master' into lickx 2022-06-04 05:03:21 +02:00
lickx
511860c408 Merge branch 'master' into lickx 2022-06-02 10:01:45 +02:00
lickx
61ce621b9d Merge branch 'master' into lickx 2022-05-27 17:17:25 +02:00
lickx
34a17490d5 Merge branch 'master' into lickx 2022-05-26 15:39:09 +02:00
lickx
d4de788fb3 Merge branch 'master' into lickx 2022-05-23 01:36:53 +02:00
lickx
3ca00ad4bb Merge branch 'master' into lickx 2022-05-16 03:55:44 +02:00
lickx
c10638ae02 Merge branch 'master' into lickx 2022-05-13 08:23:39 +02:00
lickx
674b7aa079 Merge branch 'master' into lickx 2022-05-12 06:30:12 +02:00
lickx
08612d2dad Merge branch 'master' into lickx 2022-05-11 17:21:35 +02:00
lickx
f885e5ba16 Merge branch 'master' into lickx 2022-05-07 06:04:36 +02:00
lickx
4262ac57e7 Merge branch 'master' into lickx 2022-05-05 17:53:02 +02:00
lickx
1f4f739578 Merge branch 'master' into lickx 2022-05-03 17:00:46 +02:00
lickx
95a9325b06 Merge branch 'master' into lickx 2022-05-03 06:44:44 +02:00
lickx
26c84cbb46 Merge branch 'master' into lickx 2022-05-02 17:24:17 +02:00
lickx
d06d1c4dd6 Merge branch 'master' into lickx 2022-05-02 11:15:47 +02:00
lickx
1a2ce55c44 Merge branch 'master' into lickx 2022-04-27 11:52:23 +02:00
lickx
c78ed0b731 Merge branch 'master' into lickx 2022-04-25 09:15:32 +02:00
lickx
8cb3c7a736 Merge branch 'master' into lickx 2022-04-24 07:29:12 +02:00
lickx
a8768e1b8d More sane godmode defaults 2022-04-22 20:13:45 +02:00
lickx
0f67c653cd Merge branch 'master' into lickx 2022-04-22 17:25:22 +02:00
lickx
34e1713554 Merge branch 'master' into lickx 2022-04-21 05:30:23 +02:00
lickx
f464a7e992 Merge branch 'master' into lickx 2022-04-20 08:03:28 +02:00
lickx
fd515e128f Line endings... 2022-04-20 08:00:56 +02:00
lickx
f87d699757 Merge branch 'master' into lickx 2022-04-19 10:49:52 +02:00
lickx
3903caa517 Merge branch 'master' into lickx 2022-04-17 04:57:49 +02:00
lickx
26665acd7a Merge branch 'master' into lickx 2022-04-16 08:01:22 +02:00
lickx
cb3ae3cc48 Merge branch 'master' into lickx 2022-04-15 08:57:09 +02:00
lickx
d3da948652 Merge branch 'master' into lickx 2022-04-13 07:32:24 +02:00
lickx
f38d763dd0 Merge branch 'master' into lickx 2022-04-10 19:33:33 +02:00
lickx
9b73df3a10 Merge branch 'master' into lickx 2022-04-07 16:24:51 +02:00
lickx
eecd1324c3 Merge branch 'master' into lickx 2022-04-03 09:20:09 +02:00
lickx
fc8566281f Merge branch 'master' into lickx 2022-04-02 16:47:52 +02:00
lickx
83503ed529 Merge branch 'master' into lickx 2022-03-30 18:34:45 +02:00
lickx
047c9971c2 Merge branch 'master' into lickx 2022-03-28 10:04:07 +02:00
lickx
9925365091 Merge branch 'master' into lickx 2022-03-22 17:20:26 +01:00
lickx
52ae6745f3 Merge branch 'master' into lickx 2022-03-19 05:14:33 +01:00
lickx
d89a8c6708 Merge branch 'master' into lickx 2022-03-18 12:26:08 +01:00
lickx
eadd7bdff7 Merge branch 'master' into lickx 2022-03-15 08:57:39 +01:00
lickx
8d133e52c9 Merge branch 'master' into lickx 2022-03-03 13:29:22 +01:00
lickx
05347db242 Merge branch 'master' into lickx 2022-02-26 12:52:14 +01:00
lickx
f5fb8b81d8 Merge branch 'master' into lickx 2022-02-24 01:51:24 +01:00
lickx
7ddfd275fc Merge branch 'master' into lickx 2022-02-21 10:04:45 +01:00
lickx
fbcea660df Merge branch 'master' into lickx 2022-02-18 05:28:07 +01:00
lickx
b72df30151 Less drastic, but still ethical defaults 2022-02-17 13:55:30 +01:00
lickx
b5c3d157cb Revert "Always return empty string for osGetAgentIP"
This reverts commit f7cb87f6e4.
2022-02-17 13:36:51 +01:00
lickx
5531b329fe Merge branch 'master' into lickx 2022-02-14 09:38:04 +01:00
lickx
46a14dc8da Merge branch 'master' into lickx 2022-02-11 12:39:05 +01:00
lickx
8bb1cf747d Merge branch 'master' into lickx 2022-02-08 04:37:17 +01:00
lickx
6447fae297 Discourage god mode in the example config 2022-02-05 03:39:15 +01:00
lickx
f218605904 No god mode for region owners by default 2022-02-04 06:25:02 +01:00
lickx
823602d69a Merge branch 'master' into lickx 2022-02-02 05:15:47 +01:00
lickx
f7cb87f6e4 Always return empty string for osGetAgentIP 2022-02-01 13:49:12 +01:00
lickx
b8a6b6d3c1 Merge branch 'master' into lickx 2022-02-01 13:12:28 +01:00
lickx
121ae48f17 Merge branch 'master' into lickx 2022-01-29 14:35:04 +01:00
lickx
94a9a53f9f Merge branch 'master' into lickx 2022-01-24 14:21:18 +01:00
lickx
3ade7afc34 Merge branch 'master' into lickx 2022-01-22 15:03:45 +01:00
lickx
3b96981528 Merge branch 'master' into lickx 2022-01-14 11:06:36 +01:00
lickx
80254a2a8a Faster vector checking 2022-01-12 08:46:40 +01:00
lickx
2fca7b9989 Merge branch 'master' into lickx 2022-01-12 08:32:47 +01:00
lickx
dd7db65ded Merge branch 'master' into lickx 2022-01-10 14:30:44 +01:00
lickx
5716cc6a12 Merge branch 'master' into lickx 2022-01-09 06:35:05 +01:00
lickx
983947d8f7 Merge branch 'master' into lickx 2022-01-09 01:19:55 +01:00
lickx
18b74627e5 Merge branch 'master' into lickx 2022-01-06 07:06:25 +01:00
lickx
1d34111f58 Merge branch 'master' into lickx 2022-01-04 07:02:26 +01:00
lickx
a280a6e34e Merge branch 'master' into lickx 2022-01-03 14:41:54 +01:00
lickx
f83c7839dc Merge branch 'master' into lickx 2022-01-01 05:33:50 +01:00
lickx
781ff605e0 Merge branch 'master' into lickx 2021-12-24 08:25:26 +01:00
lickx
abf61a464b Merge branch 'master' into lickx 2021-12-23 06:34:57 +01:00
lickx
3464cabdb7 Merge branch 'master' into lickx 2021-12-20 05:29:00 +01:00
lickx
ce04c54904 Merge branch 'master' into lickx 2021-12-17 06:25:20 +01:00
lickx
2a3dc1d341 Merge branch 'scriptqueue' into lickx 2021-12-15 12:33:47 +01:00
lickx
aa6fced881 Fix script state race condition 2021-12-15 12:28:49 +01:00
lickx
2a8a073cd6 Merge branch 'master' into lickx 2021-12-15 07:40:04 +01:00
lickx
68885c933b Merge branch 'hardenperms' into lickx 2021-12-15 07:29:09 +01:00
lickx
3b6f2c81dd Add hardened permissions option 2021-12-15 07:27:57 +01:00
lickx
3b5e9933ef Revert "Disallow selling work created by other avatars"
This reverts commit 54f6e52a06.
2021-12-15 07:08:14 +01:00
lickx
52cd010067 Merge branch 'viewerallowdeny' into lickx 2021-12-15 06:54:28 +01:00
lickx
41af1a1793 Make viewer allow/ban list work for sims 2021-12-15 06:53:36 +01:00
lickx
93ad6e73cf Merge branch 'folderversion' into lickx 2021-12-15 06:43:15 +01:00
lickx
7a9c591f99 Use int for folder versions 2021-12-15 06:42:45 +01:00
lickx
409f0d4096 Merge branch 'utf8' into lickx 2021-12-15 06:39:25 +01:00
lickx
7ae53fdb0a Unicode profiles and picks 2021-12-15 06:38:50 +01:00
lickx
2a73429fee Merge branch 'mantis8539' into lickx 2021-12-13 16:51:03 +01:00
lickx
7945fe64a9 Mantis 8539 2021-12-13 16:50:02 +01:00
lickx
c5f90d87b5 Use avatar rotation for attachments with local=true
Signed-off-by: lickx <sinesurfer@gmail.com>
2021-12-13 16:43:47 +01:00
lickx
6d018e8646 Mantis 8366
Signed-off-by: lickx <sinesurfer@gmail.com>
2021-12-13 16:43:15 +01:00
lickx
d58c0bbc2d Improve MoveToTarget for Mantis 8250
Signed-off-by: lickx <sinesurfer@gmail.com>
2021-12-13 16:42:48 +01:00
lickx
775f18c4bd Mantis 6311
Signed-off-by: lickx <sinesurfer@gmail.com>
2021-12-13 16:41:39 +01:00
lickx
54f6e52a06 Disallow selling work created by other avatars
Signed-off-by: lickx <sinesurfer@gmail.com>
2021-12-13 16:41:04 +01:00
285 changed files with 7679 additions and 10604 deletions

View File

@@ -706,6 +706,21 @@ namespace OpenSim.Groups
m_groupData.SetAgentActiveGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID);
ScenePresence sp = ((Scene)(remoteClient.Scene)).GetScenePresence(remoteClient.AgentId);
List<SceneObjectGroup> attachments = sp.GetAttachments();
foreach(SceneObjectGroup so in attachments)
{
//m_log.DebugFormat("[GROUPS MODULE]: Setting new group and checking scripts to run in attachment {0} for {1}", so.Name, so.OwnerID);
so.SetGroup(groupID, remoteClient);
if (so.ContainsScripts() && so.RunningScriptCount() == 0)
{
so.RootPart.ParentGroup.CreateScriptInstances(
0, false, sp.Scene.DefaultScriptEngine, sp.GetStateSource());
so.ResumeScripts();
}
}
// Changing active group changes title, active powers, all kinds of things
// anyone who is in any region that can see this client, should probably be
// updated with new group info. At a minimum, they should get ScenePresence
@@ -981,11 +996,16 @@ namespace OpenSim.Groups
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentActiveGroupRole(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, titleRoleID);
UUID agentID = remoteClient.AgentId;
m_groupData.SetAgentActiveGroupRole(agentID.ToString(), agentID.ToString(), groupID, titleRoleID);
// TODO: Not sure what all is needed here, but if the active group role change is for the group
// the client currently has set active, then we need to do a scene presence update too
// if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID)
// If the active group role change is for the group
// the client currently has set active, then we need to
// set the active group again for the tag to update
if (m_groupData.GetAgentActiveMembership(agentID.ToString(), agentID.ToString()).GroupID == groupID)
{
m_groupData.SetAgentActiveGroup(agentID.ToString(), agentID.ToString(), groupID);
}
SendDataUpdate(remoteClient, true);
}
@@ -1582,5 +1602,6 @@ namespace OpenSim.Groups
{
return client is null ? UUID.Zero : client.AgentId;
}
}
}

View File

@@ -88,8 +88,8 @@ namespace OpenSim.OfflineIM
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["PrincipalID"] = principalID;
Dictionary<string, object> ret = MakeRequest("GET", sendData);
if (ret == null)
return ims;
@@ -118,12 +118,14 @@ namespace OpenSim.OfflineIM
}
}
}
return ims;
}
public bool StoreMessage(GridInstantMessage im, out string reason)
{
Dictionary<string, object> sendData = OfflineIMDataUtils.GridInstantMessage(im);
Dictionary<string, object> ret = MakeRequest("STORE", sendData);
if (ret == null)

View File

@@ -163,5 +163,6 @@ namespace OpenSim.OfflineIM
m_Database.Delete("PrincipalID", userID.ToString());
m_Database.Delete("FromID", userID.ToString());
}
}
}

View File

@@ -1,428 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace osWebRtcVoice
{
// There are several different hashing systems ranging from int's to SHA versions.
// The model here is to create a hasher of the desired type, do Add's of things to
// hash, and complete with a Finish() to return a BHash that contains the hash value.
// Since some hash functions are incremental (doing Add's) while some are buffer
// oriented (create a hash of a byte buffer), the interface is built to cover both.
// Some optimizations are implemented internally (like not copying the buffer
// for buffer based hashers if Finish(bytes) is used).
//
// var hasher = new BHashSHA256();
// BHash bHash = hasher.Finish(buffer);
// byte[] theHash = bHash.ToByte();
//
// Note that BHash has IEquatable and IComparible so it can be used in Dictionaries
// and sorted Lists.
//
// The C# GetHashCode() method returns an int that is usually based on location.
// Signatures should really be at least 64 bits so these routines generate
// ulong's for hashes and fold them to make the int for GetHashCode().
// Create a BHasher, do a bunch of 'Add's, then Finish().
public interface IBHasher {
// Create a new object implementing BHasher, then Add values to be hashed
void Add(byte c);
void Add(ushort c);
void Add(uint c);
void Add(ulong c);
void Add(float c);
void Add(byte[] c, int offset, int len);
void Add(string c);
void Add(BHash c);
BHash Finish();
// Finish and add byte array.
// If no Add's before, can do the hashing without copying the byte array
BHash Finish(byte[] c);
BHash Finish(byte[] c, int offset, int len);
// Get the hash code after doing a Finish()
BHash Hash();
}
// ======================================================================
// BHasher computes a BHash which holds the hash value after Finish() is called.
public abstract class BHash : IEquatable<BHash>, IComparable<BHash> {
public abstract override string ToString();
public abstract byte[] ToBytes();
public abstract ulong ToULong(); // returns the hash of the hash if not int based hash
public abstract bool Equals(BHash other);
public abstract int CompareTo(BHash obj);
// public abstract int Compare(BHash x, BHash y); // TODO: do we need this function?
public abstract override int GetHashCode(); // to match the C# standard hash function
}
// A hash that is an UInt64
public class BHashULong : BHash {
protected ulong _hash;
public BHashULong() {
_hash = 5131;
}
public BHashULong(ulong initialHash) {
_hash = initialHash;
}
// the .NET GetHashCode uses an int. Make conversion easy.
public BHashULong(int initialHash) {
_hash = (ulong)initialHash;
}
public override string ToString() {
return _hash.ToString();
}
public override byte[] ToBytes() {
return BitConverter.GetBytes(_hash);
}
public override ulong ToULong() {
return _hash;
}
public override bool Equals(BHash other) {
bool ret = false;
if (other != null) {
BHash bh = other as BHashULong;
if (bh != null) {
ret = _hash.Equals(bh.ToULong());
}
}
return ret;
}
public override int CompareTo(BHash other) {
int ret = 1;
if (other != null) {
if (other is BHashULong bh) {
ret = _hash.CompareTo(bh.ToULong());
}
}
return ret;
}
public override int GetHashCode() {
ulong upper = (_hash >> 32) & 0xffffffff;
ulong lower = _hash & 0xffffffff;
return (int)(upper ^ lower);
}
}
// A hash that is an array of bytes
public class BHashBytes : BHash {
private readonly byte[] _hash;
public BHashBytes() {
_hash = new byte[0];
}
public BHashBytes(byte[] initialHash) {
_hash = initialHash;
}
public override string ToString() {
// BitConverter puts a hyphen between each byte. Remove them
return BitConverter.ToString(_hash).Replace("-", String.Empty);
}
public override byte[] ToBytes() {
return _hash;
}
public override ulong ToULong() {
return this.MakeHashCode();
}
public override bool Equals(BHash other) {
bool ret = false;
if (other != null) {
BHash bh = other as BHashBytes;
if (bh != null) {
ret = _hash.Equals(bh.ToBytes());
}
}
return ret;
}
public override int CompareTo(BHash other) {
int ret = 1;
if (other != null) {
BHash bh = other as BHashBytes;
if (bh != null) {
byte[] otherb = bh.ToBytes();
if (_hash.Length != otherb.Length) {
ret = _hash.Length.CompareTo(otherb.Length);
}
else {
ret = 0; // start off assuming they are equal
for (int ii = 0; ii < _hash.Length; ii++) {
ret = _hash[ii].CompareTo(otherb[ii]);
if (ret != 0) break;
}
}
}
}
return ret;
}
public override int GetHashCode()
{
ulong hashhash = this.MakeHashCode();
ulong upper = (hashhash >> 32 )& 0xffffffff;
ulong lower = hashhash & 0xffffffff;
return (int)(upper ^ lower);
}
public ulong MakeHashCode() {
ulong h = 5381;
for (int ii = 0; ii < _hash.Length; ii++) {
h = ((h << 5) + h) + (ulong)(_hash[ii]);
}
return h;
}
}
// ======================================================================
// ======================================================================
public abstract class BHasher : IBHasher
{
public BHasher() {
}
public abstract void Add(byte c);
public abstract void Add(ushort c);
public abstract void Add(uint c);
public abstract void Add(ulong c);
public abstract void Add(float c);
public abstract void Add(byte[] c, int offset, int len);
public abstract void Add(string c);
public abstract void Add(BHash c);
public abstract BHash Finish();
public abstract BHash Finish(byte[] c);
public abstract BHash Finish(byte[] c, int offset, int len);
public abstract BHash Hash();
}
// A hasher that builds up a buffer of bytes ('building') and then hashes over same
public abstract class BHasherBytes : BHasher {
protected byte[] building;
protected int buildingLoc;
protected int allocStep = 1024;
public BHasherBytes() : base() {
building = new byte[allocStep];
buildingLoc = 0;
}
private byte[] oneByte = new byte[1];
public override void Add(byte c) {
oneByte[0] = c;
AddBytes(oneByte, 0, 1);
}
public override void Add(ushort c) {
byte[] bytes = BitConverter.GetBytes(c);
AddBytes(bytes, 0, bytes.Length);
}
public override void Add(uint c) {
byte[] bytes = BitConverter.GetBytes(c);
AddBytes(bytes, 0, bytes.Length);
}
public override void Add(ulong c) {
byte[] bytes = BitConverter.GetBytes(c);
AddBytes(bytes, 0, bytes.Length);
}
public override void Add(float c) {
byte[] bytes = BitConverter.GetBytes(c);
AddBytes(bytes, 0, bytes.Length);
}
public override void Add(byte[] c, int offset, int len) {
AddBytes(c, offset, len);
}
public override void Add(string c)
{
byte[] bytes = Encoding.UTF8.GetBytes(c);
AddBytes(bytes, 0, bytes.Length);
}
public override void Add(BHash c) {
byte[] bytes = c.ToBytes();
AddBytes(bytes, 0, bytes.Length);
}
// Implemented by derived class
// public abstract BHash Finish();
// Helper function for simple byte array
public override BHash Finish(byte[] c) {
return this.Finish(c, 0, c.Length);
}
// Implemented by derived class
// public abstract BHash Finish(byte[] c, int offset, int len);
// Implemented by derived class
// public abstract BHash Hash();
// Add the given number of bytes to the byte array being built
protected void AddBytes(byte[] addition, int offset, int len) {
// byte[] tempBytes = new byte[len]; // DEBUG DEBUG
// Array.Copy(addition, offset, tempBytes, 0, len); // DEBUG DEBUG
// System.Console.WriteLine(String.Format("AddBytes: offset={0}, len={1}, bytes={2}", // DEBUG DEBUG
// offset, len, BitConverter.ToString(tempBytes).Replace("-", String.Empty))); // DEBUG DEBUG
if (len < 0 || offset < 0 || addition == null) {
throw new ArgumentException(String.Format("BHasherBytes.AddBytes: Bad parameters. offset={0}, len={1}",
offset, len));
}
if (offset + len > addition.Length) {
throw new ArgumentException(String.Format("BHasherBytes.AddBytes: addition parameters off end of array. addition.len={0}, offset={1}, len={2}",
addition.Length, offset, len));
}
if (len > 0) {
if (buildingLoc + len > building.Length) {
// New data requires expanding the data buffer
byte[] newBuilding = new byte[buildingLoc + len + allocStep];
Buffer.BlockCopy(building, 0, newBuilding, 0, buildingLoc);
building = newBuilding;
}
Buffer.BlockCopy(addition, offset, building, buildingLoc, len);
buildingLoc += len;
}
}
}
// ======================================================================
// ULong hash code taken from Meshmerizer
public class BHasherMdjb2 : BHasherBytes, IBHasher {
BHashULong hash = new BHashULong();
public BHasherMdjb2() : base() {
}
public override BHash Finish() {
hash = new BHashULong(ComputeMdjb2Hash(building, 0, buildingLoc));
return hash;
}
public override BHash Finish(byte[] c, int offset, int len) {
if (building.Length > 0) {
AddBytes(c, offset, len);
hash = new BHashULong(ComputeMdjb2Hash(building, 0, buildingLoc));
}
else {
// if no 'Add's were done, don't copy the input data
hash = new BHashULong(ComputeMdjb2Hash(c, offset, len));
}
return hash;
}
private ulong ComputeMdjb2Hash(byte[] c, int offset, int len) {
ulong h = 5381;
for (int ii = offset; ii < offset+len; ii++) {
h = ((h << 5) + h) + (ulong)(c[ii]);
}
return h;
}
public override BHash Hash() {
return hash;
}
}
// ======================================================================
public class BHasherMD5 : BHasherBytes, IBHasher {
BHashBytes hash = new BHashBytes();
public BHasherMD5() : base() {
}
public override BHash Finish() {
MD5 md5 = MD5.Create();
hash = new BHashBytes(md5.ComputeHash(building, 0, buildingLoc));
return hash;
}
public override BHash Finish(byte[] c) {
return this.Finish(c, 0, c.Length);
}
public override BHash Finish(byte[] c, int offset, int len) {
MD5 md5 = MD5.Create();
if (building.Length > 0) {
AddBytes(c, offset, len);
hash = new BHashBytes(md5.ComputeHash(building, 0, buildingLoc));
}
else {
// if no 'Add's were done, don't copy the input data
hash = new BHashBytes(md5.ComputeHash(c, offset, len));
}
return hash;
}
public override BHash Hash() {
return hash;
}
}
// ======================================================================
public class BHasherSHA256 : BHasherBytes, IBHasher {
BHashBytes hash = new BHashBytes();
public BHasherSHA256() : base() {
}
public override BHash Finish() {
using (SHA256 SHA256 = SHA256.Create()) {
hash = new BHashBytes(SHA256.ComputeHash(building, 0, buildingLoc));
}
return hash;
}
public override BHash Finish(byte[] c) {
return this.Finish(c, 0, c.Length);
}
public override BHash Finish(byte[] c, int offset, int len) {
using (SHA256 SHA256 = SHA256.Create()) {
if (buildingLoc > 0) {
AddBytes(c, offset, len);
hash = new BHashBytes(SHA256.ComputeHash(building, 0, buildingLoc));
}
else {
// if no 'Add's were done, don't copy the input data
hash = new BHashBytes(SHA256.ComputeHash(c, offset, len));
}
}
return hash;
}
public override BHash Hash() {
return hash;
}
}
}

View File

@@ -1,251 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using log4net;
namespace osWebRtcVoice
{
// Encapsulization of a Session to the Janus server
public class JanusAudioBridge : JanusPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[JANUS AUDIO BRIDGE]";
// Wrapper around the session connection to Janus-gateway
public JanusAudioBridge(JanusSession pSession) : base(pSession, "janus.plugin.audiobridge")
{
// m_log.DebugFormat("{0} JanusAudioBridge constructor", LogHeader);
}
public override void Dispose()
{
if (IsConnected)
{
// Close the handle
}
base.Dispose();
}
public async Task<AudioBridgeResp> SendAudioBridgeMsg(PluginMsgReq pMsg)
{
AudioBridgeResp ret = null;
try
{
ret = new AudioBridgeResp(await SendPluginMsg(pMsg));
}
catch (Exception e)
{
m_log.ErrorFormat("{0} SendPluginMsg. Exception {1}", LogHeader, e);
}
return ret;
}
/// <summary>
/// Create a room with the given criteria. This talks to Janus to create the room.
/// If the room with this RoomId already exists, just return it.
/// Janus could create and return the RoomId but this presumes that the Janus server
/// is only being used for our voice service.
/// </summary>
/// <param name="pRoomId">integer room ID to create</param>
/// <param name="pSpatial">boolean on whether room will be spatial or non-spatial</param>
/// <param name="pRoomDesc">added as "description" to the created room</param>
/// <returns></returns>
public async Task<JanusRoom> CreateRoom(int pRoomId, bool pSpatial, string pRoomDesc)
{
JanusRoom ret = null;
try
{
JanusMessageResp resp = await SendPluginMsg(new AudioBridgeCreateRoomReq(pRoomId, pSpatial, pRoomDesc));
AudioBridgeResp abResp = new AudioBridgeResp(resp);
m_log.DebugFormat("{0} CreateRoom. ReturnCode: {1}", LogHeader, abResp.AudioBridgeReturnCode);
switch (abResp.AudioBridgeReturnCode)
{
case "created":
ret = new JanusRoom(this, pRoomId);
break;
case "event":
if (abResp.AudioBridgeErrorCode == 486)
{
m_log.WarnFormat("{0} CreateRoom. Room {1} already exists. Reusing! {2}", LogHeader, pRoomId, abResp.ToString());
// if room already exists, just use it
ret = new JanusRoom(this, pRoomId);
}
else
{
m_log.ErrorFormat("{0} CreateRoom. XX Room creation failed: {1}", LogHeader, abResp.ToString());
}
break;
default:
m_log.ErrorFormat("{0} CreateRoom. YY Room creation failed: {1}", LogHeader, abResp.ToString());
break;
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} CreateRoom. Exception {1}", LogHeader, e);
}
return ret;
}
public async Task<bool> DestroyRoom(JanusRoom janusRoom)
{
bool ret = false;
try
{
JanusMessageResp resp = await SendPluginMsg(new AudioBridgeDestroyRoomReq(janusRoom.RoomId));
ret = true;
}
catch (Exception e)
{
m_log.ErrorFormat("{0} DestroyRoom. Exception {1}", LogHeader, e);
}
return ret;
}
// Constant used to denote that this is a spatial audio room for the region (as opposed to parcels)
public const int REGION_ROOM_ID = -999;
private Dictionary<int, JanusRoom> _rooms = new Dictionary<int, JanusRoom>();
// Calculate a room number for the given parameters. The room number is a hash of the parameters.
// The attempt is to deterministicly create a room number so all regions will generate the
// same room number across sessions and across the grid.
// getHashCode() is not deterministic across sessions.
public static int CalcRoomNumber(string pRegionId, string pChannelType, int pParcelLocalID, string pChannelID)
{
var hasher = new BHasherMdjb2();
// If there is a channel specified it must be group
switch (pChannelType)
{
case "local":
// A "local" channel is unique to the region and parcel
hasher.Add(pRegionId);
hasher.Add(pChannelType);
hasher.Add(pParcelLocalID);
break;
case "multiagent":
// A "multiagent" channel is unique to the grid
// should add a GridId here
hasher.Add(pChannelID);
hasher.Add(pChannelType);
break;
default:
throw new Exception("Unknown channel type: " + pChannelType);
}
var hashed = hasher.Finish();
// The "Abs()" is because Janus room number must be a positive integer
// And note that this is the BHash.GetHashCode() and not Object.getHashCode().
int roomNumber = Math.Abs(hashed.GetHashCode());
return roomNumber;
}
public async Task<JanusRoom> SelectRoom(string pRegionId, string pChannelType, bool pSpatial, int pParcelLocalID, string pChannelID)
{
int roomNumber = CalcRoomNumber(pRegionId, pChannelType, pParcelLocalID, pChannelID);
// Should be unique for the given use and channel type
m_log.DebugFormat("{0} SelectRoom: roomNumber={1}", LogHeader, roomNumber);
// Check to see if the room has already been created
lock (_rooms)
{
if (_rooms.ContainsKey(roomNumber))
{
return _rooms[roomNumber];
}
}
// The room doesn't exist. Create it.
string roomDesc = pRegionId + "/" + pChannelType + "/" + pParcelLocalID + "/" + pChannelID;
JanusRoom ret = await CreateRoom(roomNumber, pSpatial, roomDesc);
JanusRoom existingRoom = null;
if (ret is not null)
{
lock (_rooms)
{
if (_rooms.ContainsKey(roomNumber))
{
// If the room was created while we were waiting,
existingRoom = _rooms[roomNumber];
}
else
{
// Our room is the first one created. Save it.
_rooms[roomNumber] = ret;
}
}
}
if (existingRoom is not null)
{
// The room we created was already created by someone else. Delete ours and use the existing one
await DestroyRoom(ret);
ret = existingRoom;
}
return ret;
}
// Return the room with the given room ID or 'null' if no such room
public JanusRoom GetRoom(int pRoomId)
{
JanusRoom ret = null;
lock (_rooms)
{
_rooms.TryGetValue(pRoomId, out ret);
}
return ret;
}
public override void Handle_Event(JanusMessageResp pResp)
{
base.Handle_Event(pResp);
AudioBridgeResp abResp = new AudioBridgeResp(pResp);
if (abResp is not null && abResp.AudioBridgeReturnCode == "event")
{
// An audio bridge event!
m_log.DebugFormat("{0} Handle_Event. {1}", LogHeader, abResp.ToString());
}
}
public override void Handle_Message(JanusMessageResp pResp)
{
base.Handle_Message(pResp);
AudioBridgeResp abResp = new AudioBridgeResp(pResp);
if (abResp is not null && abResp.AudioBridgeReturnCode == "event")
{
// An audio bridge event!
m_log.DebugFormat("{0} Handle_Event. {1}", LogHeader, abResp.ToString());
}
}
}
}

View File

@@ -1,639 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using OpenMetaverse.StructuredData;
using OpenMetaverse;
using log4net;
namespace osWebRtcVoice
{
/// <summary>
/// Wrappers around the Janus requests and responses.
/// Since the messages are JSON and, because of the libraries we are using,
/// the internal structure is an OSDMap, these routines hold all the logic
/// to getting and setting the values in the JSON.
/// </summary>
public class JanusMessage
{
protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected static readonly string LogHeader = "[JANUS MESSAGE]";
protected OSDMap m_message = new OSDMap();
public JanusMessage()
{
}
// A basic Janus message is:
// {
// "janus": "operation",
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea",
// "session_id": 5645225333294848, // optional, gives the session ID
// "handle_id": 6969906757968657 // optional, gives the plugin handle ID
// "sender": 6969906757968657 // optional, gives the ID of the sending subsystem
// "jsep": { "type": "offer", "sdp": "..." } // optional, gives the SDP
// }
public JanusMessage(string pType) : this()
{
m_message["janus"] = pType;
m_message["transaction"] = UUID.Random().ToString();
}
public OSDMap RawBody => m_message;
public string TransactionId {
get { return m_message.TryGetString("transaction", out string tid) ? tid : null; }
set { m_message["transaction"] = value; }
}
public string Sender {
get { return m_message.TryGetString("sender", out string tid) ? tid : null; }
set { m_message["sender"] = value; }
}
public OSDMap Jsep {
get { return m_message.TryGetOSDMap("jsep", out OSDMap jsep) ? jsep : null; }
set { m_message["jsep"] = value; }
}
public void SetJsep(string pOffer, string pSdp)
{
m_message["jsep"] = new OSDMap()
{
{ "type", pOffer },
{ "sdp", pSdp }
};
}
public void AddAPIToken(string pToken)
{
m_message["apisecret"] = pToken;
}
// Note that the session_id is a long number in the JSON so we convert the string.
public string sessionId {
get { return m_message.TryGetValue("session_id", out OSD tmposd) ? OSDToLong(tmposd).ToString() : string.Empty; }
set { m_message["session_id"] = long.Parse(value); }
}
public bool hasSessionId { get { return m_message.ContainsKey("session_id"); } }
public void AddSessionId(string pToken)
{
AddSessionId(long.Parse(pToken));
}
public void AddSessionId(long pToken)
{
m_message["session_id"] = pToken;
}
public bool hasHandleId { get { return m_message.ContainsKey("handle_id"); } }
public void AddHandleId(string pToken)
{
m_message["handle_id"] = long.Parse(pToken);
}
public string sender
{
get { return m_message.TryGetString("sender", out string str) ? str : string.Empty; }
}
public virtual string ToJson()
{
return m_message.ToString();
}
public override string ToString()
{
return m_message.ToString();
}
// Utility function to convert an OSD object to an long. The OSD object can be an OSDInteger
// or an OSDArray of 4 or 8 integers.
// This exists because the JSON to OSD parser can return an OSDArray for a long number
// since there is not an OSDLong type.
// The design of the OSD conversion functions kinda needs one to know how the number
// is stored in order to extract it. Like, if it's stored as a long value (8 bytes)
// and one fetches it with .AsInteger(), it will return the first 4 bytes as an integer
// and not the long value. So this function looks at the type of the OSD object and
// extracts the number appropriately.
public static long OSDToLong(OSD pIn)
{
long ret = 0;
switch (pIn.Type)
{
case OSDType.Integer:
ret = (long)(pIn as OSDInteger).AsInteger();
break;
case OSDType.Binary:
byte[] value = (pIn as OSDBinary).value;
if (value.Length == 4)
{
ret = (long)(pIn as OSDBinary).AsInteger();
}
if (value.Length == 8)
{
ret = (pIn as OSDBinary).AsLong();
}
break;
case OSDType.Array:
if ((pIn as OSDArray).Count == 4)
{
ret = (long)pIn.AsInteger();
}
if ((pIn as OSDArray).Count == 8)
{
ret = pIn.AsLong();
}
break;
}
return ret;
}
}
// ==============================================================
// A Janus request message is a basic Janus message with an API token
public class JanusMessageReq : JanusMessage
{
public JanusMessageReq(string pType) : base(pType)
{
}
}
// ==============================================================
// Janus message response is a basic Janus message with the response data
// {
// "janus": "success",
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea", // ID of the requesting message
// "data": { ... } // the response data
// "error": { "code": 123, "reason": "..." } // if there was an error
// }
// The "janus" return code changes depending on the request. The above is for
// a successful response. Could be
// "event": for an event message (See JanusEventResp)
// "keepalive": for a keepalive event
public class JanusMessageResp : JanusMessage
{
public JanusMessageResp() : base()
{
}
public JanusMessageResp(string pType) : base(pType)
{
}
public JanusMessageResp(OSDMap pMap) : base()
{
m_message = pMap;
}
public static JanusMessageResp FromJson(string pJson)
{
var newBody = OSDParser.DeserializeJson(pJson) as OSDMap;
return new JanusMessageResp(newBody);
}
// Return the "data" portion of the response as an OSDMap or null if there is none
public OSDMap dataSection { get { return m_message.TryGetOSDMap("data", out OSDMap osdm) ? osdm : null; } }
// Check if a successful response code is in the response
public virtual bool isSuccess { get { return CheckReturnCode("success"); } }
public virtual bool isEvent { get { return CheckReturnCode("event"); } }
public virtual bool isError { get { return CheckReturnCode("error"); } }
public virtual bool CheckReturnCode(string pCode)
{
return ReturnCode == pCode;
}
public virtual string ReturnCode { get {
string ret = String.Empty;
if (m_message is not null && m_message.ContainsKey("janus"))
{
ret = m_message["janus"].AsString();
}
return ret;
} }
}
// ==============================================================
// An error response is a Janus response with an error code and reason.
// {
// "janus": "error",
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea", // ID of the requesting message
// "error": { "code": 123, "reason": "..." } // if there was an error
// }
public class ErrorResp : JanusMessageResp
{
public ErrorResp() : base("error")
{
}
public ErrorResp(string pType) : base(pType)
{
}
public ErrorResp(JanusMessageResp pResp) : base(pResp.RawBody)
{
}
public void SetError(int pCode, string pReason)
{
m_message["error"] = new OSDMap()
{
{ "code", pCode },
{ "reason", pReason }
};
}
// Dig through the response to get the error code or 0 if there is none
public int errorCode { get {
int ret = 0;
if (m_message.ContainsKey("error"))
{
var err = m_message["error"];
if (err is OSDMap)
ret = (int)OSDToLong((err as OSDMap)["code"]);
}
return ret;
}}
// Dig through the response to get the error reason or empty string if there is none
public string errorReason { get {
string ret = String.Empty;
if (m_message.ContainsKey("error"))
{
var err = m_message["error"];
if (err is OSDMap)
ret = (err as OSDMap)["reason"];
}
// return ((m_message["error"] as OSDMap)?["reason"]) ?? String.Empty;
return ret;
}}
}
// ==============================================================
// Create session request and response
public class CreateSessionReq : JanusMessageReq
{
public CreateSessionReq() : base("create")
{
}
}
public class CreateSessionResp : JanusMessageResp
{
public CreateSessionResp(JanusMessageResp pResp) : base(pResp.RawBody)
{ }
public string returnedId { get {
// The JSON response gives a long number (not a string)
// and the ODMap conversion interprets it as a long (OSDLong).
// If one just does a "ToString()" on the OSD object, you
// get an interpretation of the binary value.
return dataSection.ContainsKey("id") ? OSDToLong(dataSection["id"]).ToString() : String.Empty;
}}
}
// ==============================================================
public class DestroySessionReq : JanusMessageReq
{
public DestroySessionReq() : base("destroy")
{
// Doesn't include the session ID because it is the URI
}
}
// ==============================================================
public class TrickleReq : JanusMessageReq
{
// An empty trickle request is used to signal the end of the trickle
public TrickleReq(JanusViewerSession pVSession) : base("trickle")
{
m_message["candidate"] = new OSDMap()
{
{ "completed", true },
};
}
public TrickleReq(JanusViewerSession pVSession, OSD pCandidates) : base("trickle")
{
m_message["viewer_session"] = pVSession.ViewerSessionID;
if (pCandidates is OSDArray)
m_message["candidates"] = pCandidates;
else
m_message["candidate"] = pCandidates;
}
}
// ==============================================================
public class AttachPluginReq : JanusMessageReq
{
public AttachPluginReq(string pPlugin) : base("attach")
{
m_message["plugin"] = pPlugin;
}
}
public class AttachPluginResp : JanusMessageResp
{
public AttachPluginResp(JanusMessageResp pResp) : base(pResp.RawBody)
{ }
public string pluginId { get {
return dataSection.ContainsKey("id") ? OSDToLong(dataSection["id"]).ToString() : String.Empty;
}}
}
// ==============================================================
public class DetachPluginReq : JanusMessageReq
{
public DetachPluginReq() : base("detach")
{
// Doesn't include the session ID or plugin ID because it is the URI
}
}
// ==============================================================
public class HangupReq : JanusMessageReq
{
public HangupReq() : base("hangup")
{
// Doesn't include the session ID or plugin ID because it is the URI
}
}
// ==============================================================
// Plugin messages are defined here as wrappers around OSDMap.
// The ToJson() method is overridden to put the OSDMap into the
// message body.
// A plugin request is formatted like:
// {
// "janus": "message",
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea",
// "body": {
// "request": "create",
// "room": 10,
// "is_private": false,
// }
public class PluginMsgReq : JanusMessageReq
{
private OSDMap m_body = new OSDMap();
// Note that the passed OSDMap is placed in the "body" section of the message
public PluginMsgReq(OSDMap pBody) : base("message")
{
m_body = pBody;
}
public void AddStringToBody(string pKey, string pValue)
{
m_body[pKey] = pValue;
}
public void AddIntToBody(string pKey, int pValue)
{
m_body[pKey] = pValue;
}
public void AddBoolToBody(string pKey, bool pValue)
{
m_body[pKey] = pValue;
}
public void AddOSDToBody(string pKey, OSD pValue)
{
m_body[pKey] = pValue;
}
public override string ToJson()
{
m_message["body"] = m_body;
return base.ToJson();
}
}
// A plugin response is formatted like:
// {
// "janus": "success",
// "session_id": 5645225333294848,
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea",
// "sender": 6969906757968657,
// "plugindata": {
// "plugin": "janus.plugin.audiobridge",
// "data": {
// "audiobridge": "created",
// "room": 10,
// "permanent": false
// }
// }
public class PluginMsgResp : JanusMessageResp
{
public OSDMap m_pluginData;
public OSDMap m_data;
public PluginMsgResp(JanusMessageResp pResp) : base(pResp.RawBody)
{
if (m_message is not null && m_message.ContainsKey("plugindata"))
{
// Move the plugin data up into the m_data var so it is easier to get to
m_pluginData = m_message["plugindata"] as OSDMap;
if (m_pluginData is not null && m_pluginData.ContainsKey("data"))
{
m_data = m_pluginData["data"] as OSDMap;
// m_log.DebugFormat("{0} AudioBridgeResp. Found both plugindata and data: data={1}", LogHeader, m_data.ToString());
}
}
}
public OSDMap PluginRespData { get { return m_data; } }
// Get an integer value for a key in the response data or zero if not there
public int PluginRespDataInt(string pKey)
{
if (m_data is null)
return 0;
return m_data.ContainsKey(pKey) ? (int)OSDToLong(m_data[pKey]) : 0;
}
// Get a string value for a key in the response data or empty string if not there
public string PluginRespDataString(string pKey)
{
if (m_data is null)
return String.Empty;
return m_data.ContainsKey(pKey) ? m_data[pKey].AsString() : String.Empty;
}
}
// ==============================================================
// Plugin messages for the audio bridge.
// Audiobridge responses are formatted like:
// {
// "janus": "success",
// "session_id": 5645225333294848,
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea",
// "sender": 6969906757968657,
// "plugindata": {
// "plugin": "janus.plugin.audiobridge",
// "data": {
// "audiobridge": "created",
// "room": 10,
// "permanent": false
// }
// }
public class AudioBridgeResp: PluginMsgResp
{
public AudioBridgeResp(JanusMessageResp pResp) : base(pResp)
{
}
public override bool isSuccess { get { return PluginRespDataString("audiobridge") == "success"; } }
// Return the return code if it is in the response or empty string if not
public string AudioBridgeReturnCode { get { return PluginRespDataString("audiobridge"); } }
// Return the error code if it is in the response or zero if not
public int AudioBridgeErrorCode { get { return PluginRespDataInt("error_code"); } }
// Return the room ID if it is in the response or zero if not
public int RoomId { get { return PluginRespDataInt("room"); } }
}
// ==============================================================
public class AudioBridgeCreateRoomReq : PluginMsgReq
{
public AudioBridgeCreateRoomReq(int pRoomId) : this(pRoomId, false, null)
{
}
public AudioBridgeCreateRoomReq(int pRoomId, bool pSpatial, string pDesc) : base(new OSDMap() {
{ "room", pRoomId },
{ "request", "create" },
{ "is_private", false },
{ "permanent", false },
{ "sampling_rate", 48000 },
{ "spatial_audio", pSpatial },
{ "denoise", false },
{ "record", false }
})
{
if (!String.IsNullOrEmpty(pDesc))
AddStringToBody("description", pDesc);
}
}
// ==============================================================
public class AudioBridgeDestroyRoomReq : PluginMsgReq
{
public AudioBridgeDestroyRoomReq(int pRoomId) : base(new OSDMap() {
{ "request", "destroy" },
{ "room", pRoomId },
{ "permanent", true }
})
{
}
}
// ==============================================================
public class AudioBridgeJoinRoomReq : PluginMsgReq
{
public AudioBridgeJoinRoomReq(int pRoomId, string pAgentName) : base(new OSDMap() {
{ "request", "join" },
{ "room", pRoomId },
{ "display", pAgentName }
})
{
}
}
// A successful response contains the participant ID and the SDP
public class AudioBridgeJoinRoomResp : AudioBridgeResp
{
public AudioBridgeJoinRoomResp(JanusMessageResp pResp) : base(pResp)
{
}
public int ParticipantId { get { return PluginRespDataInt("id"); } }
}
// ==============================================================
public class AudioBridgeConfigRoomReq : PluginMsgReq
{
// TODO:
public AudioBridgeConfigRoomReq(int pRoomId, string pSdp) : base(new OSDMap() {
{ "request", "configure" },
})
{
}
}
public class AudioBridgeConfigRoomResp : AudioBridgeResp
{
// TODO:
public AudioBridgeConfigRoomResp(JanusMessageResp pResp) : base(pResp)
{
}
}
// ==============================================================
public class AudioBridgeLeaveRoomReq : PluginMsgReq
{
public AudioBridgeLeaveRoomReq(int pRoomId, int pAttendeeId) : base(new OSDMap() {
{ "request", "leave" },
{ "room", pRoomId },
{ "id", pAttendeeId }
})
{
}
}
// ==============================================================
public class AudioBridgeListRoomsReq : PluginMsgReq
{
public AudioBridgeListRoomsReq() : base(new OSDMap() {
{ "request", "list" }
})
{
}
}
// ==============================================================
public class AudioBridgeListParticipantsReq : PluginMsgReq
{
public AudioBridgeListParticipantsReq(int pRoom) : base(new OSDMap() {
{ "request", "listparticipants" },
{ "room", pRoom }
})
{
}
}
// ==============================================================
public class AudioBridgeEvent : AudioBridgeResp
{
public AudioBridgeEvent(JanusMessageResp pResp) : base(pResp)
{
}
}
// ==============================================================
// The LongPoll request returns events from the plugins. These are formatted
// like the other responses but are not responses to requests.
// They are formatted like:
// {
// "janus": "event",
// "sender": 6969906757968657,
// "transaction": "baefcec8-70c5-4e79-b2c1-d653b9617dea",
// "plugindata": {
// "plugin": "janus.plugin.audiobridge",
// "data": {
// "audiobridge": "event",
// "room": 10,
// "participants": 1,
// "participants": [
// {
// "id": 1234,
// "display": "John Doe",
// "audio_level": 0.0,
// "video_room": false,
// "video_muted": false,
// "audio_muted": false,
// "feed": 1234
// }
// ]
// }
// }
public class EventResp : JanusMessageResp
{
public EventResp() : base()
{
}
public EventResp(string pType) : base(pType)
{
}
public EventResp(JanusMessageResp pResp) : base(pResp.RawBody)
{
}
}
// ==============================================================
}

View File

@@ -1,161 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Threading.Tasks;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Base;
using OpenMetaverse.StructuredData;
using OpenMetaverse;
using Nini.Config;
using log4net;
namespace osWebRtcVoice
{
// Encapsulization of a Session to the Janus server
public class JanusPlugin : IDisposable
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[JANUS PLUGIN]";
protected IConfigSource _Config;
protected JanusSession _JanusSession;
public string PluginName { get; private set; }
public string PluginId { get; private set; }
public string PluginUri { get ; private set ; }
public bool IsConnected => !String.IsNullOrEmpty(PluginId);
// Wrapper around the session connection to Janus-gateway
public JanusPlugin(JanusSession pSession, string pPluginName)
{
_JanusSession = pSession;
PluginName = pPluginName;
}
public virtual void Dispose()
{
if (IsConnected)
{
// Close the handle
}
}
public Task<JanusMessageResp> SendPluginMsg(OSDMap pParams)
{
return _JanusSession.SendToJanus(new PluginMsgReq(pParams), PluginUri);
}
public Task<JanusMessageResp> SendPluginMsg(PluginMsgReq pJMsg)
{
return _JanusSession.SendToJanus(pJMsg, PluginUri);
}
/// <summary>
/// Make the create a handle to a plugin within the session.
/// </summary>
/// <returns>TRUE if handle was created successfully</returns>
public async Task<bool> Activate(IConfigSource pConfig)
{
_Config = pConfig;
bool ret = false;
try
{
var resp = await _JanusSession.SendToSession(new AttachPluginReq(PluginName));
if (resp is not null && resp.isSuccess)
{
var handleResp = new AttachPluginResp(resp);
PluginId = handleResp.pluginId;
PluginUri = _JanusSession.SessionUri + "/" + PluginId;
m_log.DebugFormat("{0} Activate. Plugin attached. ID={1}, URL={2}", LogHeader, PluginId, PluginUri);
_JanusSession.PluginId = PluginId;
_JanusSession.OnEvent += Handle_Event;
_JanusSession.OnMessage += Handle_Message;
ret = true;
}
else
{
m_log.ErrorFormat("{0} Activate: failed to attach to plugin {1}", LogHeader, PluginName);
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Activate: exception attaching to plugin {1}: {2}", LogHeader, PluginName, e);
}
return ret;
}
public virtual async Task<bool> Detach()
{
bool ret = false;
if (!IsConnected || _JanusSession is null)
{
m_log.WarnFormat("{0} Detach. Not connected", LogHeader);
return ret;
}
try
{
_JanusSession.OnEvent -= Handle_Event;
_JanusSession.OnMessage -= Handle_Message;
// We send the 'detach' message to the plugin URI
var resp = await _JanusSession.SendToJanus(new DetachPluginReq(), PluginUri);
if (resp is not null && resp.isSuccess)
{
m_log.DebugFormat("{0} Detach. Detached", LogHeader);
ret = true;
}
else
{
m_log.ErrorFormat("{0} Detach: failed", LogHeader);
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Detach: exception {1}", LogHeader, e);
}
return ret;
}
public virtual void Handle_Event(JanusMessageResp pResp)
{
m_log.DebugFormat("{0} Handle_Event: {1}", LogHeader, pResp.ToString());
}
public virtual void Handle_Message(JanusMessageResp pResp)
{
m_log.DebugFormat("{0} Handle_Message: {1}", LogHeader, pResp.ToString());
}
}
}

View File

@@ -1,138 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Base;
using OpenMetaverse.StructuredData;
using OpenMetaverse;
using Nini.Config;
using log4net;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace osWebRtcVoice
{
// Encapsulization of a Session to the Janus server
public class JanusRoom : IDisposable
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[JANUS ROOM]";
public int RoomId { get; private set; }
private JanusPlugin _AudioBridge;
// Wrapper around the session connection to Janus-gateway
public JanusRoom(JanusPlugin pAudioBridge, int pRoomId)
{
_AudioBridge = pAudioBridge;
RoomId = pRoomId;
}
public void Dispose()
{
// Close the room
}
public async Task<bool> JoinRoom(JanusViewerSession pVSession)
{
bool ret = false;
try
{
// m_log.DebugFormat("{0} JoinRoom. New joinReq for room {1}", LogHeader, RoomId);
// Discovered that AudioBridge doesn't care if the data portion is present
// and, if removed, the viewer complains that the "m=" sections are
// out of order. Not "cleaning" (removing the data section) seems to work.
// string cleanSdp = CleanupSdp(pSdp);
var joinReq = new AudioBridgeJoinRoomReq(RoomId, pVSession.AgentId.ToString());
// joinReq.SetJsep("offer", cleanSdp);
joinReq.SetJsep("offer", pVSession.Offer);
JanusMessageResp resp = await _AudioBridge.SendPluginMsg(joinReq);
AudioBridgeJoinRoomResp joinResp = new AudioBridgeJoinRoomResp(resp);
if (joinResp is not null && joinResp.AudioBridgeReturnCode == "joined")
{
pVSession.ParticipantId = joinResp.ParticipantId;
pVSession.Answer = joinResp.Jsep;
ret = true;
m_log.DebugFormat("{0} JoinRoom. Joined room {1}. Participant={2}", LogHeader, RoomId, pVSession.ParticipantId);
}
else
{
m_log.ErrorFormat("{0} JoinRoom. Failed to join room {1}. Resp={2}", LogHeader, RoomId, joinResp.ToString());
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} JoinRoom. Exception {1}", LogHeader, e);
}
return ret;
}
// TODO: this doesn't work.
// Not sure if it is needed. Janus generates Hangup events when the viewer leaves.
/*
public async Task<bool> Hangup(JanusViewerSession pAttendeeSession)
{
bool ret = false;
try
{
}
catch (Exception e)
{
m_log.ErrorFormat("{0} LeaveRoom. Exception {1}", LogHeader, e);
}
return ret;
}
*/
public async Task<bool> LeaveRoom(JanusViewerSession pAttendeeSession)
{
bool ret = false;
try
{
JanusMessageResp resp = await _AudioBridge.SendPluginMsg(
new AudioBridgeLeaveRoomReq(RoomId, pAttendeeSession.ParticipantId));
}
catch (Exception e)
{
m_log.ErrorFormat("{0} LeaveRoom. Exception {1}", LogHeader, e);
}
return ret;
}
}
}

View File

@@ -1,658 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Mime;
using System.Reflection;
using System.Threading.Tasks;
using OpenMetaverse.StructuredData;
using log4net;
using log4net.Core;
using System.Reflection.Metadata;
using System.Threading;
namespace osWebRtcVoice
{
// Encapsulization of a Session to the Janus server
public class JanusSession : IDisposable
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[JANUS SESSION]";
// Set to 'true' to get the messages send and received from Janus
private bool _MessageDetails = false;
private string _JanusServerURI = String.Empty;
private string _JanusAPIToken = String.Empty;
private string _JanusAdminURI = String.Empty;
private string _JanusAdminToken = String.Empty;
public string JanusServerURI => _JanusServerURI;
public string JanusAdminURI => _JanusAdminURI;
public string SessionId { get; private set; }
public string SessionUri { get ; private set ; }
public string PluginId { get; set; }
private CancellationTokenSource _CancelTokenSource = new CancellationTokenSource();
private HttpClient _HttpClient = new HttpClient();
public bool IsConnected { get; set; }
// Wrapper around the session connection to Janus-gateway
public JanusSession(string pServerURI, string pAPIToken, string pAdminURI, string pAdminToken, bool pDebugMessages = false)
{
m_log.DebugFormat("{0} JanusSession constructor", LogHeader);
_JanusServerURI = pServerURI;
_JanusAPIToken = pAPIToken;
_JanusAdminURI = pAdminURI;
_JanusAdminToken = pAdminToken;
_MessageDetails = pDebugMessages;
}
public void Dispose()
{
ClearEventSubscriptions();
if (IsConnected)
{
_ = DestroySession();
}
if (_HttpClient is not null)
{
_HttpClient.Dispose();
_HttpClient = null;
}
}
/// <summary>
/// Make the create session request to the Janus server, get the
/// sessionID and return TRUE if successful.
/// </summary>
/// <returns>TRUE if session was created successfully</returns>
public async Task<bool> CreateSession()
{
bool ret = false;
try
{
var resp = await SendToJanus(new CreateSessionReq());
if (resp is not null && resp.isSuccess)
{
var sessionResp = new CreateSessionResp(resp);
SessionId = sessionResp.returnedId;
IsConnected = true;
SessionUri = _JanusServerURI + "/" + SessionId;
m_log.DebugFormat("{0} CreateSession. Created. ID={1}, URL={2}", LogHeader, SessionId, SessionUri);
ret = true;
StartLongPoll();
}
else
{
m_log.ErrorFormat("{0} CreateSession: failed", LogHeader);
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} CreateSession: exception {1}", LogHeader, e);
}
return ret;
}
public async Task<bool> DestroySession()
{
bool ret = false;
try
{
JanusMessageResp resp = await SendToSession(new DestroySessionReq());
if (resp is not null && resp.isSuccess)
{
// Note that setting IsConnected to false will cause the long poll to exit
m_log.DebugFormat("{0} DestroySession. Destroyed", LogHeader);
}
else
{
if (resp.isError)
{
ErrorResp eResp = new ErrorResp(resp);
switch (eResp.errorCode)
{
case 458:
// This is the error code for a session that is already destroyed
m_log.DebugFormat("{0} DestroySession: session already destroyed", LogHeader);
break;
case 459:
// This is the error code for handle already destroyed
m_log.DebugFormat("{0} DestroySession: Handle not found", LogHeader);
break;
default:
m_log.ErrorFormat("{0} DestroySession: failed {1}", LogHeader, eResp.errorReason);
break;
}
}
else
{
m_log.ErrorFormat("{0} DestroySession: failed. Resp: {1}", LogHeader, resp.ToString());
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} DestroySession: exception {1}", LogHeader, e);
}
IsConnected = false;
_CancelTokenSource.Cancel();
return ret;
}
// ====================================================================
public async Task<JanusMessageResp> TrickleCandidates(JanusViewerSession pVSession, OSDArray pCandidates)
{
JanusMessageResp ret = null;
// if the audiobridge is active, the trickle message is sent to it
if (pVSession.AudioBridge is null)
{
ret = await SendToJanusNoWait(new TrickleReq(pVSession));
}
else
{
ret = await SendToJanusNoWait(new TrickleReq(pVSession), pVSession.AudioBridge.PluginUri);
}
return ret;
}
// ====================================================================
public async Task<JanusMessageResp> TrickleCompleted(JanusViewerSession pVSession)
{
JanusMessageResp ret = null;
// if the audiobridge is active, the trickle message is sent to it
if (pVSession.AudioBridge is null)
{
ret = await SendToJanusNoWait(new TrickleReq(pVSession));
}
else
{
ret = await SendToJanusNoWait(new TrickleReq(pVSession), pVSession.AudioBridge.PluginUri);
}
return ret;
}
// ====================================================================
public Dictionary<string, JanusPlugin> _Plugins = new Dictionary<string, JanusPlugin>();
public void AddPlugin(JanusPlugin pPlugin)
{
_Plugins.Add(pPlugin.PluginName, pPlugin);
}
// ====================================================================
// Post to the session
public async Task<JanusMessageResp> SendToSession(JanusMessageReq pReq)
{
return await SendToJanus(pReq, SessionUri);
}
private class OutstandingRequest
{
public string TransactionId;
public DateTime RequestTime;
public TaskCompletionSource<JanusMessageResp> TaskCompletionSource;
}
private Dictionary<string, OutstandingRequest> _OutstandingRequests = new Dictionary<string, OutstandingRequest>();
// Send a request directly to the Janus server.
// NOTE: this is probably NOT what you want to do. This is a direct call that is outside the session.
private async Task<JanusMessageResp> SendToJanus(JanusMessageReq pReq)
{
return await SendToJanus(pReq, _JanusServerURI);
}
/// <summary>
/// Send a request to the Janus server. This is the basic call that sends a request to the server.
/// The transaction ID is used to match the response to the request.
/// If the request returns an 'ack' response, the code waits for the matching event
/// before returning the response.
/// </summary>
/// <param name="pReq"></param>
/// <param name="pURI"></param>
/// <returns></returns>
public async Task<JanusMessageResp> SendToJanus(JanusMessageReq pReq, string pURI)
{
AddJanusHeaders(pReq);
// m_log.DebugFormat("{0} SendToJanus", LogHeader);
if (_MessageDetails) m_log.DebugFormat("{0} SendToJanus. URI={1}, req={2}", LogHeader, pURI, pReq.ToJson());
JanusMessageResp ret = null;
try
{
OutstandingRequest outReq = new OutstandingRequest
{
TransactionId = pReq.TransactionId,
RequestTime = DateTime.Now,
TaskCompletionSource = new TaskCompletionSource<JanusMessageResp>()
};
_OutstandingRequests.Add(pReq.TransactionId, outReq);
string reqStr = pReq.ToJson();
HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Post, pURI);
reqMsg.Content = new StringContent(reqStr, System.Text.Encoding.UTF8, MediaTypeNames.Application.Json);
reqMsg.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await _HttpClient.SendAsync(reqMsg, _CancelTokenSource.Token);
if (response.IsSuccessStatusCode)
{
string respStr = await response.Content.ReadAsStringAsync();
ret = JanusMessageResp.FromJson(respStr);
if (ret.CheckReturnCode("ack"))
{
// Some messages are asynchronous and completed with an event
if (_MessageDetails) m_log.DebugFormat("{0} SendToJanus: ack response {1}", LogHeader, respStr);
if (_OutstandingRequests.TryGetValue(pReq.TransactionId, out OutstandingRequest outstandingRequest))
{
ret = await outstandingRequest.TaskCompletionSource.Task;
_OutstandingRequests.Remove(pReq.TransactionId);
}
// If there is no OutstandingRequest, the request was not waiting for an event or already processed
}
else
{
// If the response is not an ack, that means a synchronous request/response so return the response
_OutstandingRequests.Remove(pReq.TransactionId);
if (_MessageDetails) m_log.DebugFormat("{0} SendToJanus: response {1}", LogHeader, respStr);
}
}
else
{
m_log.ErrorFormat("{0} SendToJanus: response not successful {1}", LogHeader, response);
_OutstandingRequests.Remove(pReq.TransactionId);
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} SendToJanus: exception {1}", LogHeader, e.Message);
}
return ret;
}
/// <summary>
/// Send a request to the Janus server but we just return the response and don't wait for any
/// event or anything.
/// There are some requests that are just fire-and-forget.
/// </summary>
/// <param name="pReq"></param>
/// <returns></returns>
private async Task<JanusMessageResp> SendToJanusNoWait(JanusMessageReq pReq, string pURI)
{
JanusMessageResp ret = new JanusMessageResp();
AddJanusHeaders(pReq);
try {
HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Post, pURI);
string reqStr = pReq.ToJson();
reqMsg.Content = new StringContent(reqStr, System.Text.Encoding.UTF8, MediaTypeNames.Application.Json);
reqMsg.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await _HttpClient.SendAsync(reqMsg);
string respStr = await response.Content.ReadAsStringAsync();
ret = JanusMessageResp.FromJson(respStr);
}
catch (Exception e)
{
m_log.ErrorFormat("{0} SendToJanusNoWait: exception {1}", LogHeader, e.Message);
}
return ret;
}
private async Task<JanusMessageResp> SendToJanusNoWait(JanusMessageReq pReq)
{
return await SendToJanusNoWait(pReq, SessionUri);
}
// There are various headers that are in most Janus requests. Add them here.
private void AddJanusHeaders(JanusMessageReq pReq)
{
// Authentication token
if (!String.IsNullOrEmpty(_JanusAPIToken))
{
pReq.AddAPIToken(_JanusAPIToken);
}
// Transaction ID that matches responses to requests
if (String.IsNullOrEmpty(pReq.TransactionId))
{
pReq.TransactionId = Guid.NewGuid().ToString();
}
// The following two are required for the WebSocket interface. They are optional for the
// HTTP interface since the session and plugin handle are in the URL.
// SessionId is added to the message if not already there
if (!pReq.hasSessionId && !String.IsNullOrEmpty(SessionId))
{
pReq.AddSessionId(SessionId);
}
// HandleId connects to the plugin
if (!pReq.hasHandleId && !String.IsNullOrEmpty(PluginId))
{
pReq.AddHandleId(PluginId);
}
}
bool TryGetOutstandingRequest(string pTransactionId, out OutstandingRequest pOutstandingRequest)
{
if (String.IsNullOrEmpty(pTransactionId))
{
pOutstandingRequest = null;
return false;
}
bool ret = false;
lock (_OutstandingRequests)
{
if (_OutstandingRequests.TryGetValue(pTransactionId, out pOutstandingRequest))
{
_OutstandingRequests.Remove(pTransactionId);
ret = true;
}
}
return ret;
}
public Task<JanusMessageResp> SendToJanusAdmin(JanusMessageReq pReq)
{
return SendToJanus(pReq, _JanusAdminURI);
}
public Task<JanusMessageResp> GetFromJanus()
{
return GetFromJanus(_JanusServerURI);
}
/// <summary>
/// Do a GET to the Janus server and return the response.
/// If the response is an HTTP error, we return fake JanusMessageResp with the error.
/// </summary>
/// <param name="pURI"></param>
/// <returns></returns>
public async Task<JanusMessageResp> GetFromJanus(string pURI)
{
if (!String.IsNullOrEmpty(_JanusAPIToken))
{
pURI += "?apisecret=" + _JanusAPIToken;
}
JanusMessageResp ret = null;
try
{
// m_log.DebugFormat("{0} GetFromJanus: URI = \"{1}\"", LogHeader, pURI);
HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Get, pURI);
reqMsg.Headers.Add("Accept", "application/json");
HttpResponseMessage response = null;
try
{
response = await _HttpClient.SendAsync(reqMsg, _CancelTokenSource.Token);
if (response is not null && response.IsSuccessStatusCode)
{
string respStr = await response.Content.ReadAsStringAsync();
ret = JanusMessageResp.FromJson(respStr);
// m_log.DebugFormat("{0} GetFromJanus: response {1}", LogHeader, respStr);
}
else
{
m_log.ErrorFormat("{0} GetFromJanus: response not successful {1}", LogHeader, response);
var eResp = new ErrorResp("GETERROR");
// Add the sessionId so the proper session can be shut down
eResp.AddSessionId(SessionId);
if (response is not null)
{
eResp.SetError((int)response.StatusCode, response.ReasonPhrase);
}
else
{
eResp.SetError(0, "Connection refused");
}
ret = eResp;
}
}
catch (TaskCanceledException e)
{
m_log.DebugFormat("{0} GetFromJanus: task canceled: {1}", LogHeader, e.Message);
var eResp = new ErrorResp("GETERROR");
eResp.SetError(499, "Task canceled");
ret = eResp;
}
catch (Exception e)
{
m_log.ErrorFormat("{0} GetFromJanus: exception {1}", LogHeader, e.Message);
var eResp = new ErrorResp("GETERROR");
eResp.SetError(400, "Exception: " + e.Message);
ret = eResp;
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} GetFromJanus: exception {1}", LogHeader, e);
var eResp = new ErrorResp("GETERROR");
eResp.SetError(400, "Exception: " + e.Message);
ret = eResp;
}
return ret;
}
// ====================================================================
public delegate void JanusEventHandler(EventResp pResp);
// Not all the events are used. CS0067 is to suppress the warning that the event is not used.
#pragma warning disable CS0067,CS0414
public event JanusEventHandler OnKeepAlive;
public event JanusEventHandler OnServerInfo;
public event JanusEventHandler OnTrickle;
public event JanusEventHandler OnHangup;
public event JanusEventHandler OnDetached;
public event JanusEventHandler OnError;
public event JanusEventHandler OnEvent;
public event JanusEventHandler OnMessage;
public event JanusEventHandler OnJoined;
public event JanusEventHandler OnLeaving;
public event JanusEventHandler OnDisconnect;
#pragma warning restore CS0067,CS0414
public void ClearEventSubscriptions()
{
OnKeepAlive = null;
OnServerInfo = null;
OnTrickle = null;
OnHangup = null;
OnDetached = null;
OnError = null;
OnEvent = null;
OnMessage = null;
OnJoined = null;
OnLeaving = null;
OnDisconnect = null;
}
// ====================================================================
/// <summary>
/// In the REST API, events are returned by a long poll. This
/// starts the poll and calls the registed event handler when
/// an event is received.
/// </summary>
private void StartLongPoll()
{
bool running = true;
m_log.DebugFormat("{0} EventLongPoll", LogHeader);
Task.Run(async () => {
while (running && IsConnected)
{
try
{
var resp = await GetFromJanus(SessionUri);
if (resp is not null)
{
_ = Task.Run(() =>
{
EventResp eventResp = new EventResp(resp);
switch (resp.ReturnCode)
{
case "keepalive":
// These should happen every 30 seconds
// m_log.DebugFormat("{0} EventLongPoll: keepalive {1}", LogHeader, resp.ToString());
break;
case "server_info":
// Just info on the Janus instance
m_log.DebugFormat("{0} EventLongPoll: server_info {1}", LogHeader, resp.ToString());
break;
case "ack":
// 'ack' says the request was received and an event will follow
if (_MessageDetails) m_log.DebugFormat("{0} EventLongPoll: ack {1}", LogHeader, resp.ToString());
break;
case "success":
// success is a sync response that says the request was completed
if (_MessageDetails) m_log.DebugFormat("{0} EventLongPoll: success {1}", LogHeader, resp.ToString());
break;
case "trickle":
// got a trickle ICE candidate from Janus
// this is for reverse communication from Janus to the client and we don't do that
if (_MessageDetails) m_log.DebugFormat("{0} EventLongPoll: trickle {1}", LogHeader, resp.ToString());
OnTrickle?.Invoke(eventResp);
break;
case "webrtcup":
// ICE and DTLS succeeded, and so Janus correctly established a PeerConnection with the user/application;
m_log.DebugFormat("{0} EventLongPoll: webrtcup {1}", LogHeader, resp.ToString());
break;
case "hangup":
// The PeerConnection was closed, either by the user/application or by Janus itself;
// If one is in the room, when a "hangup" event happens, it means that the user left the room.
m_log.DebugFormat("{0} EventLongPoll: hangup {1}", LogHeader, resp.ToString());
OnHangup?.Invoke(eventResp);
break;
case "detached":
// a plugin asked the core to detach one of our handles
m_log.DebugFormat("{0} EventLongPoll: event {1}", LogHeader, resp.ToString());
OnDetached?.Invoke(eventResp);
break;
case "media":
// Janus is receiving (receiving: true/false) audio/video (type: "audio/video") on this PeerConnection;
m_log.DebugFormat("{0} EventLongPoll: media {1}", LogHeader, resp.ToString());
break;
case "slowlink":
// Janus detected a slowlink (uplink: true/false) on this PeerConnection;
m_log.DebugFormat("{0} EventLongPoll: slowlink {1}", LogHeader, resp.ToString());
break;
case "error":
m_log.DebugFormat("{0} EventLongPoll: error {1}", LogHeader, resp.ToString());
if (TryGetOutstandingRequest(resp.TransactionId, out OutstandingRequest outstandingRequest))
{
outstandingRequest.TaskCompletionSource.SetResult(resp);
}
else
{
OnError?.Invoke(eventResp);
m_log.ErrorFormat("{0} EventLongPoll: error with no transaction. {1}", LogHeader, resp.ToString());
}
break;
case "event":
if (_MessageDetails) m_log.DebugFormat("{0} EventLongPoll: event {1}", LogHeader, resp.ToString());
if (TryGetOutstandingRequest(resp.TransactionId, out OutstandingRequest outstandingRequest2))
{
// Someone is waiting for this event
outstandingRequest2.TaskCompletionSource.SetResult(resp);
}
else
{
m_log.ErrorFormat("{0} EventLongPoll: event no outstanding request {1}", LogHeader, resp.ToString());
OnEvent?.Invoke(eventResp);
}
break;
case "message":
m_log.DebugFormat("{0} EventLongPoll: message {1}", LogHeader, resp.ToString());
OnMessage?.Invoke(eventResp);
break;
case "timeout":
// Events for the audio bridge
m_log.DebugFormat("{0} EventLongPoll: timeout {1}", LogHeader, resp.ToString());
break;
case "joined":
// Events for the audio bridge
OnJoined?.Invoke(eventResp);
m_log.DebugFormat("{0} EventLongPoll: joined {1}", LogHeader, resp.ToString());
break;
case "leaving":
// Events for the audio bridge
OnLeaving?.Invoke(eventResp);
m_log.DebugFormat("{0} EventLongPoll: leaving {1}", LogHeader, resp.ToString());
break;
case "GETERROR":
// Special error response from the GET
var errorResp = new ErrorResp(resp);
switch (errorResp.errorCode)
{
case 404:
// "Not found" means there is a Janus server but the session is gone
m_log.ErrorFormat("{0} EventLongPoll: GETERROR Not Found. URI={1}: {2}",
LogHeader, SessionUri, resp.ToString());
break;
case 400:
// "Bad request" means the session is gone
m_log.ErrorFormat("{0} EventLongPoll: Bad Request. URI={1}: {2}",
LogHeader, SessionUri, resp.ToString());
break;
case 499:
// "Task canceled" means the long poll was canceled
m_log.DebugFormat("{0} EventLongPoll: Task canceled. URI={1}", LogHeader, SessionUri);
break;
default:
m_log.DebugFormat("{0} EventLongPoll: unknown response. URI={1}: {2}",
LogHeader, SessionUri, resp.ToString());
break;
}
// This will cause the long poll to exit
running = false;
OnDisconnect?.Invoke(eventResp);
break;
default:
m_log.DebugFormat("{0} EventLongPoll: unknown response {1}", LogHeader, resp.ToString());
break;
}
});
}
else
{
m_log.ErrorFormat("{0} EventLongPoll: failed. Response is null", LogHeader);
}
}
catch (Exception e)
{
// This will cause the long poll to exit
running = false;
m_log.ErrorFormat("{0} EventLongPoll: exception {1}", LogHeader, e);
}
}
m_log.InfoFormat("{0} EventLongPoll: Exiting long poll loop", LogHeader);
});
}
}
}

View File

@@ -1,109 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Reflection;
using System.Threading.Tasks;
using OMV = OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
namespace osWebRtcVoice
{
public class JanusViewerSession : IVoiceViewerSession
{
protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected static readonly string LogHeader = "[JANUS VIEWER SESSION]";
// 'viewer_session' that is passed to and from the viewer
// IVoiceViewerSession.ViewerSessionID
public string ViewerSessionID { get; set; }
// IVoiceViewerSession.VoiceService
public IWebRtcVoiceService VoiceService { get; set; }
// The Janus server keeps track of the user by this ID
// IVoiceViewerSession.VoiceServiceSessionId
public string VoiceServiceSessionId { get; set; }
// IVoiceViewerSession.RegionId
public OMV.UUID RegionId { get; set; }
// IVoiceViewerSession.AgentId
public OMV.UUID AgentId { get; set; }
// Janus keeps track of the user by this ID
public int ParticipantId { get; set; }
// Connections to the Janus server
public JanusSession Session { get; set; }
public JanusAudioBridge AudioBridge { get; set; }
public JanusRoom Room { get; set; }
// This keeps copies of the offer/answer incase we need to resend
public string OfferOrig { get; set; }
public string Offer { get; set; }
// Contains "type" and "sdp" fields
public OSDMap Answer { get; set; }
public JanusViewerSession(IWebRtcVoiceService pVoiceService)
{
ViewerSessionID = OMV.UUID.Random().ToString();
VoiceService = pVoiceService;
m_log.Debug($"{LogHeader} JanusViewerSession created {ViewerSessionID}");
}
public JanusViewerSession(string pViewerSessionID, IWebRtcVoiceService pVoiceService)
{
ViewerSessionID = pViewerSessionID;
VoiceService = pVoiceService;
m_log.Debug($"{LogHeader} JanusViewerSession created {ViewerSessionID}");
}
// Send the messages to the voice service to try and get rid of the session
// IVoiceViewerSession.Shutdown
public async Task Shutdown()
{
m_log.DebugFormat($"{LogHeader} JanusViewerSession shutdown {ViewerSessionID}");
if (Room is not null)
{
var rm = Room;
Room = null;
await rm.LeaveRoom(this);
}
if (AudioBridge is not null)
{
var ab = AudioBridge;
AudioBridge = null;
await ab.Detach();
}
if (Session is not null)
{
var s = Session;
Session = null;
_ = await s.DestroySession().ConfigureAwait(false);
s.Dispose();
}
}
}
}

View File

@@ -1,478 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Threading.Tasks;
using OpenSim.Framework;
using OpenSim.Services.Base;
using OpenMetaverse.StructuredData;
using OpenMetaverse;
using Nini.Config;
using log4net;
namespace osWebRtcVoice
{
public class WebRtcJanusService : ServiceBase, IWebRtcVoiceService
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[JANUS WEBRTC SERVICE]";
private readonly IConfigSource _Config;
private bool _Enabled = false;
private string _JanusServerURI = string.Empty;
private string _JanusAPIToken = string.Empty;
private string _JanusAdminURI = string.Empty;
private string _JanusAdminToken = string.Empty;
private bool _MessageDetails = false;
// An extra "viewer session" that is created initially. Used to verify the service
// is working and for a handle for the console commands.
private JanusViewerSession _ViewerSession;
public WebRtcJanusService(IConfigSource pConfig) : base(pConfig)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string version = assembly.GetName().Version?.ToString() ?? "unknown";
_log.DebugFormat("{0} WebRtcJanusService version {1}", LogHeader, version);
_Config = pConfig;
IConfig webRtcVoiceConfig = _Config.Configs["WebRtcVoice"];
if (webRtcVoiceConfig is not null)
{
_Enabled = webRtcVoiceConfig.GetBoolean("Enabled", false);
IConfig janusConfig = _Config.Configs["JanusWebRtcVoice"];
if (_Enabled && janusConfig is not null)
{
_JanusServerURI = janusConfig.GetString("JanusGatewayURI", string.Empty);
_JanusAPIToken = janusConfig.GetString("APIToken", string.Empty);
_JanusAdminURI = janusConfig.GetString("JanusGatewayAdminURI", string.Empty);
_JanusAdminToken = janusConfig.GetString("AdminAPIToken", string.Empty);
// Debugging options
_MessageDetails = janusConfig.GetBoolean("MessageDetails", false);
if (string.IsNullOrEmpty(_JanusServerURI) || string.IsNullOrEmpty(_JanusAPIToken) ||
string.IsNullOrEmpty(_JanusAdminURI) || string.IsNullOrEmpty(_JanusAdminToken))
{
_log.Error($"{LogHeader} JanusWebRtcVoice configuration section missing required fields");
_Enabled = false;
}
if (_Enabled)
{
if(!StartConnectionToJanus())
{
_log.Error($"{LogHeader} failed connection to Janus Gateway. Disabled");
_Enabled=false;
return;
}
RegisterConsoleCommands();
_log.Info($"{LogHeader} Enabled");
}
}
else
{
_log.Error($"{LogHeader} No JanusWebRtcVoice configuration section");
_Enabled = false;
}
}
else
{
_log.Error($"{LogHeader} No WebRtcVoice configuration section");
_Enabled = false;
}
}
// Here an initial session is created and then a handle to the audio bridge plugin
// is created for the console commands. Since webrtc PeerConnections that are created
// my Janus are per-session, the other sessions will be created by the viewer requests.
private bool StartConnectionToJanus()
{
_log.DebugFormat("{0} StartConnectionToJanus", LogHeader);
_ViewerSession = new JanusViewerSession(this);
//bad
return ConnectToSessionAndAudioBridge(_ViewerSession).Result;
}
private async Task<bool> ConnectToSessionAndAudioBridge(JanusViewerSession pViewerSession)
{
JanusSession janusSession = new JanusSession(_JanusServerURI, _JanusAPIToken, _JanusAdminURI, _JanusAdminToken, _MessageDetails);
if (await janusSession.CreateSession().ConfigureAwait(false))
{
_log.DebugFormat("{0} JanusSession created", LogHeader);
// Once the session is created, create a handle to the plugin for rooms
JanusAudioBridge audioBridge = new JanusAudioBridge(janusSession);
if (await audioBridge.Activate(_Config).ConfigureAwait(false))
{
_log.Debug($"{LogHeader} AudioBridgePluginHandle created");
// Requests through the capabilities will create rooms
janusSession.AddPlugin(audioBridge);
pViewerSession.VoiceServiceSessionId = janusSession.SessionId;
pViewerSession.Session = janusSession;
pViewerSession.AudioBridge = audioBridge;
janusSession.OnDisconnect += Handle_Hangup;
janusSession.OnHangup += Handle_Hangup;
return true;
}
_log.Error($"{LogHeader} JanusPluginHandle not created");
}
_log.Error($"{LogHeader} JanusSession not created");
return false;
}
private void Handle_Hangup(EventResp pResp)
{
if (pResp is not null)
{
var sessionId = pResp.sessionId;
_log.Debug($"{LogHeader} Handle_Hangup: {pResp.RawBody}, sessionId={sessionId}");
if (VoiceViewerSession.TryGetViewerSessionByVSSessionId(sessionId, out IVoiceViewerSession viewerSession))
{
// There is a viewer session associated with this session
DisconnectViewerSession(viewerSession as JanusViewerSession);
}
else
{
_log.Debug($"{LogHeader} Handle_Hangup: no session found. SessionId={sessionId}");
}
}
}
// Disconnect the viewer session. This is called when the viewer logs out or hangs up.
private void DisconnectViewerSession(JanusViewerSession pViewerSession)
{
if (pViewerSession is not null)
{
Task.Run(() =>
{
VoiceViewerSession.RemoveViewerSession(pViewerSession.ViewerSessionID);
// No need to wait for the session to be shutdown
_ = pViewerSession.Shutdown();
});
}
}
// The pRequest parameter is a straight conversion of the JSON request from the client.
// This is the logic that takes the client's request and converts it into
// operations on rooms in the audio bridge.
// IWebRtcVoiceService.ProvisionVoiceAccountRequest
public OSDMap ProvisionVoiceAccountRequest(IVoiceViewerSession pSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
return ProvisionVoiceAccountRequestBAD(pSession, pRequest, pUserID, pSceneID).Result;
}
public async Task<OSDMap> ProvisionVoiceAccountRequestBAD(IVoiceViewerSession pSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
OSDMap ret = null;
string errorMsg = null;
JanusViewerSession viewerSession = pSession as JanusViewerSession;
if (viewerSession is not null)
{
if (viewerSession.Session is null)
{
// This is a new session so we must create a new session and handle to the audio bridge
await ConnectToSessionAndAudioBridge(viewerSession).ConfigureAwait(false);
}
// TODO: need to keep count of users in a room to know when to close a room
bool isLogout = pRequest.TryGetBool("logout", out bool lgout) && lgout;
if (isLogout)
{
// The client is logging out. Exit the room.
if (viewerSession.Room is not null)
{
await viewerSession.Room.LeaveRoom(viewerSession);
viewerSession.Room = null;
}
return new OSDMap
{
{ "response", "closed" }
};
}
// Get the parameters that select the room
// To get here, voice_server_type has already been checked to be 'webrtc' and channel_type='local'
int parcel_local_id = pRequest.TryGetInt("parcel_local_id", out int pli) ? pli : JanusAudioBridge.REGION_ROOM_ID;
string channel_id = pRequest.TryGetString("channel_id", out string cli) ? cli : string.Empty;
string channel_credentials = pRequest.TryGetString("credentials", out string cred) ? cred : string.Empty;
string channel_type = pRequest["channel_type"].AsString();
bool isSpatial = channel_type == "local";
string voice_server_type = pRequest["voice_server_type"].AsString();
_log.DebugFormat("{0} ProvisionVoiceAccountRequest: parcel_id={1} channel_id={2} channel_type={3} voice_server_type={4}", LogHeader, parcel_local_id, channel_id, channel_type, voice_server_type);
if (pRequest.TryGetOSDMap("jsep", out OSDMap jsep))
{
// The jsep is the SDP from the client. This is the client's request to connect to the audio bridge.
string jsepType = jsep["type"].AsString();
string jsepSdp = jsep["sdp"].AsString();
if (jsepType == "offer")
{
// The client is sending an offer. Find the right room and join it.
// _log.DebugFormat("{0} ProvisionVoiceAccountRequest: jsep type={1} sdp={2}", LogHeader, jsepType, jsepSdp);
viewerSession.Room = await viewerSession.AudioBridge.SelectRoom(pSceneID.ToString(),
channel_type, isSpatial, parcel_local_id, channel_id).ConfigureAwait(false);
if (viewerSession.Room is null)
{
errorMsg = "room selection failed";
_log.Error($"{LogHeader} ProvisionVoiceAccountRequest: room selection failed");
}
else {
viewerSession.Offer = jsepSdp;
viewerSession.OfferOrig = jsepSdp;
viewerSession.AgentId = pUserID;
if (await viewerSession.Room.JoinRoom(viewerSession).ConfigureAwait(false))
{
ret = new OSDMap
{
{ "jsep", viewerSession.Answer },
{ "viewer_session", viewerSession.ViewerSessionID }
};
}
else
{
errorMsg = "JoinRoom failed";
_log.Error($"{LogHeader} ProvisionVoiceAccountRequest: JoinRoom failed");
}
}
}
else
{
errorMsg = "jsep type not offer";
_log.Error($"{LogHeader} ProvisionVoiceAccountRequest: jsep type={jsepType} not offer");
}
}
else
{
errorMsg = "no jsep";
_log.Debug($"{LogHeader} ProvisionVoiceAccountRequest: no jsep. req={pRequest}");
}
}
else
{
errorMsg = "viewersession not JanusViewerSession";
_log.Error("{LogHeader} ProvisionVoiceAccountRequest: viewersession not JanusViewerSession");
}
if (!string.IsNullOrEmpty(errorMsg) && ret is null)
{
// The provision failed so build an error messgage to return
ret = new OSDMap
{
{ "response", "failed" },
{ "error", errorMsg }
};
}
return ret;
}
// IWebRtcVoiceService.VoiceAccountBalanceRequest
public OSDMap VoiceSignalingRequest(IVoiceViewerSession pSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
return VoiceSignalingRequestBAD(pSession, pRequest, pUserID, pSceneID).Result;
}
public async Task<OSDMap> VoiceSignalingRequestBAD(IVoiceViewerSession pSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
OSDMap ret = null;
JanusViewerSession viewerSession = pSession as JanusViewerSession;
JanusMessageResp resp = null;
if (viewerSession is not null)
{
// The request should be an array of candidates
if (pRequest.TryGetOSDMap("candidate", out OSDMap candidate))
{
if (candidate.TryGetBool("completed", out bool iscompleted) && iscompleted)
{
// The client has finished sending candidates
resp = await viewerSession.Session.TrickleCompleted(viewerSession).ConfigureAwait(false);
_log.DebugFormat($"{LogHeader} VoiceSignalingRequest: candidate completed");
}
else
{
}
}
else if (pRequest.TryGetOSDArray("candidates", out OSDArray candidates))
{
OSDArray candidatesArray = new OSDArray();
foreach (OSDMap cand in candidates)
{
candidatesArray.Add(new OSDMap() {
{ "candidate", cand["candidate"].AsString() },
{ "sdpMid", cand["sdpMid"].AsString() },
{ "sdpMLineIndex", cand["sdpMLineIndex"].AsLong() }
});
}
resp = await viewerSession.Session.TrickleCandidates(viewerSession, candidatesArray).ConfigureAwait(false);
_log.Debug($"{LogHeader} VoiceSignalingRequest: {candidatesArray.Count} candidates");
}
else
{
_log.Error($"{LogHeader} VoiceSignalingRequest: no 'candidate' or 'candidates'");
}
}
if (resp is null)
{
_log.ErrorFormat($"{LogHeader} VoiceSignalingRequest: no response so returning error");
ret = new OSDMap
{
{ "response", "error" }
};
}
else
{
ret = resp.RawBody;
}
return ret;
}
// This module should not be invoked with this signature
// IWebRtcVoiceService.ProvisionVoiceAccountRequest
public OSDMap ProvisionVoiceAccountRequest(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
throw new NotImplementedException();
}
// This module should not be invoked with this signature
// IWebRtcVoiceService.VoiceSignalingRequest
public OSDMap VoiceSignalingRequest(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
throw new NotImplementedException();
}
// The viewer session object holds all the connection information to Janus.
// IWebRtcVoiceService.CreateViewerSession
public IVoiceViewerSession CreateViewerSession(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
return new JanusViewerSession(this)
{
AgentId = pUserID,
RegionId = pSceneID
};
}
// ======================================================================================================
private void RegisterConsoleCommands()
{
if (_Enabled) {
MainConsole.Instance.Commands.AddCommand("Webrtc", false, "janus info",
"janus info",
"Show Janus server information",
HandleJanusInfo);
MainConsole.Instance.Commands.AddCommand("Webrtc", false, "janus list rooms",
"janus list rooms",
"List the rooms on the Janus server",
HandleJanusListRooms);
// List rooms
// List participants in a room
}
}
private void HandleJanusInfo(string module, string[] cmdparms)
{
if (_ViewerSession is not null && _ViewerSession.Session is not null)
{
WriteOut("{0} Janus session: {1}", LogHeader, _ViewerSession.Session.SessionId);
string infoURI = _ViewerSession.Session.JanusServerURI + "/info";
var resp = _ViewerSession.Session.GetFromJanus(infoURI).Result;
if (resp is not null)
MainConsole.Instance.Output(resp.ToJson());
}
}
private void HandleJanusListRooms(string module, string[] cmdparms)
{
if (_ViewerSession is not null && _ViewerSession.Session is not null && _ViewerSession.AudioBridge is not null)
{
var ab = _ViewerSession.AudioBridge;
var resp = ab.SendAudioBridgeMsg(new AudioBridgeListRoomsReq()).Result;
if (resp is not null && resp.isSuccess)
{
if (resp.PluginRespData.TryGetValue("list", out OSD list))
{
MainConsole.Instance.Output("");
MainConsole.Instance.Output(
" {0,10} {1,15} {2,5} {3,10} {4,7} {5,7}",
"Room", "Description", "Num", "SampleRate", "Spatial", "Recording");
foreach (OSDMap room in list as OSDArray)
{
int roomid = room["room"].AsInteger();
MainConsole.Instance.Output(
" {0,10} {1,15} {2,5} {3,10} {4,7} {5,7}",
roomid, room["description"], room["num_participants"],
room["sampling_rate"], room["spatial_audio"], room["record"]);
var participantResp = ab.SendAudioBridgeMsg(new AudioBridgeListParticipantsReq(roomid)).Result;
if (participantResp is not null && participantResp.AudioBridgeReturnCode == "participants")
{
if (participantResp.PluginRespData.TryGetValue("participants", out OSD participants))
{
foreach (OSDMap participant in participants as OSDArray)
{
MainConsole.Instance.Output(" {0}/{1},muted={2},talking={3},pos={4}",
participant["id"].AsLong(), participant["display"], participant["muted"],
participant["talking"], participant["spatial_position"]);
}
}
}
}
}
else
{
MainConsole.Instance.Output("No rooms");
}
}
else
{
MainConsole.Instance.Output("Failed to get room list");
}
}
}
private void WriteOut(string msg, params object[] args)
{
// m_log.InfoFormat(msg, args);
MainConsole.Instance.Output(msg, args);
}
}
}

View File

@@ -1,390 +0,0 @@
os-webrtc-janus original work, by Robert Adams, license changed to same BSD of rest of OpenSimulator
By Robert Adams, for OpenSimulator
Original license:
// Copyright 2024 Robert Adams (misterblue@misterblue.com)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@@ -1,234 +0,0 @@
# os-webrtc-janus
Addon-module for [OpenSimulator] to provide webrtc voice support
using Janus-gateway.
For an explanation of background and architecture,
this project was presented at the
[OpenSimulator Community Conference] 2024
in the presentation
[WebRTC Voice for OpenSimulator](https://www.youtube.com/watch?v=nL78fieIFYg).
This addon works by taking viewer requests for voice service and
using a separate, external [Janus-Gateway WebRTC server].
This can be configured to allow local region spatial voice
and grid-wide group and spatial voice. See the sections below.
For running that separate Janus server, check out
[os-webrtc-janus-docker] which has instructions for running
Janus-Gateway on Linux and Windows WSL using Docker.
Instructions for:
- [Building into OpenSimulator](#Building): Build OpenSimulator with WebRTC voice service
- [Configuring Simulator for Voice Services](#Configure_Simulator)
- [Configuring Robust Grid Service](#Configure_Robust)
- [Configure Standalone Region](#Configure_Standalone)
- [Managing Voice Service](#Managing_Voice) (console commands, etc)
**Note**: as of January 2024, this solution does not provide true spatial
voice service using Janus. There are people working on additions to Janus
to provide this but the existing solution provides only non-spatial
voice services using the `AudioBridge` Janus plugin. Additionally,
features like muting and individual avatar volume are not yet implemented.
<a id="Known_Issues"></a>
## Known Issues
- No spatial audio
- One can see your own "white dot" but you don't see other avatar's white dots
- No muting
- No individual volume control
And probably more found at [os-webrtc-janus issues](https://github.com/Misterblue/os-webrtc-janus/issues).
<a id="Building"></a>
## Building Plugin into OpenSimulator
`os-webrtc-janus` is integrated as a source build into [OpenSimulator].
It uses the [OpenSimulator] addon-module feature which makes the
build as easy as cloning the `os-webrtc-janus` sources into the
[OpenSimulator] source tree, running the build configuration script,
and then building OpenSimulator.
The steps are:
```
# Get the OpenSimulator sources
git clone git://opensimulator.org/git/opensim
cd opensim # cd into the top level OpenSim directory
# Fetch the WebRtc addon
cd addon-modules
git clone https://github.com/Misterblue/os-webrtc-janus.git
cd ..
# Build the project files
./runprebuild.sh
# Compile OpenSimulator with the webrtc addon
./compile.sh
# Copy the INI file for webrtc into a config dir that is read at boot
mkdir bin/config
cp addon-modules/os-webrtc-janus/os-webrtc-janus.ini bin/config
```
These building steps create several `.dll` files for `os-webrtc-janus`
in `bin/WebRtc*.dll`. Some adventurous people have found that, rather
than building the [OpenSimulator] sources, you can just copy the `.dll`s
into an existing `/bin` directory. Just make sure the `WebRtc*.dll` files
were built on the same version of [OpenSimulator] you are running.
<a id="Configure_Simulator"></a>
## Configure a Region for Voice
The last step in [Building](#Building) copied `os-webrtc-janus.ini` into
the `bin/config` directory. [OpenSimulator] reads all the `.ini` files
in that directory so this copy operation adds the configuration for `os-webrtc-janus`
and this is what needs to be configured for the simulator and region.
The sample `.ini` file has two sections: `[WebRtcVoice]` and `[JanusWebRtcVoice]`.
The `WebRtcVoice` section configures the what services the simulator uses
for WebRtc voice. The `[JanusWebRtcVoice]` section configures any connection
the simulator makes to the Janus server. The latter section is only updated
if this simulator is using a local Janus server for spatial voice.
The values for `SpatialVoiceService` and `NonSpatialVoiceService` point
either directly to a Janus service or to a Robust grid server that is providing
the grid voice service. Both these options are in the sample `os-webrtc-janus.ini`
file and the proper one should be uncommented.
The viewer makes requests for either spatial voice (used in the region and parcels)
or non-spatial voice (used for group chats or person-to-person voice conversations).
`os-webrtc-janus` allows these two types of voice connections to be handled by
different voice services. Thus there are two different configurations:
- all voice service is provided by the grid (both spatial and non-spatial point to a robust service), and
- the region simulator provides a local Janus server for region spatial voice while the grid service is used for group chats
#### Grid Only Voice Services
The most common configuration will be for a simulator that uses the grid supplied
voice services. For this configuration, `os-webrtc-janus.ini` would look like:
```
[WebRtcVoice]
Enabled = true
SpatialVoiceService = WebRtcVoice.dll:WebRtcVoiceServiceConnector
NonSpatialVoiceService = WebRtcVoice.dll:WebRtcVoiceServiceConnector
WebRtcVoiceServerURI = ${Const|PrivURL}:${Const|PrivatePort}
```
This directs both spatial and non-spatial voice to the grid service connector
and `WebRtcVoiceServerURI` points to the configured Robust grid service.
There is no need for a `[JanusWebRtcVoice]` section because all that is handled by the grid services.
#### Local Simulator Janus Service
In a grid setup, there might be a need for a single simulator/region to use its own
Janus server for either privacy or to off-load the grid voice service.
In this configuration, spatial voice is directed to the local Janus service
while the non-spatial voice goes to the grid services to allow grid wide group
chat and region independent person-to-person chat.
This is done with a `os-webrtc-janus.ini` that looks like:
```
[WebRtcVoice]
Enabled = true
SpatialVoiceService = WebRtcJanusService.dll:WebRtcJanusService
NonSpatialVoiceService = WebRtcVoice.dll:WebRtcVoiceServiceConnector
WebRtcVoiceServerURI = ${Const|PrivURL}:${Const|PrivatePort}
[JanusWebRtcVoice]
JanusGatewayURI = http://janus.example.org:14223/voice
APIToken = APITokenToNeverCheckIn
JanusGatewayAdminURI = http://janus.example.org/admin
AdminAPIToken = AdminAPITokenToNeverCheckIn
```
Notice that, since the simulator has its own Janus service, it must configure the
connection parameters to access that Janus service. The details of running and
configuring a Janus service is provided at [os-webrtc-janus-docker] but, the configuration
here needs to specify the URI to address the Janus server and the API keys
to allow this simulator access to its interfaces. The example above
contains just sample entries.
<a id="Configure_Robust"></a>
## Configure Robust Server for WebRTC Voice
For the grid services side, `os-webrtc-janus` is configured as an additional service
in the Robust OpenSimulator server. The additions to `Robust.ini` are:
```
...
[ServiceList]
...
VoiceServiceConnector = "${Const|PrivatePort}/WebRtcVoice.dll:WebRtcVoiceServerConnector"
...
[WebRtcVoice]
Enabled = true
SpatialVoiceService = WebRtcJanusService.dll:WebRtcJanusService
NonSpatialVoiceService = WebRtcJanusService.dll:WebRtcJanusService
[JanusWebRtcVoice]
JanusGatewayURI = http://janus.example.org:14223/voice
APIToken = APITokenToNeverCheckIn
JanusGatewayAdminURI = http://janus.example.org/admin
AdminAPIToken = AdminAPITokenToNeverCheckIn
...
```
This adds `VoiceServiceConnector` to the list of services presented by this Robust server
and adds the WebRtcVoice configuration that says to do both spatial and non-spatial voice
using the Janus server, and the configuration for the Janus server itself.
One can configure multiple Robust services to distribute the load of services
and a Robust server with only `VoiceServiceConnector` in its ServiceList is possible.
<a id="Configure_Standalone"></a>
## Configure Standalone Region
[OpenSimulator] can be run "standalone" where all the grid services and regions are
run in one simulator instance. Adding voice to this configuration is sometimes useful
for very private meetings or testing. For this configuration, a Janus server is set up
and the standalone simulator is configured to point all voice to that Janus server:
```
[WebRtcVoice]
Enabled = true
SpatialVoiceService = WebRtcJanusService.dll:WebRtcJanusService
NonSpatialVoiceService = WebRtcJanusService.dll:WebRtcJanusService
WebRtcVoiceServerURI = ${Const|PrivURL}:${Const|PrivatePort}
[JanusWebRtcVoice]
JanusGatewayURI = http://janus.example.org:14223/voice
APIToken = APITokenToNeverCheckIn
JanusGatewayAdminURI = http://janus.example.org/admin
AdminAPIToken = AdminAPITokenToNeverCheckIn
```
This directs both spatial and non-spatial voice to the Janus server
and configures the URI address of the Janus server and the API access
keys for that server.
<a id="Managing_Voice"></a>
## Managing Voice (Console commands)
There are a few console commands for checking on and controlling the voice system.
The current list of commands for the simulator can be listed with the
console command `help webrtc`.
This is a growing section and will be added to over time.
**webrtc list sessions** -- not implemented
**janus info** -- list many details of the Janus-Gateway configuration. Very ugly, non-formated JSON.
**janus list rooms** -- list the rooms that have been allocated in the `AudioBridge` Janus plugin
[SecondLife WebRTC Voice]: https://wiki.secondlife.com/wiki/WebRTC_Voice
[OpenSimulator]: http://opensimulator.org
[OpenSimulator Community Conference]: https://conference.opensimulator.org
[os-webrtc-janus]: https://github.com/Misterblue/os-webrtc-janus
[Janus-Gateway WebRTC server]: https://janus.conf.meetecho.com/
[os-webrtc-janus-docker]: https://github.com/Misterblue/os-webrtc-janus-docker

View File

@@ -1,132 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Linq;
using System.Collections.Generic;
using OpenMetaverse;
using System.Threading.Tasks;
namespace osWebRtcVoice
{
public class VoiceViewerSession : IVoiceViewerSession
{
// A simple session structure that is used when the connection is actually in the
// remote service.
public VoiceViewerSession(IWebRtcVoiceService pVoiceService, UUID pRegionId, UUID pAgentId)
{
RegionId = pRegionId;
AgentId = pAgentId;
ViewerSessionID = UUID.Random().ToString();
VoiceService = pVoiceService;
}
public string ViewerSessionID { get; set; }
public IWebRtcVoiceService VoiceService { get; set; }
public string VoiceServiceSessionId
{
get => throw new System.NotImplementedException();
set => throw new System.NotImplementedException();
}
public UUID RegionId { get; set; }
public UUID AgentId { get; set; }
// =====================================================================
// ViewerSessions hold the connection information for the client connection through to the voice service.
// This collection is static and is simulator wide so there will be sessions for all regions and all clients.
public static Dictionary<string, IVoiceViewerSession> ViewerSessions = new Dictionary<string, IVoiceViewerSession>();
// Get a viewer session by the viewer session ID
public static bool TryGetViewerSession(string pViewerSessionId, out IVoiceViewerSession pViewerSession)
{
lock (ViewerSessions)
{
return ViewerSessions.TryGetValue(pViewerSessionId, out pViewerSession);
}
}
// public static bool TryGetViewerSessionByAgentId(UUID pAgentId, out IVoiceViewerSession pViewerSession)
public static bool TryGetViewerSessionByAgentId(UUID pAgentId, out IEnumerable<KeyValuePair<string, IVoiceViewerSession>> pViewerSessions)
{
lock (ViewerSessions)
{
pViewerSessions = ViewerSessions.Where(v => v.Value.AgentId == pAgentId);
return pViewerSessions.Count() > 0;
}
}
// Get a viewer session by the VoiceService session ID
public static bool TryGetViewerSessionByVSSessionId(string pVSSessionId, out IVoiceViewerSession pViewerSession)
{
lock (ViewerSessions)
{
var sessions = ViewerSessions.Where(v => v.Value.VoiceServiceSessionId == pVSSessionId);
if (sessions.Count() > 0)
{
pViewerSession = sessions.First().Value;
return true;
}
pViewerSession = null;
return false;
}
}
public static void AddViewerSession(IVoiceViewerSession pSession)
{
lock (ViewerSessions)
{
ViewerSessions[pSession.ViewerSessionID] = pSession;
}
}
public static void RemoveViewerSession(string pSessionId)
{
lock (ViewerSessions)
{
ViewerSessions.Remove(pSessionId);
}
}
// Update a ViewSession from one ID to another.
// Remove the old session ID from the ViewerSessions collection, update the
// sessionID value in the IVoiceViewerSession, and add the session back to the
// collection.
// This is used in the kludge to synchronize a region's ViewerSessionID with the
// remote VoiceService's session ID.
public static void UpdateViewerSessionId(IVoiceViewerSession pSession, string pNewSessionId)
{
lock (ViewerSessions)
{
ViewerSessions.Remove(pSession.ViewerSessionID);
pSession.ViewerSessionID = pNewSessionId;
ViewerSessions[pSession.ViewerSessionID] = pSession;
}
}
public Task Shutdown()
{
throw new System.NotImplementedException();
}
}
}

View File

@@ -1,171 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using System.Threading.Tasks;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
namespace osWebRtcVoice
{
// Class that provides the network interface to the WebRTC voice server.
// This is used by the Robust server to receive requests from the region servers
// and do the voice stuff on the WebRTC service (see WebRtcVoiceServiceConnector).
public class WebRtcVoiceServerConnector : IServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[WEBRTC VOICE SERVER CONNECTOR]";
private bool m_Enabled = false;
private bool m_MessageDetails = false;
private IWebRtcVoiceService m_WebRtcVoiceService;
public WebRtcVoiceServerConnector(IConfigSource pConfig, IHttpServer pServer, string pConfigName)
{
IConfig moduleConfig = pConfig.Configs["WebRtcVoice"];
if (moduleConfig is not null)
{
m_Enabled = moduleConfig.GetBoolean("Enabled", false);
if (m_Enabled)
{
m_log.InfoFormat("{0} WebRtcVoiceServerConnector enabled", LogHeader);
m_MessageDetails = moduleConfig.GetBoolean("MessageDetails", false);
// This creates the local service that handles the requests.
// The local service provides the IWebRtcVoiceService interface and directs the requests
// to the WebRTC service.
string localServiceModule = moduleConfig.GetString("LocalServiceModule", "WebRtcVoiceServiceModule.dll:WebRtcVoiceServiceModule");
m_log.DebugFormat("{0} loading {1}", LogHeader, localServiceModule);
object[] args = new object[0];
m_WebRtcVoiceService = ServerUtils.LoadPlugin<IWebRtcVoiceService>(localServiceModule, args);
// The WebRtcVoiceServiceModule is both an IWebRtcVoiceService and a ISharedRegionModule
// so we can initialize it as if it was the region module.
ISharedRegionModule sharedModule = m_WebRtcVoiceService as ISharedRegionModule;
if (sharedModule is null)
{
m_log.ErrorFormat("{0} local service module does not implement ISharedRegionModule", LogHeader);
m_Enabled = false;
return;
}
sharedModule.Initialise(pConfig);
// Now that we have someone to handle the requests, we can set up the handlers
pServer.AddJsonRPCHandler("provision_voice_account_request", Handle_ProvisionVoiceAccountRequest);
pServer.AddJsonRPCHandler("voice_signaling_request", Handle_VoiceSignalingRequest);
}
}
}
private bool Handle_ProvisionVoiceAccountRequest(OSDMap pJson, ref JsonRpcResponse pResponse)
{
bool ret = false;
m_log.DebugFormat("{0} Handle_ProvisionVoiceAccountRequest", LogHeader);
if (m_MessageDetails) m_log.DebugFormat("{0} PVAR: req={1}", LogHeader, pJson.ToString());
if (pJson.ContainsKey("params") && pJson["params"] is OSDMap paramsMap)
{
OSDMap request = paramsMap.ContainsKey("request") ? paramsMap["request"] as OSDMap : null;
UUID userID = paramsMap.ContainsKey("userID") ? paramsMap["userID"].AsUUID() : UUID.Zero;
UUID sceneID = paramsMap.ContainsKey("scene") ? paramsMap["scene"].AsUUID() : UUID.Zero;
try
{
if (m_WebRtcVoiceService is null)
{
m_log.ErrorFormat("{0} PVAR: no local service", LogHeader);
return false;
}
OSDMap resp = m_WebRtcVoiceService.ProvisionVoiceAccountRequest(request, userID, sceneID);
pResponse = new JsonRpcResponse();
pResponse.Result = resp;
if (m_MessageDetails) m_log.DebugFormat("{0} PVAR: resp={1}", LogHeader, resp.ToString());
ret = true;
}
catch (Exception e)
{
m_log.ErrorFormat("{0} PVAR: exception {1}", LogHeader, e);
}
}
else
{
m_log.ErrorFormat("{0} PVAR: missing parameters", LogHeader);
}
return ret;
}
private bool Handle_VoiceSignalingRequest(OSDMap pJson, ref JsonRpcResponse pResponse)
{
bool ret = false;
if (pJson.ContainsKey("params") && pJson["params"] is OSDMap paramsMap)
{
m_log.DebugFormat("{0} Handle_VoiceSignalingRequest", LogHeader);
if (m_MessageDetails) m_log.DebugFormat("{0} VSR: req={1}", LogHeader, paramsMap.ToString());
OSDMap request = paramsMap.ContainsKey("request") ? paramsMap["request"] as OSDMap : null;
UUID userID = paramsMap.ContainsKey("userID") ? paramsMap["userID"].AsUUID() : UUID.Zero;
UUID sceneID = paramsMap.ContainsKey("scene") ? paramsMap["scene"].AsUUID() : UUID.Zero;
try
{
OSDMap resp = m_WebRtcVoiceService.VoiceSignalingRequest(request, userID, sceneID);
pResponse = new JsonRpcResponse();
pResponse.Result = resp;
if (m_MessageDetails) m_log.DebugFormat("{0} VSR: resp={1}", LogHeader, resp.ToString());
ret = true;
}
catch (Exception e)
{
m_log.ErrorFormat("{0} VSR: exception {1}", LogHeader, e);
}
}
else
{
m_log.ErrorFormat("{0} VSR: missing parameters", LogHeader);
}
return ret;
}
}
}

View File

@@ -1,204 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using OpenSim.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
namespace osWebRtcVoice
{
// Class that provides the local IWebRtcVoiceService interface to the JsonRPC Robust
// server. This is used by the region servers to talk to the Robust server.
public class WebRtcVoiceServiceConnector : IWebRtcVoiceService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[WEBRTC VOICE SERVICE CONNECTOR]";
private bool m_Enabled = false;
private bool m_MessageDetails = false;
private IConfigSource m_Config;
string m_serverURI = "http://localhost:8080";
public WebRtcVoiceServiceConnector(IConfigSource pConfig)
{
m_Config = pConfig;
IConfig moduleConfig = m_Config.Configs["WebRtcVoice"];
if (moduleConfig is not null)
{
m_Enabled = moduleConfig.GetBoolean("Enabled", false);
if (m_Enabled)
{
m_serverURI = moduleConfig.GetString("WebRtcVoiceServerURI", string.Empty);
if (string.IsNullOrWhiteSpace(m_serverURI))
{
m_log.Error($"{LogHeader} WebRtcVoiceServiceConnector enabled but no WebRtcVoiceServerURI specified");
m_Enabled = false;
}
else
{
m_log.Info($"{LogHeader} WebRtcVoiceServiceConnector enabled");
}
m_MessageDetails = moduleConfig.GetBoolean("MessageDetails", false);
}
}
}
// Create a local viewer session. This gets a local viewer session ID that is
// later changed when the ProvisionVoiceAccountRequest response is returned
// so that the viewer session ID is the same here as from the WebRTC service.
public IVoiceViewerSession CreateViewerSession(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
m_log.Debug($"{LogHeader} CreateViewerSession");
return new VoiceViewerSession(this, pUserID, pSceneID);
}
public OSDMap ProvisionVoiceAccountRequest(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
m_log.Debug($"{LogHeader} ProvisionVoiceAccountRequest without ViewerSession. uID={pUserID}, sID={pSceneID}");
return null;
}
// Received a ProvisionVoiceAccountRequest from a viewer. Forward it to the WebRTC service.
public OSDMap ProvisionVoiceAccountRequest(IVoiceViewerSession pVSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
m_log.Debug($"{LogHeader} VoiceSignalingRequest. uID={pUserID}, sID={pSceneID}");
OSDMap req = new()
{
{ "request", pRequest },
{ "userID", pUserID.ToString() },
{ "scene", pSceneID.ToString() }
};
var resp = JsonRpcRequest("provision_voice_account_request", m_serverURI, req);
// Kludge to sync the viewer session number in our IVoiceViewerSession with the one from the WebRTC service.
if (resp.TryGetString("viewer_session", out string otherViewerSessionId))
{
m_log.Debug(
$"{LogHeader} ProvisionVoiceAccountRequest: syncing viewSessionID. old={pVSession.ViewerSessionID}, new={otherViewerSessionId}");
VoiceViewerSession.UpdateViewerSessionId(pVSession, otherViewerSessionId);
}
return resp;
}
public OSDMap VoiceSignalingRequest(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
m_log.Debug($"{LogHeader} VoiceSignalingRequest without ViewerSession. uID={pUserID}, sID={pSceneID}");
return null;
}
public OSDMap VoiceSignalingRequest(IVoiceViewerSession pVSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
m_log.DebugFormat("{0} VoiceSignalingRequest. uID={1}, sID={2}", LogHeader, pUserID, pSceneID);
OSDMap req = new()
{
{ "request", pRequest },
{ "userID", pUserID.ToString() },
{ "scene", pSceneID.ToString() }
};
return JsonRpcRequest("voice_signaling_request", m_serverURI, req);
}
public OSDMap JsonRpcRequest(string method, string uri, OSDMap pParams)
{
string jsonId = UUID.Random().ToString();
if(string.IsNullOrWhiteSpace(uri))
return null;
OSDMap request = new()
{
{ "jsonrpc", OSD.FromString("2.0") },
{ "id", OSD.FromString(jsonId) },
{ "method", OSD.FromString(method) },
{ "params", pParams }
};
OSDMap outerResponse = null;
try
{
if (m_MessageDetails) m_log.Debug($"{LogHeader}: request: {request}");
outerResponse = WebUtil.PostToService(uri, request, 10000, true);
if (m_MessageDetails) m_log.Debug($"{LogHeader}: response: {outerResponse}");
}
catch (Exception e)
{
m_log.Error($"{LogHeader}: JsonRpc request '{method}' to {uri} failed: {e.Message}");
m_log.Debug($"{LogHeader}: request: {request}");
return new OSDMap()
{
{ "error", OSD.FromString(e.Message) }
};
}
if (!outerResponse.TryGetOSDMap("_Result", out OSDMap response))
{
string errm = $"JsonRpc request '{method}' to {1} returned an invalid response: {OSDParser.SerializeJsonString(outerResponse)}";
m_log.Error(errm);
return new OSDMap()
{
{ "error", errm }
};
}
OSD osdtmp;
if (response.TryGetValue("error", out osdtmp))
{
string errm = $"JsonRpc request '{method}' to {uri} returned an error: {OSDParser.SerializeJsonString(osdtmp)}";
m_log.Error(errm);
return new OSDMap()
{
{ "error", errm }
};
}
if (!response.TryGetOSDMap("result", out OSDMap resultmap ))
{
string errm = $"JsonRpc request '{method}' to {uri} returned result as non-OSDMap: {OSDParser.SerializeJsonString(outerResponse)}";
m_log.Error(errm);
return new OSDMap()
{
{ "error", errm }
};
}
return resultmap;
}
}
}

View File

@@ -1,500 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Net;
using System.Reflection;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using log4net;
using Nini.Config;
[assembly: Addin("WebRtcVoiceRegionModule", "1.0")]
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
namespace osWebRtcVoice
{
/// <summary>
/// This module provides the WebRTC voice interface for viewer clients..
///
/// In particular, it provides the following capabilities:
/// ProvisionVoiceAccountRequest, VoiceSignalingRequest and limited ChatSessionRequest
/// which are the user interface to the voice service.
///
/// Initially, when the user connects to the region, the region feature "VoiceServiceType" is
/// set to "webrtc" and the capabilities that support voice are enabled.
/// The capabilities then pass the user request information to the IWebRtcVoiceService interface
/// that has been registered for the reqion.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionVoiceModule")]
public class WebRtcVoiceRegionModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string logHeader = "[REGION WEBRTC VOICE]";
private static byte[] llsdUndefAnswerBytes = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
private bool _MessageDetails = false;
// Control info
private static bool m_Enabled = false;
private IConfig m_Config;
// ISharedRegionModule.Initialize
public void Initialise(IConfigSource config)
{
m_Config = config.Configs["WebRtcVoice"];
if (m_Config is not null)
{
m_Enabled = m_Config.GetBoolean("Enabled", false);
if (m_Enabled)
{
_MessageDetails = m_Config.GetBoolean("MessageDetails", false);
m_log.Info($"{logHeader}: enabled");
}
}
}
// ISharedRegionModule.PostInitialize
public void PostInitialise()
{
}
// ISharedRegionModule.AddRegion
public void AddRegion(Scene scene)
{
// todo register module to get parcels changes etc
}
// ISharedRegionModule.RemoveRegion
public void RemoveRegion(Scene scene)
{
}
// ISharedRegionModule.RegionLoaded
public void RegionLoaded(Scene scene)
{
if (m_Enabled)
{
scene.EventManager.OnRegisterCaps += delegate (UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
ISimulatorFeaturesModule simFeatures = scene.RequestModuleInterface<ISimulatorFeaturesModule>();
simFeatures?.AddFeature("VoiceServerType", OSD.FromString("webrtc"));
}
}
// ISharedRegionModule.Close
public void Close()
{
}
// ISharedRegionModule.Name
public string Name
{
get { return "RegionVoiceModule"; }
}
// ISharedRegionModule.ReplaceableInterface
public Type ReplaceableInterface
{
get { return null; }
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute three capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest, VoiceSignalingRequest and limited ChatSessionRequest
//
// ProvisionVoiceAccountRequest allows the client to obtain
// voice communication information the the avater.
//
// VoiceSignalingRequest: Used for trickling ICE candidates.
//
// ChatSessionRequest
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.Debug(
$"{logHeader}: OnRegisterCaps called with agentID {agentID} caps {caps} in scene {scene.Name}");
caps.RegisterSimpleHandler("ProvisionVoiceAccountRequest",
new SimpleStreamHandler("/" + UUID.Random(), (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) =>
{
ProvisionVoiceAccountRequest(httpRequest, httpResponse, agentID, scene);
}));
caps.RegisterSimpleHandler("VoiceSignalingRequest",
new SimpleStreamHandler("/" + UUID.Random(), (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) =>
{
VoiceSignalingRequest(httpRequest, httpResponse, agentID, scene);
}));
caps.RegisterSimpleHandler("ChatSessionRequest",
new SimpleStreamHandler("/" + UUID.Random(), (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) =>
{
ChatSessionRequest(httpRequest, httpResponse, agentID, scene);
}));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public void ProvisionVoiceAccountRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
{
// Get the voice service. If it doesn't exist, return an error.
IWebRtcVoiceService voiceService = scene.RequestModuleInterface<IWebRtcVoiceService>();
if (voiceService is null)
{
m_log.Error($"{logHeader}[ProvisionVoice]: voice service not loaded");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if(request.HttpMethod != "POST")
{
m_log.DebugFormat($"[{logHeader}][ProvisionVoice]: Not a POST request. Agent={agentID}");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
// Deserialize the request. Convert the LLSDXml to OSD for our use
OSDMap map = BodyToMap(request, "ProvisionVoiceAccountRequest");
if (map is null)
{
m_log.Error($"{logHeader}[ProvisionVoice]: No request data found. Agent={agentID}");
response.StatusCode = (int)HttpStatusCode.NoContent;
return;
}
// Make sure the request is for WebRtc voice
if (map.TryGetValue("voice_server_type", out OSD vstosd))
{
if (vstosd is OSDString vst && !((string)vst).Equals("webrtc", StringComparison.OrdinalIgnoreCase))
{
m_log.Warn($"{logHeader}[ProvisionVoice]: voice_server_type is not 'webrtc'. Request: {map}");
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.OK;
return;
}
}
if (_MessageDetails) m_log.DebugFormat($"{logHeader}[ProvisionVoice]: request: {map}");
if (map.TryGetString("channel_type", out string channelType))
{
//do fully not trust viewers voice parcel requests
if (channelType == "local")
{
if (!scene.RegionInfo.EstateSettings.AllowVoice)
{
m_log.Debug($"{logHeader}[ProvisionVoice]:region \"{scene.Name}\": voice not enabled in estate settings");
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.NotImplemented;
return;
}
if (scene.LandChannel == null)
{
m_log.Error($"{logHeader}[ProvisionVoice] region \"{scene.Name}\" land data not yet available");
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.NotImplemented;
return;
}
if(!scene.TryGetScenePresence(agentID, out ScenePresence sp))
{
m_log.Debug($"{logHeader}[ProvisionVoice]:avatar not found");
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if(map.TryGetInt("parcel_local_id", out int parcelID))
{
ILandObject parcel = scene.LandChannel.GetLandObject(parcelID);
if (parcel == null)
{
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
LandData land = parcel.LandData;
if (land == null)
{
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if (!scene.RegionInfo.EstateSettings.TaxFree && (land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
m_log.Debug($"{logHeader}[ProvisionVoice]:parcel voice not allowed");
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
if ((land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) != 0)
{
map.Remove("parcel_local_id"); // estate channel
}
else if(parcel.IsRestrictedFromLand(agentID) || parcel.IsBannedFromLand(agentID))
{
// check Z distance?
m_log.Debug($"{logHeader}[ProvisionVoice]:agent not allowed on parcel");
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
}
}
}
// The checks passed. Send the request to the voice service.
OSDMap resp = voiceService.ProvisionVoiceAccountRequest(map, agentID, scene.RegionInfo.RegionID);
if(resp is not null)
{
if (_MessageDetails) m_log.DebugFormat($"{logHeader}[ProvisionVoice]: response: {resp}");
// TODO: check for errors and package the response
// Convert the OSD to LLSDXml for the response
string xmlResp = OSDParser.SerializeLLSDXmlString(resp);
response.RawBuffer = Util.UTF8.GetBytes(xmlResp);
response.StatusCode = (int)HttpStatusCode.OK;
}
else
{
m_log.DebugFormat($"{logHeader}[ProvisionVoice]: got null response");
response.StatusCode = (int)HttpStatusCode.OK;
}
return;
}
public void VoiceSignalingRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
{
IWebRtcVoiceService voiceService = scene.RequestModuleInterface<IWebRtcVoiceService>();
if (voiceService is null)
{
m_log.ErrorFormat($"{logHeader}[VoiceSignalingRequest]: avatar \"{agentID}\": no voice service");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if(request.HttpMethod != "POST")
{
m_log.Error($"[{logHeader}][VoiceSignaling]: Not a POST request. Agent={agentID}");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
// Deserialize the request. Convert the LLSDXml to OSD for our use
OSDMap map = BodyToMap(request, "VoiceSignalingRequest");
if (map is null)
{
m_log.ErrorFormat($"{logHeader}[VoiceSignalingRequest]: No request data found. Agent={agentID}");
response.StatusCode = (int)HttpStatusCode.NoContent;
return;
}
// Make sure the request is for WebRTC voice
if (map.TryGetValue("voice_server_type", out OSD vstosd))
{
if (vstosd is OSDString vst && !((string)vst).Equals("webrtc", StringComparison.OrdinalIgnoreCase))
{
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.OK;
return;
}
}
OSDMap resp = voiceService.VoiceSignalingRequest(map, agentID, scene.RegionInfo.RegionID);
if (_MessageDetails) m_log.Debug($"{logHeader}[VoiceSignalingRequest]: Response: {resp}");
// TODO: check for errors and package the response
response.RawBuffer = llsdUndefAnswerBytes;
response.StatusCode = (int)HttpStatusCode.OK;
return;
}
/// <summary>
/// Callback for a client request for ChatSessionRequest.
/// The viewer sends this request when the user tries to start a P2P text or voice session
/// with another user. We need to generate a new session ID and return it to the client.
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
/// <param name="agentID"></param>
/// <param name="scene"></param>
public void ChatSessionRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
{
m_log.DebugFormat("{0}: ChatSessionRequest received for agent {1} in scene {2}", logHeader, agentID, scene.RegionInfo.RegionName);
if (request.HttpMethod != "POST")
{
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if (!scene.TryGetScenePresence(agentID, out ScenePresence sp) || sp.IsDeleted)
{
m_log.Warn($"{logHeader} ChatSessionRequest: scene presence not found or deleted for agent {agentID}");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
OSDMap reqmap = BodyToMap(request, "[ChatSessionRequest]");
if (reqmap is null)
{
m_log.Warn($"{logHeader} ChatSessionRequest: message body not parsable in request for agent {agentID}");
response.StatusCode = (int)HttpStatusCode.NoContent;
return;
}
m_log.Debug($"{logHeader} ChatSessionRequest");
if (!reqmap.TryGetString("method", out string method))
{
m_log.Warn($"{logHeader} ChatSessionRequest: missing required 'method' field in request for agent {agentID}");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if (!reqmap.TryGetUUID("session-id", out UUID sessionID))
{
m_log.Warn($"{logHeader} ChatSessionRequest: missing required 'session-id' field in request for agent {agentID}");
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
switch (method.ToLower())
{
// Several different method requests that we don't know how to handle.
// Just return OK for now.
case "decline p2p voice":
case "decline invitation":
case "start conference":
case "fetch history":
response.StatusCode = (int)HttpStatusCode.OK;
break;
// Asking to start a P2P voice session. We need to generate a new session ID and return
// it to the client in a ChatterBoxSessionStartReply event.
case "start p2p voice":
UUID newSessionID;
if (reqmap.TryGetUUID("params", out UUID otherID))
newSessionID = new(otherID.ulonga ^ agentID.ulonga, otherID.ulongb ^ agentID.ulongb);
else
newSessionID = UUID.Random();
IEventQueue queue = scene.RequestModuleInterface<IEventQueue>();
if (queue is null)
{
m_log.ErrorFormat("{0}: no event queue for scene {1}", logHeader, scene.RegionInfo.RegionName);
response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
queue.ChatterBoxSessionStartReply(
newSessionID,
sp.Name,
2,
false,
true,
sessionID,
true,
string.Empty,
agentID);
response.StatusCode = (int)HttpStatusCode.OK;
}
break;
default:
response.StatusCode = (int)HttpStatusCode.BadRequest;
break;
}
}
/// <summary>
/// Convert the LLSDXml body of the request to an OSDMap for easier handling.
/// Also logs the request if message details is enabled.
/// </summary>
/// <param name="request"></param>
/// <param name="pCaller"></param>
/// <returns>'null' if the request body is empty or cannot be deserialized</returns>
private OSDMap BodyToMap(IOSHttpRequest request, string pCaller)
{
try
{
using Stream inputStream = request.InputStream;
if (inputStream.Length > 0)
{
OSD tmp = OSDParser.DeserializeLLSDXml(inputStream);
if (_MessageDetails)
m_log.Debug($"{pCaller} BodyToMap: Request: {tmp}");
if(tmp is OSDMap map)
return map;
}
}
catch
{
m_log.Debug($"{pCaller} BodyToMap: Fail to decode LLSDXml request");
}
return null;
}
}
}

View File

@@ -1,295 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Server.Base;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Mono.Addins;
using log4net;
using Nini.Config;
[assembly: Addin("WebRtcVoiceServiceModule", "1.0")]
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
namespace osWebRtcVoice
{
/// <summary>
/// Interface for the WebRtcVoiceService.
/// An instance of this is registered as the IWebRtcVoiceService for this region.
/// The function here is to direct the capability requests to the appropriate voice service.
/// For the moment, there are separate voice services for spatial and non-spatial voice
/// with the idea that a region could have a pre-region spatial voice service while
/// the grid could have a non-spatial voice service for group chat, etc.
/// Fancier configurations are possible.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebRtcVoiceServiceModule")]
public class WebRtcVoiceServiceModule : ISharedRegionModule, IWebRtcVoiceService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[WEBRTC VOICE SERVICE MODULE]";
private static bool m_Enabled = false;
private IConfigSource m_Config;
private IWebRtcVoiceService m_spatialVoiceService;
private IWebRtcVoiceService m_nonSpatialVoiceService;
// =====================================================================
// ISharedRegionModule.Initialize
// Get configuration and load the modules that will handle spatial and non-spatial voice.
public void Initialise(IConfigSource pConfig)
{
m_Config = pConfig;
IConfig moduleConfig = m_Config.Configs["WebRtcVoice"];
if (moduleConfig is not null)
{
m_Enabled = moduleConfig.GetBoolean("Enabled", false);
if (m_Enabled)
{
// Get the DLLs for the two voice services
string spatialDllName = moduleConfig.GetString("SpatialVoiceService", string.Empty);
string nonSpatialDllName = moduleConfig.GetString("NonSpatialVoiceService", string.Empty);
if (string.IsNullOrEmpty(spatialDllName) && string.IsNullOrEmpty(nonSpatialDllName))
{
m_log.Error($"{LogHeader} No VoiceService specified in configuration");
m_Enabled = false;
return;
}
// Default non-spatial to spatial if not specified
if (string.IsNullOrEmpty(nonSpatialDllName))
{
m_log.Debug($"{LogHeader} nonSpatialDllName not specified. Defaulting to spatialDllName");
nonSpatialDllName = spatialDllName;
}
// Load the two voice services
m_log.Debug($"{LogHeader} Loading SpatialVoiceService from {spatialDllName}");
m_spatialVoiceService = ServerUtils.LoadPlugin<IWebRtcVoiceService>(spatialDllName, [m_Config]);
if (m_spatialVoiceService is null)
{
m_log.Error($"{LogHeader} Could not load SpatialVoiceService from {spatialDllName}, module disabled");
m_Enabled = false;
return;
}
m_log.Debug($"{LogHeader} Loading NonSpatialVoiceService from {nonSpatialDllName}");
if (spatialDllName != nonSpatialDllName)
{
m_nonSpatialVoiceService = ServerUtils.LoadPlugin<IWebRtcVoiceService>(nonSpatialDllName, [ m_Config ]);
if (m_nonSpatialVoiceService is null)
{
m_log.Error("{LogHeader} Could not load NonSpatialVoiceService from {nonSpatialDllName}");
m_Enabled = false;
}
}
if (m_Enabled)
{
m_log.Info($"{LogHeader} WebRtcVoiceService enabled");
}
}
}
}
// ISharedRegionModule.PostInitialize
public void PostInitialise()
{
}
// ISharedRegionModule.Close
public void Close()
{
}
// ISharedRegionModule.ReplaceableInterface
public Type ReplaceableInterface
{
get { return null; }
}
// ISharedRegionModule.Name
public string Name
{
get { return "WebRtcVoiceServiceModule"; }
}
// ISharedRegionModule.AddRegion
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
m_log.Debug($"{LogHeader} Adding WebRtcVoiceService to region {scene.Name}");
scene.RegisterModuleInterface<IWebRtcVoiceService>(this);
// TODO: figure out what events we care about
// When new client (child or root) is added to scene, before OnClientLogin
// scene.EventManager.OnNewClient += Event_OnNewClient;
// When client is added on login.
// scene.EventManager.OnClientLogin += Event_OnClientLogin;
// New presence is added to scene. Child, root, and NPC. See Scene.AddNewAgent()
// scene.EventManager.OnNewPresence += Event_OnNewPresence;
// scene.EventManager.OnRemovePresence += Event_OnRemovePresence;
// update to client position (either this or 'significant')
// scene.EventManager.OnClientMovement += Event_OnClientMovement;
// "significant" update to client position
// scene.EventManager.OnSignificantClientMovement += Event_OnSignificantClientMovement;
}
}
// ISharedRegionModule.RemoveRegion
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IWebRtcVoiceService>(this);
}
}
// ISharedRegionModule.RegionLoaded
public void RegionLoaded(Scene scene)
{
}
// =====================================================================
// Thought about doing this but currently relying on the voice service
// event ("hangup") to remove the viewer session.
private void Event_OnRemovePresence(UUID pAgentID)
{
// When a presence is removed, remove the viewer sessions for that agent
IEnumerable<KeyValuePair<string, IVoiceViewerSession>> vSessions;
if (VoiceViewerSession.TryGetViewerSessionByAgentId(pAgentID, out vSessions))
{
foreach(KeyValuePair<string, IVoiceViewerSession> v in vSessions)
{
m_log.DebugFormat("{0} Event_OnRemovePresence: removing viewer session {1}", LogHeader, v.Key);
VoiceViewerSession.RemoveViewerSession(v.Key);
v.Value.Shutdown();
}
}
}
// =====================================================================
// IWebRtcVoiceService
// IWebRtcVoiceService.ProvisionVoiceAccountRequest
public OSDMap ProvisionVoiceAccountRequest(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
OSDMap response = null;
IVoiceViewerSession vSession = null;
if (pRequest.TryGetString("viewer_session", out string viewerSessionId))
{
// request has a viewer session. Use that to find the voice service
if (!VoiceViewerSession.TryGetViewerSession(viewerSessionId, out vSession))
{
m_log.Error($"{0} ProvisionVoiceAccountRequest: viewer session {viewerSessionId} not found");
}
}
else
{
// the request does not have a viewer session. See if it's an initial request
if (pRequest.TryGetString("channel_type", out string channelType))
{
if (channelType == "local")
{
// TODO: check if this userId is making a new session (case that user is reconnecting)
vSession = m_spatialVoiceService.CreateViewerSession(pRequest, pUserID, pSceneID);
VoiceViewerSession.AddViewerSession(vSession);
}
else
{
// TODO: check if this userId is making a new session (case that user is reconnecting)
vSession = m_nonSpatialVoiceService.CreateViewerSession(pRequest, pUserID, pSceneID);
VoiceViewerSession.AddViewerSession(vSession);
}
}
else
{
m_log.Error($"{LogHeader} ProvisionVoiceAccountRequest: no channel_type in request");
}
}
if (vSession is not null)
{
response = vSession.VoiceService.ProvisionVoiceAccountRequest(vSession, pRequest, pUserID, pSceneID);
}
return response;
}
// IWebRtcVoiceService.VoiceSignalingRequest
public OSDMap VoiceSignalingRequest(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
OSDMap response = null;
IVoiceViewerSession vSession = null;
if (pRequest.TryGetString("viewer_session", out string viewerSessionId))
{
// request has a viewer session. Use that to find the voice service
if (VoiceViewerSession.TryGetViewerSession(viewerSessionId, out vSession))
{
response = vSession.VoiceService.VoiceSignalingRequest(vSession, pRequest, pUserID, pSceneID);
}
else
{
m_log.ErrorFormat("{0} VoiceSignalingRequest: viewer session {1} not found", LogHeader, viewerSessionId);
}
}
else
{
m_log.ErrorFormat("{0} VoiceSignalingRequest: no viewer_session in request", LogHeader);
}
return response;
}
// This module should never be called with this signature
public OSDMap ProvisionVoiceAccountRequest(IVoiceViewerSession pVSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
throw new NotImplementedException();
}
// This module should never be called with this signature
public OSDMap VoiceSignalingRequest(IVoiceViewerSession pVSession, OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
throw new NotImplementedException();
}
public IVoiceViewerSession CreateViewerSession(OSDMap pRequest, UUID pUserID, UUID pSceneID)
{
throw new NotImplementedException();
}
}
}

View File

@@ -25,11 +25,21 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Net;
using System.Reflection;
using System.Timers;
using System.Threading;
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Mono.Addins;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Framework.Console;
@@ -39,20 +49,9 @@ using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Timers;
using System.Xml;
using static System.Net.Mime.MediaTypeNames;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PermissionMask = OpenSim.Framework.PermissionMask;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using RegionInfo = OpenSim.Framework.RegionInfo;
namespace OpenSim.ApplicationPlugins.RemoteController
@@ -132,14 +131,13 @@ namespace OpenSim.ApplicationPlugins.RemoteController
m_httpServer = MainServer.GetHttpServer((uint)port,ipaddr);
Dictionary<string, XmlRpcMethod> availableMethods = new Dictionary<string, XmlRpcMethod>();
availableMethods["admin_alert_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAlertUserMethod);
availableMethods["admin_broadcast"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAlertMethod);
availableMethods["admin_create_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateRegionMethod);
availableMethods["admin_delete_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcDeleteRegionMethod);
availableMethods["admin_close_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCloseRegionMethod);
availableMethods["admin_modify_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcModifyRegionMethod);
availableMethods["admin_region_query"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRegionQueryMethod);
availableMethods["admin_shutdown"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcShutdownMethod);
availableMethods["admin_broadcast"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAlertMethod);
availableMethods["admin_dialog"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcDialogMethod);
availableMethods["admin_restart"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRestartMethod);
availableMethods["admin_load_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadHeightmapMethod);
@@ -423,39 +421,6 @@ namespace OpenSim.ApplicationPlugins.RemoteController
m_log.Info("[RADMIN]: Restart Region request complete");
}
private void XmlRpcAlertUserMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
{
//m_log.Info("[RADMIN]: AlertUser request started");
Hashtable responseData = (Hashtable)response.Value;
Hashtable requestData = (Hashtable)request.Params[0];
string agentIdStr = (string)requestData["agent_id"];
string message = (string)requestData["message"];
responseData["accepted"] = true;
if(!UUID.TryParse(agentIdStr, out UUID agentId))
{
responseData["success"] = false;
responseData["error"] = "Invalid agent_id";
m_log.Info($"[RADMIN]: alert to agent got invalid uuid: {agentIdStr}: {message}");
return;
}
if(m_application.SceneManager.TryGetRootScenePresence(agentId, out ScenePresence sp ))
{
sp.ControllingClient.SendAlertMessage(message);
m_log.Info($"[RADMIN]: Sent alert to agent {agentIdStr}: {message}");
responseData["success"] = true;
return;
}
responseData["success"] = false;
responseData["error"] = "User not found or not online";
m_log.Info($"[RADMIN]: Fail to send alert to not found agent {agentIdStr}: {message}");
}
private void XmlRpcAlertMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
{
m_log.Info("[RADMIN]: Alert request started");
@@ -490,7 +455,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
string message = (string)requestData["message"];
string fromuuid = (string)requestData["from"];
m_log.Info($"[RADMIN]: Broadcasting: {message}");
m_log.InfoFormat("[RADMIN]: Broadcasting: {0}", message);
responseData["accepted"] = true;
responseData["success"] = true;
@@ -499,7 +464,8 @@ namespace OpenSim.ApplicationPlugins.RemoteController
delegate(Scene scene)
{
IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
dialogModule?.SendNotificationToUsersInRegion(UUID.Zero, fromuuid, message);
if (dialogModule != null)
dialogModule.SendNotificationToUsersInRegion(UUID.Zero, fromuuid, message);
});
m_log.Info("[RADMIN]: Dialog request complete");
@@ -654,7 +620,6 @@ namespace OpenSim.ApplicationPlugins.RemoteController
m_application.Shutdown();
}
/// <summary>
/// Create a new region.
/// <summary>

View File

@@ -70,7 +70,6 @@ namespace OpenSim.Capabilities.Handlers
List<LLSDFetchInventoryDescendents> folders;
List<UUID> bad_folders = new();
try
{
OSDArray foldersrequested = null;

View File

@@ -27,6 +27,7 @@
using System.Net;
using System.Reflection;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;

View File

@@ -115,7 +115,7 @@ namespace OpenSim.Framework.Capabilities
{
writer.Formatting = Formatting.None;
writer.WriteStartElement(string.Empty, "llsd", string.Empty);
writer.WriteStartElement(String.Empty, "llsd", String.Empty);
LLSDWriteOne(writer, obj);
writer.WriteEndElement();
writer.Flush();
@@ -132,32 +132,32 @@ namespace OpenSim.Framework.Capabilities
{
if (obj == null)
{
writer.WriteStartElement(string.Empty, "undef", string.Empty);
writer.WriteStartElement(String.Empty, "undef", String.Empty);
writer.WriteEndElement();
return;
}
if (obj is string s)
{
writer.WriteStartElement(string.Empty, "string", string.Empty);
writer.WriteStartElement(String.Empty, "string", String.Empty);
writer.WriteString(s);
writer.WriteEndElement();
}
else if (obj is int)
{
writer.WriteStartElement(string.Empty, "integer", string.Empty);
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteString(obj.ToString());
writer.WriteEndElement();
}
else if (obj is double || obj is float)
{
writer.WriteStartElement(string.Empty, "real", string.Empty);
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteString(obj.ToString());
writer.WriteEndElement();
}
else if (obj is bool b)
{
writer.WriteStartElement(string.Empty, "boolean", string.Empty);
writer.WriteStartElement(String.Empty, "boolean", String.Empty);
writer.WriteString(b ? "1" : "0");
writer.WriteEndElement();
}
@@ -167,7 +167,7 @@ namespace OpenSim.Framework.Capabilities
}
else if (obj is UUID u)
{
writer.WriteStartElement(string.Empty, "uuid", string.Empty);
writer.WriteStartElement(String.Empty, "uuid", String.Empty);
writer.WriteString(u.ToString());
writer.WriteEndElement();
}
@@ -185,10 +185,10 @@ namespace OpenSim.Framework.Capabilities
}
else if (obj is Dictionary<string,object> dict)
{
writer.WriteStartElement(string.Empty, "map", string.Empty);
writer.WriteStartElement(String.Empty, "map", String.Empty);
foreach (KeyValuePair<string,object> kvp in dict)
{
writer.WriteStartElement(string.Empty, "key", string.Empty);
writer.WriteStartElement(String.Empty, "key", String.Empty);
writer.WriteString(kvp.Key);
writer.WriteEndElement();
LLSDWriteOne(writer, kvp.Value);
@@ -197,7 +197,7 @@ namespace OpenSim.Framework.Capabilities
}
else if (obj is ArrayList a)
{
writer.WriteStartElement(string.Empty, "array", string.Empty);
writer.WriteStartElement(String.Empty, "array", String.Empty);
foreach (object item in a)
{
LLSDWriteOne(writer, item);

View File

@@ -324,7 +324,7 @@ namespace OpenSim.Data.MySQL
metadata.CreatorID = dbReader["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = Array.Empty<byte>();
metadata.SHA1 = new byte[] { };
retList.Add(metadata);
}

View File

@@ -341,7 +341,6 @@ namespace OpenSim.Data.MySQL
while (reader.Read())
{
SceneObjectPart prim = BuildPrim(reader);
if (reader["Shape"] is DBNull)
prim.Shape = PrimitiveBaseShape.Default;
else

View File

@@ -295,6 +295,7 @@ namespace OpenSim.Data.MySQL
ad.SimName = reader.GetString("simname");
ad.GlobalPos = reader.GetString("posglobal");
ad.ParcelName = reader.GetString("parcelname");
}
}
}

View File

@@ -231,20 +231,27 @@ namespace OpenSim.Data.MySQL
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
byte[] data;
if (m_enableCompression)
{
using MemoryStream inMs = new(asset.Data);
using MemoryStream outputStream = new();
using GZipStream compressionStream = new(outputStream, CompressionMode.Compress);
inMs.CopyTo(compressionStream);
compressionStream.Flush();
data = outputStream.ToArray();
}
else
data = asset.Data;
MemoryStream outputStream = new MemoryStream();
byte[] hash = SHA256.HashData(data);
using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false))
{
// Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue));
// We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream.
compressionStream.Close();
byte[] compressedData = outputStream.ToArray();
asset.Data = compressedData;
}
}
byte[] hash;
using (HashAlgorithm hasher = SHA256.Create())
hash = hasher.ComputeHash(asset.Data);
// m_log.DebugFormat(
// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",
// asset.ID, asset.Name, hash, compressedData.Length);
try
{
@@ -290,7 +297,7 @@ namespace OpenSim.Data.MySQL
dbcon))
{
cmd.Parameters.AddWithValue("?Hash", hash);
cmd.Parameters.AddWithValue("?Data", data);
cmd.Parameters.AddWithValue("?Data", asset.Data);
cmd.ExecuteNonQuery();
}
}

View File

@@ -84,3 +84,14 @@ CREATE TABLE IF NOT EXISTS `usersettings` (
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
commit;
:VERSION 6 # Unicode profiles
ALTER TABLE classifieds CONVERT TO CHARACTER SET utf8;
ALTER TABLE usernotes CONVERT TO CHARACTER SET utf8;
ALTER TABLE userpicks CONVERT TO CHARACTER SET utf8;
ALTER TABLE userprofile CONVERT TO CHARACTER SET utf8;
ALTER TABLE userdata CONVERT TO CHARACTER SET utf8;
commit;

View File

@@ -46,7 +46,7 @@ namespace OpenSim.Data.PGSQL
protected string m_ConnectionString;
protected PGSQLManager m_database; //used for parameter type translation
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>(StringComparer.OrdinalIgnoreCase);
new Dictionary<string, FieldInfo>();
protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
@@ -101,7 +101,7 @@ namespace OpenSim.Data.PGSQL
private void LoadFieldTypes()
{
m_FieldTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
m_FieldTypes = new Dictionary<string, string>();
string query = string.Format(@"select column_name,data_type
from INFORMATION_SCHEMA.COLUMNS
@@ -268,7 +268,7 @@ namespace OpenSim.Data.PGSQL
List<T> result = new List<T>();
if (cmd.Connection == null)
{
cmd.Connection = new NpgsqlConnection(m_ConnectionString);
cmd.Connection = new NpgsqlConnection(m_connectionString);
}
if (cmd.Connection.State == ConnectionState.Closed)
{

View File

@@ -174,7 +174,7 @@ namespace OpenSim.Data.PGSQL
{
return (bool)value;
}
if (valueType == typeof(byte[]))
if (valueType == typeof(Byte[]))
{
return value;
}

View File

@@ -26,9 +26,11 @@
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Text;
using Npgsql;
using log4net;
@@ -105,20 +107,21 @@ namespace OpenSim.Data.PGSQL
return retUA;
}
*/
/*
public UserAccountData Get(UUID principalID, UUID scopeID)
{
UserAccountData ret = new UserAccountData();
ret.Data = new Dictionary<string, string>();
string sql = string.Format(@"select * from {0} where ""PrincipalID"" = :PrincipalID", m_Realm);
string sql = string.Format(@"select * from {0} where ""PrincipalID"" = :principalID", m_Realm);
if (scopeID != UUID.Zero)
sql += @" and ""ScopeID"" = :ScopeID";
sql += @" and ""ScopeID"" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("ScopeID", scopeID));
cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
using (NpgsqlDataReader result = cmd.ExecuteReader())
@@ -156,6 +159,7 @@ namespace OpenSim.Data.PGSQL
return null;
}
public override bool Store(UserAccountData data)
{
if (data.Data.ContainsKey("PrincipalID"))
@@ -265,6 +269,7 @@ namespace OpenSim.Data.PGSQL
}
return false;
}
*/
/*
public UserAccountData[] Get(string[] keys, string[] vals)
{
@@ -293,23 +298,26 @@ namespace OpenSim.Data.PGSQL
return new UserAccountData[0];
string sql = "";
UUID scope_id;
UUID.TryParse(scopeID.ToString(), out scope_id);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
if (words.Length == 1)
{
sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""=:UUIDZero) and (LOWER(""FirstName"" COLLATE ""en_US.utf8"") like LOWER(:search) or LOWER(""LastName"" COLLATE ""en_US.utf8"") like LOWER(:search))", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("ScopeID", scopeID));
cmd.Parameters.Add (m_database.CreateParameter("UUIDZero", UUID.Zero));
sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""=:UUIDZero) and (""FirstName"" ilike :search or ""LastName"" ilike :search)", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("scopeID", (UUID)scope_id));
cmd.Parameters.Add (m_database.CreateParameter("UUIDZero", (UUID)UUID.Zero));
cmd.Parameters.Add(m_database.CreateParameter("search", "%" + words[0] + "%"));
}
else
{
sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""=:UUIDZero) and (LOWER(""FirstName"" COLLATE ""en_US.utf8"") like LOWER(:searchFirst) or LOWER(""LastName"" COLLATE ""en_US.utf8"") like LOWER(:searchLast))", m_Realm);
sql = String.Format(@"select * from {0} where (""ScopeID""=:ScopeID or ""ScopeID""=:UUIDZero) and (""FirstName"" ilike :searchFirst or ""LastName"" ilike :searchLast)", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("searchFirst", "%" + words[0] + "%"));
cmd.Parameters.Add(m_database.CreateParameter("searchLast", "%" + words[1] + "%"));
cmd.Parameters.Add (m_database.CreateParameter("UUIDZero", UUID.Zero));
cmd.Parameters.Add(m_database.CreateParameter("ScopeID", scopeID));
cmd.Parameters.Add (m_database.CreateParameter("UUIDZero", (UUID)UUID.Zero));
cmd.Parameters.Add(m_database.CreateParameter("ScopeID", (UUID)scope_id));
}
cmd.Connection = conn;
cmd.CommandText = sql;
@@ -320,27 +328,7 @@ namespace OpenSim.Data.PGSQL
public UserAccountData[] GetUsersWhere(UUID scopeID, string where)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
// Fix case sensitivity for PostgreSQL column names
where = where.Replace("PrincipalID", "\"PrincipalID\"")
.Replace("ScopeID", "\"ScopeID\"")
.Replace("FirstName", "\"FirstName\"")
.Replace("LastName", "\"LastName\"");
if (!scopeID.IsZero())
{
where = "(\"ScopeID\"=:ScopeID or \"ScopeID\"='00000000-0000-0000-0000-000000000000') and (" + where + ")";
cmd.Parameters.Add(m_database.CreateParameter("ScopeID", scopeID));
}
cmd.CommandText = String.Format("select * from {0} where " + where, m_Realm);
cmd.Connection = conn;
conn.Open();
return DoQuery(cmd);
}
return null;
}
}
}

View File

@@ -32,9 +32,11 @@ using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
using Npgsql;
namespace OpenSim.Data.PGSQL
@@ -56,7 +58,7 @@ namespace OpenSim.Data.PGSQL
private bool m_enableCompression = false;
private PGSQLManager m_database;
private string m_connectionString;
private object m_dbLock = new();
private object m_dbLock = new object();
/// <summary>
/// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock
@@ -210,9 +212,6 @@ namespace OpenSim.Data.PGSQL
{
// m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID);
if (!UUID.TryParse(asset.ID, out UUID asset_id))
return;
lock (m_dbLock)
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
@@ -245,6 +244,7 @@ namespace OpenSim.Data.PGSQL
using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false))
{
// Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue));
// We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream.
compressionStream.Close();
byte[] compressedData = outputStream.ToArray();
@@ -254,9 +254,12 @@ namespace OpenSim.Data.PGSQL
byte[] hash = hasher.ComputeHash(asset.Data);
//m_log.DebugFormat(
// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",
// asset.ID, asset.Name, hash, compressedData.Length);
UUID asset_id;
UUID.TryParse(asset.ID, out asset_id);
// m_log.DebugFormat(
// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",
// asset.ID, asset.Name, hash, compressedData.Length);
try
{
@@ -349,9 +352,6 @@ namespace OpenSim.Data.PGSQL
if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates)
return;
if(!UUID.TryParse(assetMetadata.ID, out UUID asset_id))
return;
lock (m_dbLock)
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString))
@@ -362,11 +362,14 @@ namespace OpenSim.Data.PGSQL
try
{
UUID asset_id;
UUID.TryParse(assetMetadata.ID, out asset_id);
using (cmd)
{
// create unix epoch time
cmd.Parameters.Add(m_database.CreateParameter("ID", asset_id));
cmd.Parameters.Add(m_database.CreateParameter("AccessTime", (int)Utils.DateTimeToUnixTime(now)));
cmd.Parameters.Add(m_database.CreateParameter("id", asset_id));
cmd.Parameters.Add(m_database.CreateParameter("access_time", (int)Utils.DateTimeToUnixTime(now)));
cmd.ExecuteNonQuery();
}
}
@@ -404,7 +407,7 @@ namespace OpenSim.Data.PGSQL
{
if (dbReader.Read())
{
// m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid);
// m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid);
exists = true;
}
}
@@ -428,7 +431,7 @@ namespace OpenSim.Data.PGSQL
public bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return [];
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
@@ -464,7 +467,7 @@ namespace OpenSim.Data.PGSQL
/// <returns>true if it exists, false otherwise.</returns>
public bool ExistsAsset(UUID uuid)
{
// m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid);
// m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid);
bool assetExists = false;
@@ -475,7 +478,7 @@ namespace OpenSim.Data.PGSQL
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT id FROM XAssetsMeta WHERE id=:ID", dbcon))
{
cmd.Parameters.Add(m_database.CreateParameter("ID", uuid));
cmd.Parameters.Add(m_database.CreateParameter("id", uuid));
try
{
@@ -490,7 +493,7 @@ namespace OpenSim.Data.PGSQL
}
catch (Exception e)
{
m_log.Error($"[XASSETS DB]: PGSql failure fetching asset {uuid}", e);
m_log.Error(string.Format("[XASSETS DB]: PGSql failure fetching asset {0}", uuid), e);
}
}
}
@@ -519,9 +522,9 @@ namespace OpenSim.Data.PGSQL
dbcon.Open();
using(NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT name, description, access_time, ""AssetType"", temporary, id, asset_flags, creatorid
FROM XAssetsMeta
LIMIT :start, :count", dbcon))
LIMIT :start, :count",dbcon))
{
cmd.Parameters.Add(m_database.CreateParameter("start", start));
cmd.Parameters.Add(m_database.CreateParameter("start",start));
cmd.Parameters.Add(m_database.CreateParameter("count", count));
try
@@ -571,7 +574,7 @@ namespace OpenSim.Data.PGSQL
using (NpgsqlCommand cmd = new NpgsqlCommand(@"delete from XAssetsMeta where id=:ID", dbcon))
{
cmd.Parameters.Add(m_database.CreateParameter("ID", id));
cmd.Parameters.Add(m_database.CreateParameter(id, id));
cmd.ExecuteNonQuery();
}

View File

@@ -26,23 +26,42 @@
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Reflection;
using System.Text;
using log4net;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLXInventoryData : IXInventoryData
{
// private static readonly ILog m_log = LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
private PGSQLFolderHandler m_Folders;
private PGSQLItemHandler m_Items;
public PGSQLXInventoryData(string conn, string realm)
{
m_Folders = new PGSQLFolderHandler(conn, "inventoryfolders", "InventoryStore");
m_Items = new PGSQLItemHandler(conn, "inventoryitems", string.Empty);
m_Folders = new PGSQLFolderHandler(
conn, "inventoryfolders", "InventoryStore");
m_Items = new PGSQLItemHandler(
conn, "inventoryitems", String.Empty);
}
public static UUID str2UUID(string strUUID)
{
UUID newUUID = UUID.Zero;
UUID.TryParse(strUUID, out newUUID);
return newUUID;
}
public XInventoryFolder[] GetFolder(string field, string val)
@@ -109,7 +128,7 @@ namespace OpenSim.Data.PGSQL
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
return m_Items.GetActiveGestures(principalID);
return m_Items.GetActiveGestures(principalID.ToString());
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
@@ -125,14 +144,9 @@ namespace OpenSim.Data.PGSQL
{
}
public bool MoveItem(string idstr, string newParentstr)
public bool MoveItem(string id, string newParent)
{
if(!UUID.TryParse(idstr, out UUID id))
return false;
if(!UUID.TryParse(newParentstr, out UUID newParent))
return false;
XInventoryItem[] retrievedItems = Get(["inventoryID"], [idstr]);
XInventoryItem[] retrievedItems = Get(new string[] { "inventoryID" }, new string[] { id });
if (retrievedItems.Length == 0)
return false;
@@ -142,7 +156,7 @@ namespace OpenSim.Data.PGSQL
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = $"update {m_Realm} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID";
cmd.CommandText = String.Format(@"update {0} set ""parentFolderID"" = :ParentFolderID where ""inventoryID"" = :InventoryID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("ParentFolderID", newParent));
cmd.Parameters.Add(m_database.CreateParameter("InventoryID", id ));
cmd.Connection = conn;
@@ -158,20 +172,19 @@ namespace OpenSim.Data.PGSQL
return true;
}
public XInventoryItem[] GetActiveGestures(string principalID)
{
return UUID.TryParse(principalID, out UUID princID) ? GetActiveGestures(princID) : [];
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
public XInventoryItem[] GetActiveGestures(string principalID)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
// cmd.CommandText = String.Format(@"select * from inventoryitems where ""avatarID"" = :uuid and ""assetType"" = :type and ""flags"" = 1", m_Realm);
// cmd.CommandText = String.Format(@"select * from inventoryitems where ""avatarID"" = :uuid and ""assetType"" = :type and ""flags"" = 1", m_Realm);
cmd.CommandText = "select * from inventoryitems where avatarID = :uuid and assetType = :type and flags = 1";
cmd.CommandText = String.Format(@"select * from inventoryitems where ""avatarID"" = :uuid and ""assetType"" = :type and ""flags"" = 1");
UUID princID = UUID.Zero;
UUID.TryParse(principalID, out princID);
cmd.Parameters.Add(m_database.CreateParameter("uuid", principalID));
cmd.Parameters.Add(m_database.CreateParameter("type", (int)AssetType.Gesture));
@@ -195,11 +208,11 @@ namespace OpenSim.Data.PGSQL
and ""assetID"" = :AssetID
group by ""assetID"" ", m_Realm);
*/
cmd.CommandText = @"select bit_or(inventoryCurrentPermissions) as inventoryCurrentPermissions
cmd.CommandText = String.Format(@"select bit_or(""inventoryCurrentPermissions"") as ""inventoryCurrentPermissions""
from inventoryitems
where avatarID::uuid = :PrincipalID
and assetID::uuid = :AssetID
group by assetID";
where ""avatarID""::uuid = :PrincipalID
and ""assetID""::uuid = :AssetID
group by ""assetID"" ");
cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("AssetID", assetID));
@@ -242,13 +255,7 @@ namespace OpenSim.Data.PGSQL
public bool MoveFolder(string id, string newParentFolderID)
{
if(!UUID.TryParse(id, out UUID foldID))
return false;
if(!UUID.TryParse(newParentFolderID, out UUID newPar))
return false;
XInventoryFolder[] folders = Get(["folderID"], [id]);
XInventoryFolder[] folders = Get(new string[] { "folderID" }, new string[] { id });
if (folders.Length == 0)
return false;
@@ -259,8 +266,13 @@ namespace OpenSim.Data.PGSQL
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
UUID foldID = UUID.Zero;
UUID.TryParse(id, out foldID);
cmd.CommandText = $"update {m_Realm} set parentFolderID = :ParentFolderID where folderID = :folderID";
UUID newPar = UUID.Zero;
UUID.TryParse(newParentFolderID, out newPar);
cmd.CommandText = String.Format(@"update {0} set ""parentFolderID"" = :ParentFolderID where ""folderID"" = :folderID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("ParentFolderID", newPar));
cmd.Parameters.Add(m_database.CreateParameter("folderID", foldID));
cmd.Connection = conn;
@@ -299,19 +311,20 @@ namespace OpenSim.Data.PGSQL
protected bool IncrementFolderVersion(string folderID)
{
//m_log.DebugFormat("[PGSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
//Util.PrintCallStack();
// m_log.DebugFormat("[PGSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
// Util.PrintCallStack();
if(!UUID.TryParse(folderID, out UUID foldID))
return false;
string sql = @"update inventoryfolders set version=version+1 where folderID = :folderID";
string sql = @"update inventoryfolders set version=version+1 where ""folderID"" = :folderID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
UUID foldID = UUID.Zero;
UUID.TryParse(folderID, out foldID);
conn.Open();
cmd.Parameters.Add( m_database.CreateParameter("folderID", foldID) );
try

View File

@@ -139,7 +139,7 @@ CREATE TABLE Tmp_inventoryitems
INSERT INTO Tmp_inventoryitems ("inventoryID", "assetID", "assetType", "parentFolderID", "avatarID", "inventoryName", "inventoryDescription", "inventoryNextPermissions", "inventoryCurrentPermissions", "invType", "creatorID", "inventoryBasePermissions", "inventoryEveryOnePermissions", "salePrice", "SaleType", "creationDate", "groupID", "groupOwned", "flags", "inventoryGroupPermissions")
SELECT cast("inventoryID" as uuid), cast("assetID" as uuid), "assetType", cast("parentFolderID" as uuid), cast("avatarID" as uuid), "inventoryName", "inventoryDescription", "inventoryNextPermissions", "inventoryCurrentPermissions", "invType", cast("creatorID" as uuid), "inventoryBasePermissions", "inventoryEveryOnePermissions", "salePrice", "saleType", "creationDate", cast("groupID" as uuid), "groupOwned", "flags", "inventoryGroupPermissions"
SELECT cast("inventoryID" as uuid), cast("assetID" as uuid), "assetType", cast("parentFolderID" as uuid), cast("avatarID" as uuid), "inventoryName", "inventoryDescription", "inventoryNextPermissions", "inventoryCurrentPermissions", "invType", cast("creatorID" as uuid), "inventoryBasePermissions", "inventoryEveryOnePermissions", "salePrice", "SaleType", "creationDate", cast("groupID" as uuid), "groupOwned", "flags", "inventoryGroupPermissions"
FROM inventoryitems ;
DROP TABLE inventoryitems;

View File

@@ -89,16 +89,14 @@ CREATE TABLE IF NOT EXISTS userdata (
commit;
:VERSION 4 # -------------------------------
:VERSION 3 # -------------------------------
begin;
CREATE TABLE IF NOT EXISTS usersettings (
useruuid char(36) NOT NULL,
imviaemail binary(1) NOT NULL,
visible binary(1) NOT NULL,
email varchar(254) NOT NULL,
PRIMARY KEY (useruuid)
);
)
commit;

View File

@@ -31,7 +31,11 @@ using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{

View File

@@ -30,7 +30,11 @@ using System.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
@@ -51,7 +55,7 @@ namespace OpenSim.Data.SQLite
private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID";
private const string assetSelect = "select * from assets";
private SQLiteConnection m_conn;
private SqliteConnection m_conn;
protected virtual Assembly Assembly
{
@@ -77,13 +81,13 @@ namespace OpenSim.Data.SQLite
/// <param name="dbconnect">connect string</param>
override public void Initialise(string dbconnect)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
if (dbconnect.Length == 0)
{
dbconnect = "URI=file:Asset.db";
dbconnect = "URI=file:Asset.db,version=3";
}
m_conn = new SQLiteConnection(dbconnect);
m_conn = new SqliteConnection(dbconnect);
m_conn.Open();
Migration m = new Migration(m_conn, Assembly, "AssetStore");
@@ -101,9 +105,9 @@ namespace OpenSim.Data.SQLite
{
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(SelectAssetSQL, m_conn))
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", uuid.ToString()));
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
@@ -153,17 +157,17 @@ namespace OpenSim.Data.SQLite
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(UpdateAssetSQL, m_conn))
using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Name", assetName));
cmd.Parameters.Add(new SQLiteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SQLiteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SQLiteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SQLiteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SQLiteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SQLiteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SQLiteParameter(":Data", asset.Data));
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", assetName));
cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
return true;
@@ -174,17 +178,17 @@ namespace OpenSim.Data.SQLite
{
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(InsertAssetSQL, m_conn))
using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Name", assetName));
cmd.Parameters.Add(new SQLiteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SQLiteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SQLiteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SQLiteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SQLiteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SQLiteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SQLiteParameter(":Data", asset.Data));
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", assetName));
cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
return true;
@@ -227,7 +231,7 @@ namespace OpenSim.Data.SQLite
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(sql, m_conn))
using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
{
using (IDataReader reader = cmd.ExecuteReader())
{
@@ -303,10 +307,10 @@ namespace OpenSim.Data.SQLite
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(SelectAssetMetadataSQL, m_conn))
using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":start", start));
cmd.Parameters.Add(new SQLiteParameter(":count", count));
cmd.Parameters.Add(new SqliteParameter(":start", start));
cmd.Parameters.Add(new SqliteParameter(":count", count));
using (IDataReader reader = cmd.ExecuteReader())
{
@@ -355,7 +359,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
override public void Initialise()
{
Initialise("URI=file:Asset.db");
Initialise("URI=file:Asset.db,version=3");
}
/// <summary>
@@ -376,9 +380,9 @@ namespace OpenSim.Data.SQLite
{
lock (this)
{
using (SQLiteCommand cmd = new SQLiteCommand(DeleteAssetSQL, m_conn))
using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":UUID", uuid.ToString()));
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
cmd.ExecuteNonQuery();
}
}

View File

@@ -34,7 +34,11 @@ using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -46,7 +50,7 @@ namespace OpenSim.Data.SQLite
private List<string> m_ColumnNames;
private int m_LastExpire;
protected static SQLiteConnection m_Connection;
protected static SqliteConnection m_Connection;
private static bool m_initialized = false;
protected virtual Assembly Assembly
@@ -61,9 +65,9 @@ namespace OpenSim.Data.SQLite
if (!m_initialized)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
m_Connection = new SQLiteConnection(connectionString);
m_Connection = new SqliteConnection(connectionString);
m_Connection.Open();
Migration m = new Migration(m_Connection, Assembly, "AuthStore");
@@ -79,9 +83,9 @@ namespace OpenSim.Data.SQLite
ret.Data = new Dictionary<string, object>();
IDataReader result;
using (SQLiteCommand cmd = new SQLiteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"))
using (SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"))
{
cmd.Parameters.Add(new SQLiteParameter(":PrincipalID", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
result = ExecuteReader(cmd, m_Connection);
}
@@ -133,7 +137,7 @@ namespace OpenSim.Data.SQLite
foreach (object o in data.Data.Values)
values[i++] = o.ToString();
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
if (Get(data.PrincipalID) != null)
{
@@ -146,13 +150,13 @@ namespace OpenSim.Data.SQLite
if (!first)
update += ", ";
update += "`" + field + "` = :" + field;
cmd.Parameters.Add(new SQLiteParameter(":" + field, data.Data[field]));
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
first = false;
}
update += " where UUID = :UUID";
cmd.Parameters.Add(new SQLiteParameter(":UUID", data.PrincipalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
cmd.CommandText = update;
try
@@ -176,9 +180,9 @@ namespace OpenSim.Data.SQLite
String.Join("`, `", fields) +
"`) values (:UUID, :" + String.Join(", :", fields) + ")";
cmd.Parameters.Add(new SQLiteParameter(":UUID", data.PrincipalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
foreach (string field in fields)
cmd.Parameters.Add(new SQLiteParameter(":" + field, data.Data[field]));
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
cmd.CommandText = insert;
@@ -202,7 +206,7 @@ namespace OpenSim.Data.SQLite
public bool SetDataItem(UUID principalID, string item, string value)
{
using (SQLiteCommand cmd = new SQLiteCommand("update `" + m_Realm +
using (SqliteCommand cmd = new SqliteCommand("update `" + m_Realm +
"` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
@@ -217,7 +221,7 @@ namespace OpenSim.Data.SQLite
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (SQLiteCommand cmd = new SQLiteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() +
using (SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() +
"', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
@@ -232,7 +236,7 @@ namespace OpenSim.Data.SQLite
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (SQLiteCommand cmd = new SQLiteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() +
using (SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() +
" minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
@@ -244,7 +248,7 @@ namespace OpenSim.Data.SQLite
private void DoExpire()
{
using (SQLiteCommand cmd = new SQLiteCommand("delete from tokens where validity < datetime('now', 'localtime')"))
using (SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"))
ExecuteNonQuery(cmd, m_Connection);
m_LastExpire = System.Environment.TickCount;

View File

@@ -33,7 +33,11 @@ using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -52,7 +56,7 @@ namespace OpenSim.Data.SQLite
public bool Delete(UUID principalID, string name)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm);
cmd.Parameters.AddWithValue(":PrincipalID", principalID.ToString());

View File

@@ -30,8 +30,11 @@ using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
@@ -43,7 +46,7 @@ namespace OpenSim.Data.SQLite
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SQLiteConnection m_connection;
private SqliteConnection m_connection;
private string m_connectionString;
private FieldInfo[] m_Fields;
@@ -66,13 +69,13 @@ namespace OpenSim.Data.SQLite
public void Initialise(string connectionString)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
m_connectionString = connectionString;
m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);
m_connection = new SQLiteConnection(m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Migration m = new Migration(m_connection, Assembly, "EstateStore");
@@ -100,7 +103,7 @@ namespace OpenSim.Data.SQLite
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = :RegionID";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
@@ -109,7 +112,7 @@ namespace OpenSim.Data.SQLite
}
}
private EstateSettings DoLoad(SQLiteCommand cmd, UUID regionID, bool create)
private EstateSettings DoLoad(SqliteCommand cmd, UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
@@ -118,7 +121,7 @@ namespace OpenSim.Data.SQLite
{
r = cmd.ExecuteReader();
}
catch (SQLiteException)
catch (SqliteException)
{
m_log.Error("[SQLITE]: There was an issue loading the estate settings. This can happen the first time running OpenSimulator with CSharpSqlite the first time. OpenSimulator will probably crash, restart it and it should be good to go.");
}
@@ -185,7 +188,7 @@ namespace OpenSim.Data.SQLite
{
List<string> names = new List<string>(FieldList);
using (SQLiteCommand cmd = m_connection.CreateCommand())
using (SqliteCommand cmd = m_connection.CreateCommand())
{
if (es.EstateID < 100)
{
@@ -235,7 +238,7 @@ namespace OpenSim.Data.SQLite
foreach (string f in fields)
terms.Add(f+" = :"+f);
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "update estate_settings set " + String.Join(", ", terms.ToArray()) + " where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
@@ -270,7 +273,7 @@ namespace OpenSim.Data.SQLite
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "select * from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
@@ -294,7 +297,7 @@ namespace OpenSim.Data.SQLite
private void SaveBanList(EstateSettings es)
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "delete from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
@@ -320,7 +323,7 @@ namespace OpenSim.Data.SQLite
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "delete from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
@@ -347,7 +350,7 @@ namespace OpenSim.Data.SQLite
List<UUID> uuids = new List<UUID>();
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID);
@@ -373,7 +376,7 @@ namespace OpenSim.Data.SQLite
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
@@ -400,7 +403,7 @@ namespace OpenSim.Data.SQLite
string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateName", search);
@@ -424,7 +427,7 @@ namespace OpenSim.Data.SQLite
string sql = "select EstateID from estate_settings";
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
@@ -447,7 +450,7 @@ namespace OpenSim.Data.SQLite
string sql = "select EstateID from estate_settings where estate_settings.EstateOwner = :EstateOwner";
IDataReader r;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateOwner", ownerID);
@@ -466,10 +469,10 @@ namespace OpenSim.Data.SQLite
public bool LinkRegion(UUID regionID, int estateID)
{
using(SQLiteTransaction transaction = m_connection.BeginTransaction())
using(SqliteTransaction transaction = m_connection.BeginTransaction())
{
// Delete any existing estate mapping for this region.
using(SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "delete from estate_map where RegionID = :RegionID";
cmd.Transaction = transaction;
@@ -478,7 +481,7 @@ namespace OpenSim.Data.SQLite
cmd.ExecuteNonQuery();
}
using(SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Transaction = transaction;

View File

@@ -31,7 +31,11 @@ using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -40,11 +44,11 @@ namespace OpenSim.Data.SQLite
/// </summary>
public class SQLiteFramework
{
protected object m_lockObject = new Object();
protected Object m_lockObject = new Object();
protected SQLiteFramework(string connectionString)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
}
//////////////////////////////////////////////////////////////
@@ -52,10 +56,17 @@ namespace OpenSim.Data.SQLite
// All non queries are funneled through one connection
// to increase performance a little
//
protected int ExecuteNonQuery(SQLiteCommand cmd, SQLiteConnection connection)
protected int ExecuteNonQuery(SqliteCommand cmd, SqliteConnection connection)
{
lock (connection)
{
/*
SqliteConnection newConnection =
(SqliteConnection)((ICloneable)connection).Clone();
newConnection.Open();
cmd.Connection = newConnection;
*/
cmd.Connection = connection;
//Console.WriteLine("XXX " + cmd.CommandText);
@@ -63,12 +74,12 @@ namespace OpenSim.Data.SQLite
}
}
protected IDataReader ExecuteReader(SQLiteCommand cmd, SQLiteConnection connection)
protected IDataReader ExecuteReader(SqliteCommand cmd, SqliteConnection connection)
{
lock (connection)
{
//SQLiteConnection newConnection =
// (SQLiteConnection)((ICloneable)connection).Clone();
//SqliteConnection newConnection =
// (SqliteConnection)((ICloneable)connection).Clone();
//newConnection.Open();
//cmd.Connection = newConnection;

View File

@@ -31,7 +31,11 @@ using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -49,7 +53,7 @@ namespace OpenSim.Data.SQLite
public FriendsData[] GetFriends(string userID)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("select a.*,case when b.Flags is null then -1 else b.Flags end as TheirFlags from {0} as a left join {0} as b on a.PrincipalID = b.Friend and a.Friend = b.PrincipalID where a.PrincipalID = :PrincipalID", m_Realm);
cmd.Parameters.AddWithValue(":PrincipalID", userID.ToString());
@@ -65,7 +69,7 @@ namespace OpenSim.Data.SQLite
public override bool Delete(string principalID, string friend)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("delete from {0} where PrincipalID = :PrincipalID and Friend = :Friend", m_Realm);
cmd.Parameters.AddWithValue(":PrincipalID", principalID.ToString());

View File

@@ -30,8 +30,11 @@ using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
@@ -49,7 +52,7 @@ namespace OpenSim.Data.SQLite
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected static SQLiteConnection m_Connection;
protected static SqliteConnection m_Connection;
private static bool m_initialized;
protected virtual Assembly Assembly
@@ -64,14 +67,14 @@ namespace OpenSim.Data.SQLite
if (!m_initialized)
{
m_Connection = new SQLiteConnection(connectionString);
m_Connection = new SqliteConnection(connectionString);
//Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString));
m_Connection.Open();
if (storeName != String.Empty)
{
//SQLiteConnection newConnection =
// (SQLiteConnection)((ICloneable)m_Connection).Clone();
//SqliteConnection newConnection =
// (SqliteConnection)((ICloneable)m_Connection).Clone();
//newConnection.Open();
//Migration m = new Migration(newConnection, Assembly, storeName);
@@ -129,11 +132,11 @@ namespace OpenSim.Data.SQLite
List<string> terms = new List<string>();
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SQLiteParameter(":" + fields[i], keys[i]));
cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
terms.Add("`" + fields[i] + "` = :" + fields[i]);
}
@@ -148,7 +151,7 @@ namespace OpenSim.Data.SQLite
}
}
protected T[] DoQuery(SQLiteCommand cmd)
protected T[] DoQuery(SqliteCommand cmd)
{
IDataReader reader = ExecuteReader(cmd, m_Connection);
if (reader == null)
@@ -212,7 +215,7 @@ namespace OpenSim.Data.SQLite
public virtual T[] Get(string where)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
@@ -225,7 +228,7 @@ namespace OpenSim.Data.SQLite
public virtual bool Store(T row)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
string query = "";
List<String> names = new List<String>();
@@ -235,7 +238,7 @@ namespace OpenSim.Data.SQLite
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
cmd.Parameters.Add(new SQLiteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
@@ -247,7 +250,7 @@ namespace OpenSim.Data.SQLite
{
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
cmd.Parameters.Add(new SQLiteParameter(":" + kvp.Key, kvp.Value));
cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
}
}
@@ -274,11 +277,11 @@ namespace OpenSim.Data.SQLite
List<string> terms = new List<string>();
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SQLiteParameter(":" + fields[i], keys[i]));
cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
terms.Add("`" + fields[i] + "` = :" + fields[i]);
}

View File

@@ -33,7 +33,7 @@ using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
using Mono.Data.Sqlite;
namespace OpenSim.Data.SQLite
{
@@ -69,7 +69,7 @@ namespace OpenSim.Data.SQLite
public void DeleteOld()
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("delete from {0} where TMStamp < datetime('now', '-2 day') ", m_Realm);

View File

@@ -31,7 +31,11 @@ using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -50,7 +54,7 @@ namespace OpenSim.Data.SQLite
public bool Delete(UUID agentID, UUID muteID, string muteName)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = "delete from MuteList where `AgentID` = :AgentID and `MuteID` = :MuteID and `MuteName` = :MuteName";

View File

@@ -32,8 +32,11 @@ using System.Drawing;
using System.IO;
using System.Reflection;
using log4net;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
@@ -63,18 +66,18 @@ namespace OpenSim.Data.SQLite
private const string regionSpawnPointsSelect = "select * from spawn_points";
private DataSet ds;
private SQLiteDataAdapter primDa;
private SQLiteDataAdapter shapeDa;
private SQLiteDataAdapter itemsDa;
private SQLiteDataAdapter terrainDa;
private SQLiteDataAdapter landDa;
private SQLiteDataAdapter landAccessListDa;
private SQLiteDataAdapter regionSettingsDa;
private SQLiteDataAdapter regionWindlightDa;
private SQLiteDataAdapter regionEnvironmentDa;
private SQLiteDataAdapter regionSpawnPointsDa;
private SqliteDataAdapter primDa;
private SqliteDataAdapter shapeDa;
private SqliteDataAdapter itemsDa;
private SqliteDataAdapter terrainDa;
private SqliteDataAdapter landDa;
private SqliteDataAdapter landAccessListDa;
private SqliteDataAdapter regionSettingsDa;
private SqliteDataAdapter regionWindlightDa;
private SqliteDataAdapter regionEnvironmentDa;
private SqliteDataAdapter regionSpawnPointsDa;
private SQLiteConnection m_conn;
private SqliteConnection m_conn;
private String m_connectionString;
protected virtual Assembly Assembly
@@ -110,46 +113,46 @@ namespace OpenSim.Data.SQLite
{
try
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
m_connectionString = connectionString;
ds = new DataSet("Region");
m_log.Info("[SQLITE REGION DB]: Sqlite - connecting: " + connectionString);
m_conn = new SQLiteConnection(m_connectionString);
m_conn = new SqliteConnection(m_connectionString);
m_conn.Open();
SQLiteCommand primSelectCmd = new SQLiteCommand(primSelect, m_conn);
primDa = new SQLiteDataAdapter(primSelectCmd);
SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn);
primDa = new SqliteDataAdapter(primSelectCmd);
SQLiteCommand shapeSelectCmd = new SQLiteCommand(shapeSelect, m_conn);
shapeDa = new SQLiteDataAdapter(shapeSelectCmd);
// SQLiteCommandBuilder shapeCb = new SQLiteCommandBuilder(shapeDa);
SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn);
shapeDa = new SqliteDataAdapter(shapeSelectCmd);
// SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa);
SQLiteCommand itemsSelectCmd = new SQLiteCommand(itemsSelect, m_conn);
itemsDa = new SQLiteDataAdapter(itemsSelectCmd);
SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn);
itemsDa = new SqliteDataAdapter(itemsSelectCmd);
SQLiteCommand terrainSelectCmd = new SQLiteCommand(terrainSelect, m_conn);
terrainDa = new SQLiteDataAdapter(terrainSelectCmd);
SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn);
terrainDa = new SqliteDataAdapter(terrainSelectCmd);
SQLiteCommand landSelectCmd = new SQLiteCommand(landSelect, m_conn);
landDa = new SQLiteDataAdapter(landSelectCmd);
SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn);
landDa = new SqliteDataAdapter(landSelectCmd);
SQLiteCommand landAccessListSelectCmd = new SQLiteCommand(landAccessListSelect, m_conn);
landAccessListDa = new SQLiteDataAdapter(landAccessListSelectCmd);
SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn);
landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd);
SQLiteCommand regionSettingsSelectCmd = new SQLiteCommand(regionSettingsSelect, m_conn);
regionSettingsDa = new SQLiteDataAdapter(regionSettingsSelectCmd);
SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn);
regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd);
SQLiteCommand regionWindlightSelectCmd = new SQLiteCommand(regionWindlightSelect, m_conn);
regionWindlightDa = new SQLiteDataAdapter(regionWindlightSelectCmd);
SqliteCommand regionWindlightSelectCmd = new SqliteCommand(regionWindlightSelect, m_conn);
regionWindlightDa = new SqliteDataAdapter(regionWindlightSelectCmd);
SQLiteCommand regionEnvironmentSelectCmd = new SQLiteCommand(regionEnvironmentSelect, m_conn);
regionEnvironmentDa = new SQLiteDataAdapter(regionEnvironmentSelectCmd);
SqliteCommand regionEnvironmentSelectCmd = new SqliteCommand(regionEnvironmentSelect, m_conn);
regionEnvironmentDa = new SqliteDataAdapter(regionEnvironmentSelectCmd);
SQLiteCommand regionSpawnPointsSelectCmd = new SQLiteCommand(regionSpawnPointsSelect, m_conn);
regionSpawnPointsDa = new SQLiteDataAdapter(regionSpawnPointsSelectCmd);
SqliteCommand regionSpawnPointsSelectCmd = new SqliteCommand(regionSpawnPointsSelect, m_conn);
regionSpawnPointsDa = new SqliteDataAdapter(regionSpawnPointsSelectCmd);
// This actually does the roll forward assembly stuff
Migration m = new Migration(m_conn, Assembly, "RegionStore");
@@ -401,25 +404,25 @@ namespace OpenSim.Data.SQLite
// remove region's spawnpoints
using (
SQLiteCommand cmd =
new SQLiteCommand("delete from spawn_points where RegionID=:RegionID",
SqliteCommand cmd =
new SqliteCommand("delete from spawn_points where RegionID=:RegionID",
m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionID", rs.RegionUUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":RegionID", rs.RegionUUID.ToString()));
cmd.ExecuteNonQuery();
}
}
foreach (SpawnPoint sp in rs.SpawnPoints())
{
using (SQLiteCommand cmd = new SQLiteCommand("insert into spawn_points(RegionID, Yaw, Pitch, Distance)" +
using (SqliteCommand cmd = new SqliteCommand("insert into spawn_points(RegionID, Yaw, Pitch, Distance)" +
"values ( :RegionID, :Yaw, :Pitch, :Distance)", m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionID", rs.RegionUUID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Yaw", sp.Yaw));
cmd.Parameters.Add(new SQLiteParameter(":Pitch", sp.Pitch));
cmd.Parameters.Add(new SQLiteParameter(":Distance", sp.Distance));
cmd.Parameters.Add(new SqliteParameter(":RegionID", rs.RegionUUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Yaw", sp.Yaw));
cmd.Parameters.Add(new SqliteParameter(":Pitch", sp.Pitch));
cmd.Parameters.Add(new SqliteParameter(":Distance", sp.Distance));
cmd.ExecuteNonQuery();
}
}
@@ -666,6 +669,8 @@ namespace OpenSim.Data.SQLite
createdObjects.Add(group.UUID, group);
retvals.Add(group);
LoadItems(prim);
}
}
catch (Exception e)
@@ -762,9 +767,9 @@ namespace OpenSim.Data.SQLite
{
lock (ds)
{
using (SQLiteCommand cmd = new SQLiteCommand("delete from terrain where RegionUUID=:RegionUUID", m_conn))
using (SqliteCommand cmd = new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID", m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
cmd.ExecuteNonQuery();
}
@@ -779,11 +784,11 @@ namespace OpenSim.Data.SQLite
m_log.DebugFormat("{0} Storing terrain format {1}", LogHeader, terrainDBRevision);
using (SQLiteCommand cmd = new SQLiteCommand(sql, m_conn))
using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Revision", terrainDBRevision));
cmd.Parameters.Add(new SQLiteParameter(":Heightfield", terrainDBblob));
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Revision", terrainDBRevision));
cmd.Parameters.Add(new SqliteParameter(":Heightfield", terrainDBblob));
cmd.ExecuteNonQuery();
}
}
@@ -799,9 +804,9 @@ namespace OpenSim.Data.SQLite
lock (ds)
{
using (
SQLiteCommand cmd = new SQLiteCommand("delete from bakedterrain where RegionUUID=:RegionUUID", m_conn))
SqliteCommand cmd = new SqliteCommand("delete from bakedterrain where RegionUUID=:RegionUUID", m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
cmd.ExecuteNonQuery();
}
@@ -816,11 +821,11 @@ namespace OpenSim.Data.SQLite
m_log.DebugFormat("{0} Storing bakedterrain format {1}", LogHeader, terrainDBRevision);
using (SQLiteCommand cmd = new SQLiteCommand(sql, m_conn))
using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":Revision", terrainDBRevision));
cmd.Parameters.Add(new SQLiteParameter(":Heightfield", terrainDBblob));
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Revision", terrainDBRevision));
cmd.Parameters.Add(new SqliteParameter(":Heightfield", terrainDBblob));
cmd.ExecuteNonQuery();
}
}
@@ -850,9 +855,9 @@ namespace OpenSim.Data.SQLite
String sql = "select RegionUUID, Revision, Heightfield from terrain" +
" where RegionUUID=:RegionUUID order by Revision desc";
using (SQLiteCommand cmd = new SQLiteCommand(sql, m_conn))
using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
using (IDataReader row = cmd.ExecuteReader())
{
@@ -885,9 +890,9 @@ namespace OpenSim.Data.SQLite
String sql = "select RegionUUID, Revision, Heightfield from bakedterrain" +
" where RegionUUID=:RegionUUID";
using (SQLiteCommand cmd = new SQLiteCommand(sql, m_conn))
using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
{
cmd.Parameters.Add(new SQLiteParameter(":RegionUUID", regionID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
using (IDataReader row = cmd.ExecuteReader())
{
@@ -911,15 +916,15 @@ namespace OpenSim.Data.SQLite
// Can't use blanket SQL statements when using SqlAdapters unless you re-read the data into the adapter
// after you're done.
// replaced below code with the SqliteAdapter version.
//using (SQLiteCommand cmd = new SQLiteCommand("delete from land where UUID=:UUID", m_conn))
//using (SqliteCommand cmd = new SqliteCommand("delete from land where UUID=:UUID", m_conn))
//{
// cmd.Parameters.Add(new SQLiteParameter(":UUID", globalID.ToString()));
// cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString()));
// cmd.ExecuteNonQuery();
//}
//using (SQLiteCommand cmd = new SQLiteCommand("delete from landaccesslist where LandUUID=:UUID", m_conn))
//using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:UUID", m_conn))
//{
// cmd.Parameters.Add(new SQLiteParameter(":UUID", globalID.ToString()));
// cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString()));
// cmd.ExecuteNonQuery();
//}
@@ -968,9 +973,9 @@ namespace OpenSim.Data.SQLite
}
// I know this caused someone issues before, but OpenSim is unusable if we leave this stuff around
//using (SQLiteCommand cmd = new SQLiteCommand("delete from landaccesslist where LandUUID=:LandUUID", m_conn))
//using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:LandUUID", m_conn))
//{
// cmd.Parameters.Add(new SQLiteParameter(":LandUUID", parcel.LandData.GlobalID.ToString()));
// cmd.Parameters.Add(new SqliteParameter(":LandUUID", parcel.LandData.GlobalID.ToString()));
// cmd.ExecuteNonQuery();
// }
@@ -1048,7 +1053,7 @@ namespace OpenSim.Data.SQLite
regionSettingsDa.Update(ds, "regionsettings");
regionWindlightDa.Update(ds, "regionwindlight");
}
catch (SQLiteException SqlEx)
catch (SqliteException SqlEx)
{
throw new Exception(
"There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!",
@@ -1296,8 +1301,8 @@ namespace OpenSim.Data.SQLite
createCol(shapes, "LastAttachPoint", typeof(Int32));
// text TODO: this isn't right, but I'm not sure the right
// way to specify this as a blob atm
createCol(shapes, "Texture", typeof(byte[]));
createCol(shapes, "ExtraParams", typeof(byte[]));
createCol(shapes, "Texture", typeof(Byte[]));
createCol(shapes, "ExtraParams", typeof(Byte[]));
createCol(shapes, "Media", typeof(String));
createCol(shapes, "MatOvrd", typeof(byte[]));
shapes.PrimaryKey = new DataColumn[] { shapes.Columns["UUID"] };
@@ -2585,7 +2590,7 @@ namespace OpenSim.Data.SQLite
/// front. If we just have a list of b, c, etc... we can
/// generate these strings instead of typing them out.
/// </remarks>
private static SQLiteCommand createInsertCommand(string table, DataTable dt)
private static SqliteCommand createInsertCommand(string table, DataTable dt)
{
string[] cols = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
@@ -2601,13 +2606,13 @@ namespace OpenSim.Data.SQLite
sql += String.Join(", :", cols);
sql += ")";
// m_log.DebugFormat("[SQLITE]: Created insert command {0}", sql);
SQLiteCommand cmd = new SQLiteCommand(sql);
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSQLiteParameter(col.ColumnName, col.DataType));
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
@@ -2620,7 +2625,7 @@ namespace OpenSim.Data.SQLite
/// <param name="pk"></param>
/// <param name="dt"></param>
/// <returns>the created command</returns>
private static SQLiteCommand createUpdateCommand(string table, string pk, DataTable dt)
private static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
{
string sql = "update " + table + " set ";
string subsql = String.Empty;
@@ -2635,14 +2640,14 @@ namespace OpenSim.Data.SQLite
}
sql += subsql;
sql += " where " + pk;
SQLiteCommand cmd = new SQLiteCommand(sql);
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSQLiteParameter(col.ColumnName, col.DataType));
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
@@ -2654,7 +2659,7 @@ namespace OpenSim.Data.SQLite
/// <param name="pk"></param>
/// <param name="dt"></param>
/// <returns>the created command</returns>
private static SQLiteCommand createUpdateCommand(string table, string pk1, string pk2, DataTable dt)
private static SqliteCommand createUpdateCommand(string table, string pk1, string pk2, DataTable dt)
{
string sql = "update " + table + " set ";
string subsql = String.Empty;
@@ -2669,14 +2674,14 @@ namespace OpenSim.Data.SQLite
}
sql += subsql;
sql += " where " + pk1 + " and " + pk2;
SQLiteCommand cmd = new SQLiteCommand(sql);
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSQLiteParameter(col.ColumnName, col.DataType));
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
@@ -2719,7 +2724,7 @@ namespace OpenSim.Data.SQLite
///<summary>
/// This is a convenience function that collapses 5 repetitive
/// lines for defining SQLiteParameters to 2 parameters:
/// lines for defining SqliteParameters to 2 parameters:
/// column name and database type.
///
/// It assumes certain conventions like :param as the param
@@ -2728,9 +2733,9 @@ namespace OpenSim.Data.SQLite
/// for us.
///</summary>
///<returns>a built sqlite parameter</returns>
private static SQLiteParameter createSQLiteParameter(string name, Type type)
private static SqliteParameter createSqliteParameter(string name, Type type)
{
SQLiteParameter param = new SQLiteParameter();
SqliteParameter param = new SqliteParameter();
param.ParameterName = ":" + name;
param.DbType = dbtypeFromType(type);
param.SourceColumn = name;
@@ -2743,7 +2748,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupPrimCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupPrimCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("prims", ds.Tables["prims"]);
da.InsertCommand.Connection = conn;
@@ -2751,8 +2756,8 @@ namespace OpenSim.Data.SQLite
da.UpdateCommand = createUpdateCommand("prims", "UUID=:UUID", ds.Tables["prims"]);
da.UpdateCommand.Connection = conn;
SQLiteCommand delete = new SQLiteCommand("delete from prims where UUID = :UUID");
delete.Parameters.Add(createSQLiteParameter("UUID", typeof(String)));
SqliteCommand delete = new SqliteCommand("delete from prims where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
@@ -2762,7 +2767,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupItemsCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("primitems", ds.Tables["primitems"]);
da.InsertCommand.Connection = conn;
@@ -2770,8 +2775,8 @@ namespace OpenSim.Data.SQLite
da.UpdateCommand = createUpdateCommand("primitems", "itemID = :itemID", ds.Tables["primitems"]);
da.UpdateCommand.Connection = conn;
SQLiteCommand delete = new SQLiteCommand("delete from primitems where itemID = :itemID");
delete.Parameters.Add(createSQLiteParameter("itemID", typeof(String)));
SqliteCommand delete = new SqliteCommand("delete from primitems where itemID = :itemID");
delete.Parameters.Add(createSqliteParameter("itemID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
@@ -2781,7 +2786,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupTerrainCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupTerrainCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("terrain", ds.Tables["terrain"]);
da.InsertCommand.Connection = conn;
@@ -2792,7 +2797,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupLandCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupLandCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("land", ds.Tables["land"]);
da.InsertCommand.Connection = conn;
@@ -2800,8 +2805,8 @@ namespace OpenSim.Data.SQLite
da.UpdateCommand = createUpdateCommand("land", "UUID=:UUID", ds.Tables["land"]);
da.UpdateCommand.Connection = conn;
SQLiteCommand delete = new SQLiteCommand("delete from land where UUID=:UUID");
delete.Parameters.Add(createSQLiteParameter("UUID", typeof(String)));
SqliteCommand delete = new SqliteCommand("delete from land where UUID=:UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
da.DeleteCommand = delete;
da.DeleteCommand.Connection = conn;
}
@@ -2811,7 +2816,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupLandAccessCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupLandAccessCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("landaccesslist", ds.Tables["landaccesslist"]);
da.InsertCommand.Connection = conn;
@@ -2819,14 +2824,14 @@ namespace OpenSim.Data.SQLite
da.UpdateCommand = createUpdateCommand("landaccesslist", "LandUUID=:landUUID", "AccessUUID=:AccessUUID", ds.Tables["landaccesslist"]);
da.UpdateCommand.Connection = conn;
SQLiteCommand delete = new SQLiteCommand("delete from landaccesslist where LandUUID= :LandUUID and AccessUUID= :AccessUUID");
delete.Parameters.Add(createSQLiteParameter("LandUUID", typeof(String)));
delete.Parameters.Add(createSQLiteParameter("AccessUUID", typeof(String)));
SqliteCommand delete = new SqliteCommand("delete from landaccesslist where LandUUID= :LandUUID and AccessUUID= :AccessUUID");
delete.Parameters.Add(createSqliteParameter("LandUUID", typeof(String)));
delete.Parameters.Add(createSqliteParameter("AccessUUID", typeof(String)));
da.DeleteCommand = delete;
da.DeleteCommand.Connection = conn;
}
private void setupRegionSettingsCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupRegionSettingsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("regionsettings", ds.Tables["regionsettings"]);
da.InsertCommand.Connection = conn;
@@ -2839,7 +2844,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupRegionWindlightCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupRegionWindlightCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("regionwindlight", ds.Tables["regionwindlight"]);
da.InsertCommand.Connection = conn;
@@ -2847,20 +2852,20 @@ namespace OpenSim.Data.SQLite
da.UpdateCommand.Connection = conn;
}
private void setupRegionEnvironmentCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupRegionEnvironmentCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("regionenvironment", ds.Tables["regionenvironment"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("regionenvironment", "region_id=:region_id", ds.Tables["regionenvironment"]);
da.UpdateCommand.Connection = conn;
SQLiteCommand delete = new SQLiteCommand("delete from regionenvironment where region_id= :region_id");
delete.Parameters.Add(createSQLiteParameter("region_id", typeof(String)));
SqliteCommand delete = new SqliteCommand("delete from regionenvironment where region_id= :region_id");
delete.Parameters.Add(createSqliteParameter("region_id", typeof(String)));
da.DeleteCommand = delete;
da.DeleteCommand.Connection = conn;
}
private void setupRegionSpawnPointsCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupRegionSpawnPointsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("spawn_points", ds.Tables["spawn_points"]);
da.InsertCommand.Connection = conn;
@@ -2873,7 +2878,7 @@ namespace OpenSim.Data.SQLite
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupShapeCommands(SQLiteDataAdapter da, SQLiteConnection conn)
private void setupShapeCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("primshapes", ds.Tables["primshapes"]);
da.InsertCommand.Connection = conn;
@@ -2881,8 +2886,8 @@ namespace OpenSim.Data.SQLite
da.UpdateCommand = createUpdateCommand("primshapes", "UUID=:UUID", ds.Tables["primshapes"]);
da.UpdateCommand.Connection = conn;
SQLiteCommand delete = new SQLiteCommand("delete from primshapes where UUID = :UUID");
delete.Parameters.Add(createSQLiteParameter("UUID", typeof(String)));
SqliteCommand delete = new SqliteCommand("delete from primshapes where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}

View File

@@ -31,7 +31,11 @@ using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -62,7 +66,7 @@ namespace OpenSim.Data.SQLite
if (words.Length > 2)
return new UserAccountData[0];
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
if (words.Length == 1)
{

View File

@@ -30,8 +30,11 @@ using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
@@ -44,7 +47,7 @@ namespace OpenSim.Data.SQLite
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SQLiteConnection m_connection;
private SqliteConnection m_connection;
private string m_connectionString;
private Dictionary<string, FieldInfo> m_FieldMap =
@@ -66,13 +69,13 @@ namespace OpenSim.Data.SQLite
public void Initialise(string connectionString)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
m_connectionString = connectionString;
m_log.Info("[PROFILES_DATA]: Sqlite - connecting: "+m_connectionString);
m_connection = new SQLiteConnection(m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Migration m = new Migration(m_connection, Assembly, "UserProfiles");
@@ -91,7 +94,7 @@ namespace OpenSim.Data.SQLite
string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id";
IDataReader reader = null;
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", creatorId);
@@ -187,7 +190,7 @@ namespace OpenSim.Data.SQLite
ad.ExpirationDate = (int)epochexp.TotalSeconds;
try {
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", ad.ClassifiedId.ToString());
@@ -227,7 +230,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", recordId.ToString());
@@ -254,7 +257,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":AdId", ad.ClassifiedId.ToString());
@@ -300,7 +303,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
@@ -337,7 +340,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":CreatorId", avatarId.ToString());
@@ -413,7 +416,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
int top_pick;
int.TryParse(pick.TopPick.ToString(), out top_pick);
@@ -456,7 +459,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
@@ -484,7 +487,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", notes.UserId.ToString());
@@ -530,7 +533,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
@@ -559,7 +562,7 @@ namespace OpenSim.Data.SQLite
query += "SELECT * FROM userprofile WHERE ";
query += "useruuid = :Id";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
@@ -636,7 +639,7 @@ namespace OpenSim.Data.SQLite
query += ":profileFirstImage, ";
query += ":profileFirstText)";
using (SQLiteCommand put = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.CommandText = query;
put.Parameters.AddWithValue(":userId", props.UserId.ToString());
@@ -675,7 +678,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":profileURL", props.WebUrl);
@@ -712,7 +715,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":WantMask", up.WantToMask);
@@ -748,7 +751,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ImViaEmail", pref.IMViaEmail);
@@ -782,7 +785,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString());
@@ -800,7 +803,7 @@ namespace OpenSim.Data.SQLite
query = "INSERT INTO usersettings VALUES ";
query += "(:Id,'false','false', :Email)";
using (SQLiteCommand put = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", pref.UserId.ToString());
put.Parameters.AddWithValue(":Email", pref.EMail);
@@ -832,7 +835,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
@@ -853,7 +856,7 @@ namespace OpenSim.Data.SQLite
query += ":DataKey,";
query += ":DataVal) ";
using (SQLiteCommand put = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", props.UserId.ToString());
put.Parameters.AddWithValue(":TagId", props.TagId.ToString());
@@ -888,7 +891,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":UserId", props.UserId.ToString());
@@ -918,7 +921,7 @@ namespace OpenSim.Data.SQLite
try
{
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = string.Format(query, "\"classifieds\"");
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
@@ -932,7 +935,7 @@ namespace OpenSim.Data.SQLite
}
}
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = string.Format(query, "\"userpicks\"");
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
@@ -948,7 +951,7 @@ namespace OpenSim.Data.SQLite
query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = :Id";
using (SQLiteCommand cmd = (SQLiteCommand)m_connection.CreateCommand())
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());

View File

@@ -27,7 +27,11 @@
using System;
using System.Data;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
@@ -81,7 +85,7 @@ namespace OpenSim.Data.SQLite
/// front. If we just have a list of b, c, etc... we can
/// generate these strings instead of typing them out.
/// </remarks>
public static SQLiteCommand createInsertCommand(string table, DataTable dt)
public static SqliteCommand createInsertCommand(string table, DataTable dt)
{
string[] cols = new string[dt.Columns.Count];
@@ -97,13 +101,13 @@ namespace OpenSim.Data.SQLite
sql += ") values (:";
sql += String.Join(", :", cols);
sql += ")";
SQLiteCommand cmd = new SQLiteCommand(sql);
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSQLiteParameter(col.ColumnName, col.DataType));
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
@@ -115,7 +119,7 @@ namespace OpenSim.Data.SQLite
/// <param name="pk"></param>
/// <param name="dt"></param>
/// <returns>the created command</returns>
public static SQLiteCommand createUpdateCommand(string table, string pk, DataTable dt)
public static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
{
string sql = "update " + table + " set ";
string subsql = String.Empty;
@@ -130,14 +134,14 @@ namespace OpenSim.Data.SQLite
}
sql += subsql;
sql += " where " + pk;
SQLiteCommand cmd = new SQLiteCommand(sql);
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSQLiteParameter(col.ColumnName, col.DataType));
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
@@ -184,7 +188,7 @@ namespace OpenSim.Data.SQLite
///<summary>
/// <para>
/// This is a convenience function that collapses 5 repetitive
/// lines for defining SQLiteParameters to 2 parameters:
/// lines for defining SqliteParameters to 2 parameters:
/// column name and database type.
/// </para>
///
@@ -198,9 +202,9 @@ namespace OpenSim.Data.SQLite
/// <param name="name"></param>
/// <param name="type"></param>
///<returns>a built sqlite parameter</returns>
public static SQLiteParameter createSQLiteParameter(string name, Type type)
public static SqliteParameter createSqliteParameter(string name, Type type)
{
SQLiteParameter param = new SQLiteParameter();
SqliteParameter param = new SqliteParameter();
param.ParameterName = ":" + name;
param.DbType = dbtypeFromType(type);
param.SourceColumn = name;

View File

@@ -29,7 +29,11 @@ using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;
using System.Data.SQLite;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
@@ -48,7 +52,7 @@ namespace OpenSim.Data.SQLite
public SQLiteXInventoryData(string conn, string realm)
{
DllmapConfigHelper.RegisterAssembly(typeof(SQLiteConnection).Assembly);
DllmapConfigHelper.RegisterAssembly(typeof(SqliteConnection).Assembly);
m_Folders = new SqliteFolderHandler(
conn, "inventoryfolders", "XInventoryStore");
@@ -189,11 +193,11 @@ namespace OpenSim.Data.SQLite
UUID oldParent = retrievedItems[0].parentFolderID;
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":ParentFolderID", newParent));
cmd.Parameters.Add(new SQLiteParameter(":InventoryID", id));
cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParent));
cmd.Parameters.Add(new SqliteParameter(":InventoryID", id));
if (ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
@@ -207,12 +211,12 @@ namespace OpenSim.Data.SQLite
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("select * from inventoryitems where avatarId = :uuid and assetType = :type and flags = 1", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":uuid", principalID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":type", (int)AssetType.Gesture));
cmd.Parameters.Add(new SqliteParameter(":uuid", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":type", (int)AssetType.Gesture));
return DoQuery(cmd);
}
@@ -222,11 +226,11 @@ namespace OpenSim.Data.SQLite
{
IDataReader reader;
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("select inventoryCurrentPermissions from inventoryitems where avatarID = :PrincipalID and assetID = :AssetID", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":PrincipalID", principalID.ToString()));
cmd.Parameters.Add(new SQLiteParameter(":AssetID", assetID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":AssetID", assetID.ToString()));
reader = ExecuteReader(cmd, m_Connection);
}
@@ -271,11 +275,11 @@ namespace OpenSim.Data.SQLite
UUID oldParentFolderUUID = folders[0].parentFolderID;
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where folderID = :FolderID", m_Realm);
cmd.Parameters.Add(new SQLiteParameter(":ParentFolderID", newParentFolderID));
cmd.Parameters.Add(new SQLiteParameter(":FolderID", id));
cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParentFolderID));
cmd.Parameters.Add(new SqliteParameter(":FolderID", id));
if (ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
@@ -303,10 +307,10 @@ namespace OpenSim.Data.SQLite
// m_log.DebugFormat("[MYSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
// Util.PrintCallStack();
using (SQLiteCommand cmd = new SQLiteCommand())
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = "update inventoryfolders set version=version+1 where folderID = :folderID";
cmd.Parameters.Add(new SQLiteParameter(":folderID", folderID));
cmd.Parameters.Add(new SqliteParameter(":folderID", folderID));
if(ExecuteNonQuery(cmd, m_Connection) == 0)
return false;

View File

@@ -145,7 +145,7 @@ namespace OpenSim.Framework
}
else // New style version contains no spaces, just version number
{
return $"{Channel} {m_viewerInternal}";
return $"{Channel} {m_viewerInternal}";
}
}
}
@@ -372,7 +372,7 @@ namespace OpenSim.Framework
OSDMap urls = (OSDMap)tmpOSD;
foreach (KeyValuePair<String, OSD> kvp in urls)
{
ServiceURLs[kvp.Key] = kvp.Value.AsString();
ServiceURLs[kvp.Key] = kvp.Value;
//System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]);
}
}

View File

@@ -142,7 +142,6 @@ namespace OpenSim.Framework
sb.AppendASCII($"{kvp.Key} {kvp.Value.Value} {kvp.Value.Key}\n");
return OSUTF8Cached.GetArrayAndRelease(sb);
}
/*
public bool Validate(AnimationSetValidator val)
{

View File

@@ -41,8 +41,8 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
{
public class AssetLoaderFileSystem : IAssetLoader
{
private const string LIBRARY_OWNER_IDstr = "11111111-1111-0000-0000-000100bba000";
private static readonly UUID LIBRARY_OWNER_ID = new UUID(LIBRARY_OWNER_IDstr);
private static readonly UUID LIBRARY_OWNER_ID = new UUID("11111111-1111-0000-0000-000100bba000");
private static readonly string LIBRARY_OWNER_IDstr = "11111111-1111-0000-0000-000100bba000";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@@ -78,8 +78,9 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
if (fInfo.Exists)
{
FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] idata = new byte[numBytes];
BinaryReader br = new BinaryReader(fStream);
byte[] idata = br.ReadBytes((int)numBytes);
idata = br.ReadBytes((int)numBytes);
br.Close();
fStream.Close();
info.Data = idata;

View File

@@ -216,6 +216,7 @@ namespace OpenSim.Framework
}
}
}
}
/// <summary>
@@ -311,6 +312,7 @@ namespace OpenSim.Framework
return controldata;
}
public void UnpackUpdateMessage(OSDMap args)
{
OSD osdtmp;

View File

@@ -34,19 +34,21 @@ namespace OpenSim.Framework
/// A double dictionary that is thread abort safe.
/// </summary>
/// <remarks>
/// This adapts OpenMetaverse.DoubleDictionary to be thread-abort safe by acquiring ReaderWriterLockSlim within
/// a finally section (which can't be interrupted by Thread.Abort()).
/// </remarks>
public class DoubleDictionaryThreadAbortSafe<TKey1, TKey2, TValue>
{
readonly Dictionary<TKey1, TValue> Dictionary1;
readonly Dictionary<TKey2, TValue> Dictionary2;
Dictionary<TKey1, TValue> Dictionary1;
Dictionary<TKey2, TValue> Dictionary2;
private TValue[] m_array;
readonly ReaderWriterLockSlim rwLock = new();
ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
public DoubleDictionaryThreadAbortSafe()
{
Dictionary1 = [];
Dictionary2 = [];
Dictionary1 = new Dictionary<TKey1,TValue>();
Dictionary2 = new Dictionary<TKey2,TValue>();
m_array = null;
}
@@ -59,102 +61,133 @@ namespace OpenSim.Framework
~DoubleDictionaryThreadAbortSafe()
{
rwLock?.Dispose();
if(rwLock != null)
rwLock.Dispose();
}
public void Add(TKey1 key1, TKey2 key2, TValue value)
{
rwLock.EnterWriteLock();
bool gotLock = false;
try
{
Dictionary1[key1] = value;
Dictionary2[key2] = value;
m_array = null;
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterWriteLock();
gotLock = true;
}
Dictionary1[key1] = value;
Dictionary2[key2] = value;
m_array = null;
}
finally
{
if (gotLock)
rwLock.ExitWriteLock();
}
finally { rwLock.ExitWriteLock(); }
}
public bool Remove(TKey1 key1, TKey2 key2)
{
rwLock.EnterWriteLock();
try
{
bool success = Dictionary1.Remove(key1);
success &= Dictionary2.Remove(key2);
m_array = null;
return success;
}
finally { rwLock.ExitWriteLock(); }
}
bool success;
bool gotLock = false;
public bool Remove(TKey1 key1, TKey2 key2, out TValue value)
{
rwLock.EnterWriteLock();
try
{
bool success = Dictionary1.Remove(key1, out value);
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterWriteLock();
gotLock = true;
}
success = Dictionary1.Remove(key1);
success &= Dictionary2.Remove(key2);
m_array = null;
return success;
}
finally { rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
rwLock.ExitWriteLock();
}
return success;
}
public bool Remove(TKey1 key1)
{
rwLock.EnterWriteLock();
try
{
// This is an O(n) operation!
if (Dictionary1.Remove(key1, out TValue value))
{
m_array = null;
foreach (KeyValuePair<TKey2, TValue> kvp in Dictionary2)
{
if (kvp.Value.Equals(value))
{
Dictionary2.Remove(kvp.Key);
return true;
}
}
}
return false;
}
finally { rwLock.ExitWriteLock(); }
}
bool found = false;
bool gotLock = false;
public bool Remove(TKey1 key1, out TValue value)
{
rwLock.EnterWriteLock();
try
{
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterWriteLock();
gotLock = true;
}
// This is an O(n) operation!
if (Dictionary1.Remove(key1, out value))
{
m_array = null;
TValue value;
if (Dictionary1.TryGetValue(key1, out value))
{
foreach (KeyValuePair<TKey2, TValue> kvp in Dictionary2)
{
if (kvp.Value.Equals(value))
{
Dictionary2.Remove(kvp.Key);
return true;
try { }
finally
{
Dictionary1.Remove(key1);
Dictionary2.Remove(kvp.Key);
m_array = null;
}
found = true;
break;
}
}
}
return false;
}
finally { rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
rwLock.ExitWriteLock();
}
return found;
}
public bool Remove(TKey2 key2)
{
rwLock.EnterWriteLock();
bool found = false;
bool gotLock = false;
try
{
// This is an O(n) operation!
if (Dictionary2.Remove(key2, out TValue value))
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterWriteLock();
gotLock = true;
}
// This is an O(n) operation!
TValue value;
if (Dictionary2.TryGetValue(key2, out value))
{
m_array = null;
foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1)
{
if (kvp.Value.Equals(value))
@@ -162,51 +195,49 @@ namespace OpenSim.Framework
try { }
finally
{
Dictionary2.Remove(key2);
Dictionary1.Remove(kvp.Key);
m_array = null;
}
return true;
found = true;
break;
}
}
}
return false;
}
finally { rwLock.ExitWriteLock(); }
}
public bool Remove(TKey2 key2, out TValue value)
{
rwLock.EnterWriteLock();
try
finally
{
// This is an O(n) operation!
if (Dictionary2.Remove(key2, out value))
{
m_array = null;
foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1)
{
if (kvp.Value.Equals(value))
{
Dictionary1.Remove(kvp.Key);
return true;
}
}
}
return false;
if (gotLock)
rwLock.ExitWriteLock();
}
finally { rwLock.ExitWriteLock(); }
return found;
}
public void Clear()
{
rwLock.EnterWriteLock();
bool gotLock = false;
try
{
Dictionary1.Clear();
Dictionary2.Clear();
m_array = null;
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterWriteLock();
gotLock = true;
Dictionary1.Clear();
Dictionary2.Clear();
m_array = null;
}
}
finally
{
if (gotLock)
rwLock.ExitWriteLock();
}
finally { rwLock.ExitWriteLock(); }
}
public int Count
@@ -216,42 +247,68 @@ namespace OpenSim.Framework
public bool ContainsKey(TKey1 key)
{
rwLock.EnterReadLock();
try
{
return Dictionary1.ContainsKey(key);
}
finally { rwLock.ExitReadLock(); }
return Dictionary1.ContainsKey(key);
}
public bool ContainsKey(TKey2 key)
{
rwLock.EnterReadLock();
try
{
return Dictionary2.ContainsKey(key);
}
finally { rwLock.ExitReadLock(); }
return Dictionary2.ContainsKey(key);
}
public bool TryGetValue(TKey1 key, out TValue value)
{
rwLock.EnterReadLock();
bool success;
bool gotLock = false;
try
{
return Dictionary1.TryGetValue(key, out value);
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterReadLock();
gotLock = true;
}
success = Dictionary1.TryGetValue(key, out value);
}
finally { rwLock.ExitReadLock(); }
finally
{
if (gotLock)
rwLock.ExitReadLock();
}
return success;
}
public bool TryGetValue(TKey2 key, out TValue value)
{
rwLock.EnterReadLock();
bool success;
bool gotLock = false;
try
{
return Dictionary2.TryGetValue(key, out value);
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterReadLock();
gotLock = true;
}
success = Dictionary2.TryGetValue(key, out value);
}
finally { rwLock.ExitReadLock(); }
finally
{
if (gotLock)
rwLock.ExitReadLock();
}
return success;
}
public void ForEach(Action<TValue> action)
@@ -266,44 +323,76 @@ namespace OpenSim.Framework
public void ForEach(Action<KeyValuePair<TKey1, TValue>> action)
{
rwLock.EnterReadLock();
bool gotLock = false;
try
{
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterReadLock();
gotLock = true;
}
foreach (KeyValuePair<TKey1, TValue> entry in Dictionary1)
action(entry);
}
finally { rwLock.ExitReadLock(); }
finally
{
if (gotLock)
rwLock.ExitReadLock();
}
}
public void ForEach(Action<KeyValuePair<TKey2, TValue>> action)
{
rwLock.EnterReadLock();
bool gotLock = false;
try
{
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterReadLock();
gotLock = true;
}
foreach (KeyValuePair<TKey2, TValue> entry in Dictionary2)
action(entry);
}
finally { rwLock.ExitReadLock(); }
finally
{
if (gotLock)
rwLock.ExitReadLock();
}
}
public TValue FindValue(Predicate<TValue> predicate)
{
TValue[] values = GetArray();
for (int i = 0; i < values.Length; ++i)
int len = values.Length;
for (int i = 0; i < len; ++i)
{
if (predicate(values[i]))
return values[i];
}
return default;
return default(TValue);
}
public IList<TValue> FindAll(Predicate<TValue> predicate)
{
IList<TValue> list = [];
IList<TValue> list = new List<TValue>();
TValue[] values = GetArray();
for (int i = 0; i < values.Length; ++i)
int len = values.Length;
for (int i = 0; i < len; ++i)
{
if (predicate(values[i]))
list.Add(values[i]);
@@ -313,11 +402,21 @@ namespace OpenSim.Framework
public int RemoveAll(Predicate<TValue> predicate)
{
IList<TKey1> list = [];
IList<TKey1> list = new List<TKey1>();
bool gotUpgradeableLock = false;
rwLock.EnterUpgradeableReadLock();
try
{
// Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing
// the acquision inside the main try. The inner finally block is needed because thread aborts cannot
// interrupt code in these blocks (hence gotLock is guaranteed to be set correctly).
try {}
finally
{
rwLock.EnterUpgradeableReadLock();
gotUpgradeableLock = true;
}
foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1)
{
if (predicate(kvp.Value))
@@ -331,43 +430,83 @@ namespace OpenSim.Framework
list2.Add(kvp.Key);
}
bool gotWriteLock = false;
try
{
rwLock.EnterWriteLock();
try {}
finally
{
rwLock.EnterWriteLock();
gotWriteLock = true;
for (int i = 0; i < list.Count; i++)
Dictionary1.Remove(list[i]);
for (int i = 0; i < list.Count; i++)
Dictionary1.Remove(list[i]);
for (int i = 0; i < list2.Count; i++)
Dictionary2.Remove(list2[i]);
m_array = null;
return list.Count;
for (int i = 0; i < list2.Count; i++)
Dictionary2.Remove(list2[i]);
m_array = null;
}
}
finally
{
if (gotWriteLock)
rwLock.ExitWriteLock();
}
finally { rwLock.ExitWriteLock(); }
}
finally { rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotUpgradeableLock)
rwLock.ExitUpgradeableReadLock();
}
return list.Count;
}
public TValue[] GetArray()
{
rwLock.EnterUpgradeableReadLock();
bool gotupLock = false;
try
{
try { }
finally
{
rwLock.EnterUpgradeableReadLock();
gotupLock = true;
}
if (m_array == null)
{
rwLock.EnterWriteLock();
bool gotwritelock = false;
try
{
try { }
finally
{
rwLock.EnterWriteLock();
gotwritelock = true;
}
m_array = new TValue[Dictionary1.Count];
Dictionary1.Values.CopyTo(m_array, 0);
}
finally { rwLock.ExitWriteLock(); }
finally
{
if (gotwritelock)
rwLock.ExitWriteLock();
}
}
return m_array;
}
catch { return []; }
finally { rwLock.ExitUpgradeableReadLock(); }
catch
{
return new TValue[0];
}
finally
{
if (gotupLock)
rwLock.ExitUpgradeableReadLock();
}
}
}
}

View File

@@ -67,7 +67,10 @@ namespace OpenSim.Framework
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private void CheckTimer()
{
m_purgeTimer ??= new Timer(Purge, null, m_expire, Timeout.Infinite);
if (m_purgeTimer == null)
{
m_purgeTimer = new Timer(Purge, null, m_expire, Timeout.Infinite);
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
@@ -103,9 +106,17 @@ namespace OpenSim.Framework
private void Purge(object ignored)
{
m_rwLock.EnterUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
if (m_expireControl.Count == 0)
{
DisposeTimer();
@@ -123,9 +134,16 @@ namespace OpenSim.Framework
if(expired.Count > 0)
{
m_rwLock.EnterWriteLock();
bool gotWriteLock = false;
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotWriteLock = true;
}
valuesArrayCache = null;
foreach (TKey1 key in expired)
{
@@ -133,8 +151,11 @@ namespace OpenSim.Framework
m_values.Remove(key);
}
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotWriteLock)
m_rwLock.ExitWriteLock();
}
if (m_expireControl.Count == 0)
DisposeTimer();
else
@@ -143,7 +164,11 @@ namespace OpenSim.Framework
else
m_purgeTimer.Change(m_expire, Timeout.Infinite);
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
@@ -154,17 +179,28 @@ namespace OpenSim.Framework
public void Add(TKey1 key, TValue1 val)
{
bool gotLock = false;
int now = (int)(Util.GetTimeStampMS() - m_startTS) + m_expire;
m_rwLock.EnterWriteLock();
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
m_expireControl[key] = now;
m_values[key] = val;
valuesArrayCache = null;
CheckTimer();
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
@@ -181,6 +217,7 @@ namespace OpenSim.Framework
public void Add(TKey1 key, TValue1 val, int expireMS)
{
bool gotLock = false;
int now;
if (expireMS > 0)
{
@@ -190,44 +227,78 @@ namespace OpenSim.Framework
else
now = int.MinValue;
m_rwLock.EnterWriteLock();
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
m_expireControl[key] = now;
m_values[key] = val;
valuesArrayCache = null;
CheckTimer();
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
}
public bool Remove(TKey1 key)
{
m_rwLock.EnterWriteLock();
bool success;
bool gotLock = false;
try
{
bool success = m_expireControl.Remove(key);
try {}
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
success = m_expireControl.Remove(key);
success |= m_values.Remove(key);
if(success)
valuesArrayCache = null;
if (m_expireControl.Count == 0)
DisposeTimer();
return success;
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
return success;
}
public void Clear()
{
m_rwLock.EnterWriteLock();
bool gotLock = false;
try
{
try {}
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
DisposeTimer();
m_expireControl.Clear();
m_values.Clear();
valuesArrayCache = null;
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
}
public int Count
@@ -243,12 +314,22 @@ namespace OpenSim.Framework
public bool ContainsKey(TKey1 key)
{
m_rwLock.EnterReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterReadLock();
gotLock = true;
}
return m_expireControl.ContainsKey(key);
}
finally { m_rwLock.ExitReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitReadLock();
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
@@ -259,14 +340,26 @@ namespace OpenSim.Framework
public bool ContainsKey(TKey1 key, int expireMS)
{
m_rwLock.EnterUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
if(m_expireControl.ContainsKey(key))
{
m_rwLock.EnterWriteLock();
bool gotWriteLock = false;
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotWriteLock = true;
}
int now;
if(expireMS > 0)
{
@@ -279,33 +372,68 @@ namespace OpenSim.Framework
m_expireControl[key] = now;
return true;
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotWriteLock)
m_rwLock.ExitWriteLock();
}
}
return false;
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
}
public bool TryGetValue(TKey1 key, out TValue1 value)
{
m_rwLock.EnterReadLock();
bool gotLock = false;
try
{
try {}
finally
{
m_rwLock.EnterReadLock();
gotLock = true;
}
return m_values.TryGetValue(key, out value);
}
finally { m_rwLock.ExitReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitReadLock();
}
}
public bool TryGetValue(TKey1 key, int expireMS, out TValue1 value)
{
m_rwLock.EnterUpgradeableReadLock();
bool success;
bool gotLock = false;
try
{
if(m_values.TryGetValue(key, out value))
try { }
finally
{
m_rwLock.EnterWriteLock();
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
success = m_values.TryGetValue(key, out value);
if(success)
{
bool gotWriteLock = false;
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotWriteLock = true;
}
int now;
if(expireMS > 0)
{
@@ -316,30 +444,56 @@ namespace OpenSim.Framework
now = int.MinValue;
m_expireControl[key] = now;
return true;
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotWriteLock)
m_rwLock.ExitWriteLock();
}
}
return false;
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
return success;
}
public ref TValue1 TryGetOrDefaultValue(TKey1 key, out bool existed)
{
m_rwLock.ExitUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.ExitUpgradeableReadLock();
gotLock = true;
}
return ref CollectionsMarshal.GetValueRefOrAddDefault(m_values, key, out existed);
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
}
public ref TValue1 TryGetOrDefaultValue(TKey1 key, int expireMS, out bool existed)
{
m_rwLock.EnterWriteLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
ref TValue1 ret = ref CollectionsMarshal.GetValueRefOrAddDefault(m_values, key, out existed);
int now;
if (expireMS > 0)
@@ -353,16 +507,26 @@ namespace OpenSim.Framework
m_expireControl[key] = now;
return ref ret;
}
finally { m_rwLock.EnterWriteLock(); }
finally
{
if (gotLock)
m_rwLock.EnterWriteLock();
}
}
public TValue1[] Values
{
get
{
m_rwLock.EnterUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
if(valuesArrayCache == null)
{
valuesArrayCache = new TValue1[m_values.Count];
@@ -370,7 +534,11 @@ namespace OpenSim.Framework
}
return valuesArrayCache;
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
}
}
@@ -379,12 +547,22 @@ namespace OpenSim.Framework
{
get
{
m_rwLock.EnterUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
return m_values.Keys;
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
}
}
*/

View File

@@ -60,7 +60,10 @@ namespace OpenSim.Framework
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private void CheckTimer()
{
m_purgeTimer ??= new Timer(Purge, null, m_expire, Timeout.Infinite);
if (m_purgeTimer == null)
{
m_purgeTimer = new Timer(Purge, null, m_expire, Timeout.Infinite);
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
@@ -96,9 +99,17 @@ namespace OpenSim.Framework
private void Purge(object ignored)
{
m_rwLock.EnterUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
if (m_dictionary.Count == 0)
{
DisposeTimer();
@@ -116,14 +127,24 @@ namespace OpenSim.Framework
if (expired.Count > 0)
{
m_rwLock.EnterWriteLock();
bool gotWriteLock = false;
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotWriteLock = true;
}
foreach (Tkey1 key in expired)
m_dictionary.Remove(key);
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotWriteLock)
m_rwLock.ExitWriteLock();
}
if (m_dictionary.Count == 0)
DisposeTimer();
else
@@ -132,24 +153,40 @@ namespace OpenSim.Framework
else
m_purgeTimer.Change(m_expire, Timeout.Infinite);
}
finally { m_rwLock.ExitUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitUpgradeableReadLock();
}
}
public void Add(Tkey1 key)
{
bool gotLock = false;
int now = (int)(Util.GetTimeStampMS() - m_startTS) + m_expire;
m_rwLock.EnterWriteLock();
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
m_dictionary[key] = now;
CheckTimer();
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
}
public void Add(Tkey1 key, int expireMS)
{
bool gotLock = false;
int now;
if (expireMS > 0)
{
@@ -159,38 +196,71 @@ namespace OpenSim.Framework
else
now = int.MinValue;
m_rwLock.EnterWriteLock();
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
m_dictionary[key] = now;
CheckTimer();
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
}
public bool Remove(Tkey1 key)
{
m_rwLock.EnterWriteLock();
bool success;
bool gotLock = false;
try
{
bool success = m_dictionary.Remove(key);
try {}
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
success = m_dictionary.Remove(key);
if(m_dictionary.Count == 0)
DisposeTimer();
return success;
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
return success;
}
public void Clear()
{
m_rwLock.EnterWriteLock();
bool gotLock = false;
try
{
try {}
finally
{
m_rwLock.EnterWriteLock();
gotLock = true;
}
m_dictionary.Clear();
DisposeTimer();
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotLock)
m_rwLock.ExitWriteLock();
}
}
public int Count
@@ -200,24 +270,46 @@ namespace OpenSim.Framework
public bool ContainsKey(Tkey1 key)
{
m_rwLock.EnterReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterReadLock();
gotLock = true;
}
return m_dictionary.ContainsKey(key);
}
finally { m_rwLock.ExitReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitReadLock();
}
}
public bool ContainsKey(Tkey1 key, int expireMS)
{
m_rwLock.EnterUpgradeableReadLock();
bool gotLock = false;
try
{
try { }
finally
{
m_rwLock.EnterUpgradeableReadLock();
gotLock = true;
}
if (m_dictionary.ContainsKey(key))
{
m_rwLock.EnterWriteLock();
bool gotWriteLock = false;
try
{
try { }
finally
{
m_rwLock.EnterWriteLock();
gotWriteLock = true;
}
int now;
if (expireMS > 0)
{
@@ -230,21 +322,44 @@ namespace OpenSim.Framework
m_dictionary[key] = now;
return true;
}
finally { m_rwLock.ExitWriteLock(); }
finally
{
if (gotWriteLock)
m_rwLock.ExitWriteLock();
}
}
return false;
}
finally { m_rwLock.EnterUpgradeableReadLock(); }
finally
{
if (gotLock)
m_rwLock.EnterUpgradeableReadLock();
}
}
public bool TryGetValue(Tkey1 key, out int value)
{
m_rwLock.EnterReadLock();
bool success;
bool gotLock = false;
try
{
return m_dictionary.TryGetValue(key, out value);
try {}
finally
{
m_rwLock.EnterReadLock();
gotLock = true;
}
success = m_dictionary.TryGetValue(key, out value);
}
finally { m_rwLock.ExitReadLock(); }
finally
{
if (gotLock)
m_rwLock.ExitReadLock();
}
return success;
}
}
}

View File

@@ -71,7 +71,7 @@ namespace OpenSim.Framework
Flags = OSHTTPURIFlags.None;
try
{
Uri m_checkuri = new(uri);
Uri m_checkuri = new Uri(uri);
if(m_checkuri.Scheme != Uri.UriSchemeHttp && m_checkuri.Scheme != Uri.UriSchemeHttps)
return;
@@ -368,11 +368,10 @@ namespace OpenSim.Framework
private string m_SearchURL = string.Empty;
private string m_DestinationGuideURL = string.Empty;
private string m_economyURL = string.Empty;
private string[] m_StunServers = null;
public GridInfo (IConfigSource config, string defaultURI = "")
{
string[] sections = ["Const", "Startup", "Hypergrid"];
string[] sections = new string[] {"Const", "Startup", "Hypergrid"};
string gatekeeper = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", sections, string.Empty);
if (string.IsNullOrEmpty(gatekeeper))
@@ -417,7 +416,8 @@ namespace OpenSim.Framework
OSHHTPHost tmp = new OSHHTPHost(alias[i].Trim(), false);
if (tmp.IsValidHost)
{
m_gateKeeperAlias ??= new HashSet<OSHHTPHost>();
if (m_gateKeeperAlias == null)
m_gateKeeperAlias = new HashSet<OSHHTPHost>();
m_gateKeeperAlias.Add(tmp);
}
}
@@ -431,7 +431,6 @@ namespace OpenSim.Framework
m_gridUrlAlias[i++] = a.URI;
}
string home = Util.GetConfigVarFromSections<string>(config, "HomeURI", sections, string.Empty);
if (string.IsNullOrEmpty(home))
@@ -459,13 +458,14 @@ namespace OpenSim.Framework
OSHHTPHost tmp = new OSHHTPHost(alias[i].Trim(), false);
if (tmp.IsValidHost)
{
m_homeURLAlias ??= new HashSet<OSHHTPHost>();
if (m_homeURLAlias == null)
m_homeURLAlias = new HashSet<OSHHTPHost>();
m_homeURLAlias.Add(tmp);
}
}
}
string[] namessections = ["Const", "GridInfo", "SimulatorFeatures"];
string[] namessections = new string[] { "Const", "GridInfo", "SimulatorFeatures" };
m_GridName = Util.GetConfigVarFromSections<string>(config, "GridName", namessections, string.Empty);
if (string.IsNullOrEmpty(m_GridName))
m_GridName = Util.GetConfigVarFromSections<string>(config, "gridname", namessections, string.Empty);
@@ -504,8 +504,7 @@ namespace OpenSim.Framework
m_DestinationGuideURL = tmpuri.URI;
}
m_economyURL = Util.GetConfigVarFromSections<string>(config, "economy", ["Economy", "GridInfo"]);
m_economyURL = Util.GetConfigVarFromSections<string>(config, "economy", new string[] { "Economy", "GridInfo" });
if (!string.IsNullOrEmpty(m_economyURL))
{
tmpuri = new OSHTTPURI(m_economyURL.Trim(), true);
@@ -516,20 +515,6 @@ namespace OpenSim.Framework
}
m_economyURL = tmpuri.URI;
}
string stunservers = Util.GetConfigVarFromSections<string>(config, "StunServers", ["Const", "Startup", "GridInfo", "SimulatorFeatures"], string.Empty);
if (!string.IsNullOrWhiteSpace(stunservers))
{
string[] stuns = stunservers.Split(',');
List<string> stunsarr = new List<string>(stuns.Length);
for (int i = 0; i < stuns.Length; ++i)
{
OSHHTPHost tmp = new OSHHTPHost(stuns[i].Trim(), false);
if (tmp.IsValidHost)
stunsarr.Add("stun:" + tmp.HostAndPort);
}
m_StunServers = stunsarr.Count > 0 ? stunsarr.ToArray() : null;
}
}
public bool HasHGConfig
@@ -700,7 +685,6 @@ namespace OpenSim.Framework
}
}
public string GridName
{
get { return m_GridName; }
@@ -772,27 +756,5 @@ namespace OpenSim.Framework
m_log.Error((tmp.IsValidHost ? "Could not resolve EconomyURL" : "EconomyURL is a invalid host ") + value ?? "");
}
}
public string[] StunServers
{
get { return m_StunServers; }
set
{
if(value.Length > 0)
{
List<string> values = new List<string>(value.Length);
for (int i = 0; i < value.Length; ++i)
{
OSHHTPHost tmp = new OSHHTPHost(value[i].Trim(), false);
if (tmp.IsValidHost)
values.Add("stun:" + tmp.HostAndPort);
}
m_StunServers = values.Count > 0 ? values.ToArray() : null;
}
else
m_StunServers = null;
}
}
}
}

View File

@@ -1396,8 +1396,7 @@ namespace OpenSim.Framework
void SendRegionHandle(UUID regoinID, ulong handle);
void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y);
//void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt, int options);
void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, int options); //lookat does nothing
void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt);
void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data);
void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data);

View File

@@ -794,8 +794,8 @@ namespace OpenSim.Framework
public static byte[] ulongToByteArray(ulong uLongValue)
{
return
[
return new byte[8]
{
(byte)(uLongValue >> 56),
(byte)(uLongValue >> 48),
(byte)(uLongValue >> 40),
@@ -804,18 +804,18 @@ namespace OpenSim.Framework
(byte)(uLongValue >> 16),
(byte)(uLongValue >> 8),
(byte)uLongValue
];
};
}
public static byte[] uintToByteArray(uint value)
{
return
[
return new byte[4]
{
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value
];
};
}
static readonly char[] base64Chars = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',

View File

@@ -63,7 +63,7 @@ namespace OpenSim.Framework
private uint _flags = (uint)ParcelFlags.AllowFly | (uint)ParcelFlags.AllowLandmark |
(uint)ParcelFlags.AllowAPrimitiveEntry |
(uint)ParcelFlags.AllowDeedToGroup |
(uint)ParcelFlags.CreateObjects | (uint)ParcelFlags.AllowOtherScripts |
(uint)ParcelFlags.AllowOtherScripts |
(uint)ParcelFlags.AllowVoiceChat;
private byte _landingType = (byte)OpenMetaverse.LandingType.Direct;
@@ -84,7 +84,7 @@ namespace OpenSim.Framework
private UUID _snapshotID = UUID.Zero;
private Vector3 _userLocation = new();
private Vector3 _userLookAt = new();
private int _otherCleanTime = 0;
private int _otherCleanTime = 5;
private string _mediaType = "none/none";
private string _mediaDescription = "";
private int _mediaHeight = 0;

View File

@@ -119,7 +119,7 @@ namespace OpenSim.Framework
// Copy the temporary stream to the network stream
formDataStream.Seek(0, SeekOrigin.Begin);
using (Stream requestStream = request.GetRequestStream())
formDataStream.CopyTo(requestStream, (int)formDataStream.Length);
formDataStream.CopyStream(requestStream, (int)formDataStream.Length);
}
#endregion Stream Writing

View File

@@ -240,10 +240,12 @@ namespace OpenSim.Framework
// 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 (!url.AbsolutePath.StartsWith("/lslhttp/"))
{
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);
}

View File

@@ -320,7 +320,9 @@ namespace OpenSim.Framework
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
@@ -1506,7 +1508,7 @@ namespace OpenSim.Framework
return null;
if (RenderMaterials.overrides is null || RenderMaterials.overrides.Length == 0)
return [0]; // store so outdated viewer caches can be updated
return new byte[] { 0 }; // store so outdated viewer caches can be updated
int nentries = 0;
for (int i = 0; i < RenderMaterials.overrides.Length; i++)
@@ -1515,7 +1517,7 @@ namespace OpenSim.Framework
nentries++;
}
if(nentries == 0)
return [0];
return new byte[] { 0 };
osUTF8 sb = OSUTF8Cached.Acquire();
sb.Append((byte)nentries);
@@ -1539,7 +1541,6 @@ namespace OpenSim.Framework
if (data is null || data.Length < 1)
return;
int nentries = data[0];
if (nentries > 128)
return;

View File

@@ -44,19 +44,20 @@ namespace OpenSim.Framework
// The point is an absolute position, so we need the relative
// location to the spawn point
Vector3 offset = point - pos;
Distance = offset.Length();
Distance = Vector3.Mag(offset);
// Next we need to rotate this vector into the spawn point's
// coordinate system
rot.W = -rot.W;
offset *= rot;
offset.Normalize();
Vector3 dir = Vector3.Normalize(offset);
// Get the bearing (yaw)
Yaw = MathF.Atan2(offset.Y, offset.X);
Yaw = MathF.Atan2(dir.Y, dir.X);
// Get the elevation (pitch)
Pitch = -MathF.Atan2(offset.Z, MathF.Sqrt(offset.X * offset.X + offset.Y * offset.Y));
Pitch = -MathF.Atan2(dir.Z, MathF.Sqrt(dir.X * dir.X + dir.Y * dir.Y));
}
public Vector3 GetLocation(Vector3 pos, Quaternion rot)
@@ -64,8 +65,8 @@ namespace OpenSim.Framework
Quaternion y = Quaternion.CreateFromEulers(0, 0, Yaw);
Quaternion p = Quaternion.CreateFromEulers(0, Pitch, 0);
Vector3 dir = Vector3.UnitX * p * y;
Vector3 offset = dir * Distance;
Vector3 dir = new Vector3(1, 0, 0) * p * y;
Vector3 offset = dir * (float)Distance;
offset *= rot;
@@ -110,10 +111,10 @@ namespace OpenSim.Framework
/// <value>
/// These appear to be terrain textures that are shipped with the client.
/// </value>
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_1 = new("b8d3965a-ad78-bf43-699b-bff8eca6c975");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_2 = new("abb783e6-3e93-26c0-248a-247666855da3");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_3 = new("179cdabd-398a-9b6b-1391-4dc333ba321f");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_4 = new("beb169c7-11ea-fff2-efe5-0f24dc881df2");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_1 = new("0bc58228-74a0-7e83-89bc-5c23464bcec5");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_2 = new("63338ede-0037-c4fd-855b-015d77112fc8");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_3 = new("303cd381-8560-7579-23f1-f0a880799740");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_4 = new("53a2f406-4895-1d13-d541-d2e3b86bc19c");
public static readonly UUID DEFAULT_TERRAIN_PBR_1 = new("b8d3965a-ad78-bf43-699b-bff8eca6c975");
public static readonly UUID DEFAULT_TERRAIN_PBR_2 = new("abb783e6-3e93-26c0-248a-247666855da3");

View File

@@ -286,8 +286,7 @@ namespace OpenSim.Framework
responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
responseMessage.EnsureSuccessStatusCode();
using CancellationTokenSource cts = new(30000);
using Stream respStream = responseMessage.Content.ReadAsStream(cts.Token);
Stream respStream = responseMessage.Content.ReadAsStream();
int length = respStream.Read(_readbuf, 0, BufferSize);
while (length > 0)
{
@@ -403,5 +402,6 @@ namespace OpenSim.Framework
client?.Dispose();
}
}
}
}

View File

@@ -179,7 +179,7 @@ namespace OpenSim.Framework.Servers
{
m_log.Info("[STARTUP]: Beginning startup processing");
m_log.Info("[STARTUP]: Version: " + m_version);
m_log.Info("[STARTUP]: version: " + m_version);
m_log.Info($"[STARTUP]: Operating system version: {Environment.OSVersion}, .NET platform {Util.RuntimePlatformStr}, Runtime {Environment.Version}");
m_log.Info($"[STARTUP]: Processor Architecture: {RuntimeInformation.ProcessArchitecture}({(BitConverter.IsLittleEndian ? "le" : "be")} {(Environment.Is64BitProcess ? "64" : "32")}bit)");
try

View File

@@ -2299,7 +2299,7 @@ namespace OpenSim.Framework.Servers.HttpServer
}
if (httpRequest.QueryFlags.Contains("about"))
{
httpResponse.Redirect("http://opensimulator.org/wiki/0.9.3.1_Release");
httpResponse.Redirect("https://github.com/lickx/opensim-lickx");
return;
}
if (!httpRequest.QueryAsDictionary.TryGetValue("method", out string method) || string.IsNullOrWhiteSpace(method))

View File

@@ -219,7 +219,6 @@ namespace OSHttpServer
/// </remarks>
public virtual void Cleanup()
{
if (StreamPassedOff)
return;

View File

@@ -125,53 +125,23 @@ namespace OSHttpServer
private async void AcceptLoop()
{
while (true)
try
{
if (m_shutdown)
while (true)
{
m_shutdownEvent?.Set();
break;
}
if (m_shutdown)
{
m_shutdownEvent.Set();
break;
}
Socket socket = null;
try
{
socket = await m_listener.AcceptSocketAsync(m_CancellationSource.Token).ConfigureAwait(false);
Socket socket = await m_listener.AcceptSocketAsync(m_CancellationSource.Token).ConfigureAwait(false); ;
if (!socket.Connected)
{
socket.Dispose();
continue;
}
}
catch (OperationCanceledException)
{
m_shutdownEvent?.Set();
break;
}
catch (SocketException snssErr)
{
m_logWriter.Write(this, LogPrio.Debug, "OSHTTP Accept wait ignoring error: " + snssErr.Message);
socket?.Dispose();
continue;
}
catch (Exception err)
{
m_logWriter.Write(this, LogPrio.Debug, "OSHTTP Accept wait fatal error: " + err.Message);
ExceptionThrown?.Invoke(this, err);
}
if (m_shutdown)
{
m_shutdownEvent?.Set();
socket?.Dispose();
break;
}
if(socket == null)
continue;
try
{
socket.NoDelay = true;
if (!OnAcceptingSocket(socket))
@@ -179,7 +149,6 @@ namespace OSHttpServer
socket.Disconnect(true);
continue;
}
if (socket.Connected)
{
m_logWriter.Write(this, LogPrio.Debug, $"Accepted connection from: {socket.RemoteEndPoint}");
@@ -190,25 +159,18 @@ namespace OSHttpServer
m_contextFactory.CreateContext(socket);
}
else
socket?.Dispose();
}
catch (OperationCanceledException)
{
m_shutdownEvent?.Set();
break;
}
catch (SocketException snssErr)
{
m_logWriter.Write(this, LogPrio.Debug, "OSHTTP Accept processing ignoring error: " + snssErr.Message);
socket?.Dispose();
continue;
}
catch (Exception err)
{
m_logWriter.Write(this, LogPrio.Debug, "OSHTTP Accept processing fatal error: " + err.Message);
ExceptionThrown?.Invoke(this, err);
socket.Dispose();
}
}
catch (OperationCanceledException)
{
m_shutdownEvent.Set();
}
catch (Exception err)
{
m_logWriter.Write(this, LogPrio.Debug, err.Message);
ExceptionThrown?.Invoke(this, err);
}
}
/// <summary>

View File

@@ -63,7 +63,7 @@ namespace OpenSim.Framework.Servers
protected DateTime m_startuptime;
protected string m_startupDirectory = Environment.CurrentDirectory;
protected string m_pidFile = string.Empty;
protected string m_pidFile = String.Empty;
protected ServerStatsCollector m_serverStatsCollector;
@@ -90,7 +90,7 @@ namespace OpenSim.Framework.Servers
using (FileStream fs = File.Create(path))
{
byte[] buf = Encoding.ASCII.GetBytes(pidstring);
Byte[] buf = Encoding.ASCII.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
}
@@ -116,7 +116,8 @@ namespace OpenSim.Framework.Servers
{
m_log.Error($"[SERVER BASE]: Error whilst removing {m_pidFile}", e);
}
m_pidFile = string.Empty;
m_pidFile = String.Empty;
}
}

View File

@@ -26,10 +26,10 @@
*/
using System;
using System.Collections;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using log4net;
@@ -78,6 +78,7 @@ namespace OpenSim.Framework
private readonly int m_mapStride;
private readonly int m_mapPatchsStride;
// legacy CompressionFactor
public float CompressionFactor { get; private set; }
@@ -100,7 +101,6 @@ namespace OpenSim.Framework
public float this[int x, int y]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_heightmap[x, y]; }
set
{
@@ -115,9 +115,7 @@ namespace OpenSim.Framework
public float this[int x, int y, int z]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return this[x, y]; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set { this[x, y] = value; }
}
@@ -244,7 +242,7 @@ namespace OpenSim.Framework
m_heightmap[xx, yy] = pHeight;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTainted()
{
return m_taints.IsTaited();
@@ -253,7 +251,7 @@ namespace OpenSim.Framework
// Return 'true' of the patch that contains these region coordinates has been modified.
// Note that checking the taint clears it.
// There is existing code that relies on this feature.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAt(int xx, int yy, bool clearOnTest)
{
yy /= Constants.TerrainPatchSize;
@@ -261,45 +259,45 @@ namespace OpenSim.Framework
return m_taints.Get(indx, clearOnTest);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAt(int xx, int yy)
{
yy /= Constants.TerrainPatchSize;
return m_taints.Get(xx / Constants.TerrainPatchSize + yy * m_taintSizeX);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAtPatch(int xx, int yy, bool clearOnTest)
{
int indx = xx + yy * m_taintSizeX;
return m_taints.Get(indx, clearOnTest);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAtPatch(int xx, int yy)
{
return m_taints.Get(xx + yy * m_taintSizeX);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAtPatch(int indx, bool clearOnTest)
{
return m_taints.Get(indx, clearOnTest);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAtPatchWithClear(int indx)
{
return m_taints.GetAndClear(indx);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public bool IsTaintedAtPatch(int indx)
{
return m_taints.Get(indx);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public int GetAndClearNextTaint(int startIndex)
{
return m_taints.GetAndClearNextTrue(startIndex);
@@ -471,6 +469,7 @@ namespace OpenSim.Framework
for (int jj = 0; jj < SizeY; jj++)
{
m_heightmap[ii, jj] = (float)pTerrain[ii, jj];
}
}
// m_log.DebugFormat("{0} new by doubles. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ);
@@ -631,34 +630,37 @@ namespace OpenSim.Framework
Array ret = null;
try
{
using (MemoryStream inp = new MemoryStream((2 * sizeof(int)) + (SizeX * SizeY * sizeof(float))))
using (MemoryStream inp = new MemoryStream((2 * sizeof(Int32)) + (SizeX * SizeY * sizeof(float))))
{
using (BinaryWriter bw = new BinaryWriter(inp))
{
bw.Write(SizeX);
bw.Write(SizeY);
bw.Write((Int32)SizeX);
bw.Write((Int32)SizeY);
for (int yy = 0; yy < SizeY; yy++)
for (int xx = 0; xx < SizeX; xx++)
{
//bw.Write((float)m_heightmap[xx, yy]);
bw.Write(MathF.Round(m_heightmap[xx, yy], 3, MidpointRounding.AwayFromZero));
}
bw.Flush();
inp.Seek(0, SeekOrigin.Begin);
using MemoryStream outputStream = new MemoryStream();
using GZipStream compressionStream = new(outputStream, CompressionMode.Compress);
inp.CopyTo(compressionStream);
compressionStream.Flush();
ret = outputStream.ToArray();
using (MemoryStream outputStream = new MemoryStream())
{
using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress))
{
inp.CopyStream(compressionStream, int.MaxValue);
compressionStream.Close();
ret = outputStream.ToArray();
}
}
}
}
m_log.Debug($"{LogHeader} V2DGzip {ret.Length} bytes");
}
catch (Exception ex)
{
m_log.Error($"{LogHeader} V2DGzip error: {ex.Message}");
}
catch {}
m_log.DebugFormat("{0} V2DGzip {1} bytes", LogHeader, ret.Length);
return ret;
}
@@ -785,6 +787,7 @@ namespace OpenSim.Framework
{
using (GZipStream decompressionStream = new GZipStream(inputStream, CompressionMode.Decompress))
{
decompressionStream.Flush();
decompressionStream.CopyTo(outputStream);
}
}

View File

@@ -2546,9 +2546,7 @@ namespace OpenSim.Framework
(byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
(byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
(byte)x, (byte)(x >> 8), 0, 0,
(byte)y, (byte)(y >> 8), 0, 0
};
(byte)y, (byte)(y >> 8), 0, 0 };
return new UUID(bytes, 0);
}
@@ -2559,8 +2557,7 @@ namespace OpenSim.Framework
(byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
(byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
(byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
(byte)y, (byte)(y >> 8), 0, 0
};
(byte)y, (byte)(y >> 8), 0, 0 };
return new UUID(bytes, 0);
}

View File

@@ -53,11 +53,11 @@ namespace OpenSim
public static string GetVersionString(string versionNumber, Flavour flavour)
{
string versionString = $"OpenSim {versionNumber} Nessie {flavour}";
string versionString = $"OpenSim/lickx {versionNumber} {flavour}";
return versionString.PadRight(VERSIONINFO_VERSION_LENGTH);
}
public const int VERSIONINFO_VERSION_LENGTH = 27;
public const int VERSIONINFO_VERSION_LENGTH = 26;
/// <value>
/// This is the external interface version. It is separate from the OpenSimulator project version.

View File

@@ -316,6 +316,7 @@ namespace OpenSim.Framework
return;
OSD otmp;
if (map.TryGetValue("day_cycle", out otmp) && otmp is OSDMap)
{
Cycle = new DayCycle();

View File

@@ -26,7 +26,6 @@
*/
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
@@ -37,7 +36,6 @@ using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
@@ -49,6 +47,7 @@ using OpenSim.Framework.ServiceAuth;
using System.Net.Http;
using System.Security.Authentication;
using System.Runtime.CompilerServices;
using System.Threading;
namespace OpenSim.Framework
{
@@ -340,7 +339,7 @@ namespace OpenSim.Framework
output = output[..MaxRequestDiagLength] + "...";
}
m_log.Debug($"[LOGHTTP]: {context} {Util.BinaryToASCII(output)}");
m_log.DebugFormat($"[LOGHTTP]: {context}{Util.BinaryToASCII(output)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -425,8 +424,7 @@ namespace OpenSim.Framework
responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
responseMessage.EnsureSuccessStatusCode();
using CancellationTokenSource cts = new(30000);
Stream resStream = responseMessage.Content.ReadAsStream(cts.Token);
Stream resStream = responseMessage.Content.ReadAsStream();
if (resStream is not null)
{
using StreamReader reader = new(resStream);
@@ -534,6 +532,7 @@ namespace OpenSim.Framework
{
int reqnum = RequestNumber++;
string method = (data is not null && data["RequestMethod"] is not null) ? data["RequestMethod"] : "unknown";
if (DebugLevel >= 3)
m_log.Debug($"[LOGHTTP]: HTTP OUT {reqnum} ServiceForm '{method}' to {url}");
@@ -591,8 +590,7 @@ namespace OpenSim.Framework
responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
responseMessage.EnsureSuccessStatusCode();
using CancellationTokenSource cts = new(30000);
using StreamReader reader = new(responseMessage.Content.ReadAsStream(cts.Token));
using StreamReader reader = new(responseMessage.Content.ReadAsStream());
string responseStr = reader.ReadToEnd();
rcvlen = responseStr.Length;
if (DebugLevel >= 5)
@@ -806,18 +804,18 @@ namespace OpenSim.Framework
/// </remarks>
public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(8196);
byte[] buffer = new byte[4096];
int readBytes;
int totalCopiedBytes = 0;
while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(8196, maximumBytesToCopy))) > 0)
while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
{
int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
copyTo.Write(buffer, 0, writeBytes);
totalCopiedBytes += writeBytes;
maximumBytesToCopy -= writeBytes;
}
ArrayPool<byte>.Shared.Return(buffer);
return totalCopiedBytes;
}
@@ -1151,7 +1149,7 @@ namespace OpenSim.Framework
HttpResponseMessage responseMessage = null;
HttpRequestMessage request = null;
HttpClient client = null;
string respstring = string.Empty;
string respstring = String.Empty;
int sendlen = 0;
int rcvlen = 0;
try
@@ -1163,7 +1161,7 @@ namespace OpenSim.Framework
auth?.AddAuthorization(request.Headers);
request.Headers.ExpectContinue = false;
request.Headers.TransferEncodingChunked = false;
request.Headers.TransferEncodingChunked = false; if (timeoutsecs > 0)
if (keepalive)
{
@@ -1194,8 +1192,7 @@ namespace OpenSim.Framework
if ((responseMessage.Content.Headers.ContentLength is long contentLength) && contentLength != 0)
{
using CancellationTokenSource cts = new(30000);
using StreamReader reader = new(responseMessage.Content.ReadAsStream(cts.Token));
using StreamReader reader = new(responseMessage.Content.ReadAsStream());
respstring = reader.ReadToEnd();
rcvlen = respstring.Length;
}
@@ -1280,8 +1277,7 @@ namespace OpenSim.Framework
if ((responseMessage.Content.Headers.ContentLength is long contentLength) && contentLength != 0)
{
using CancellationTokenSource cts = new(30000);
using StreamReader reader = new(responseMessage.Content.ReadAsStream(cts.Token));
using StreamReader reader = new(responseMessage.Content.ReadAsStream());
respstring = reader.ReadToEnd();
}
}
@@ -1424,7 +1420,7 @@ namespace OpenSim.Framework
request.Content.Headers.TryAddWithoutValidation("Content-Length", sendlen.ToString());
}
responseMessage = client.Send(request, HttpCompletionOption.ResponseContentRead);
responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
responseMessage.EnsureSuccessStatusCode();
int rcvlen = 0;
@@ -1518,7 +1514,7 @@ namespace OpenSim.Framework
//else
// request.Headers.TryAddWithoutValidation("Connection", "close");
responseMessage = client.Send(request, HttpCompletionOption.ResponseContentRead);
responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
responseMessage.EnsureSuccessStatusCode();
int rcvlen = 0;

View File

@@ -126,7 +126,7 @@ namespace OpenSim
// Configure Log4Net
configSource.AddSwitch("Startup", "logconfig");
string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", string.Empty);
string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
if (!string.IsNullOrEmpty(logConfigFile))
{
XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));

View File

@@ -38,6 +38,7 @@ using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
using System.Net;
using System.Runtime.InteropServices;
using log4net;
using NDesk.Options;
using Nini.Config;
@@ -79,6 +80,7 @@ namespace OpenSim
private string m_timedScript = "disabled";
private int m_timeInterval = 1200;
private System.Timers.Timer m_scriptTimer;
private PosixSignalRegistration m_signalReg;
public OpenSim(IConfigSource configSource) : base(configSource)
{
@@ -132,6 +134,12 @@ namespace OpenSim
m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod);
m_log.InfoFormat("[OPENSIM MAIN] Running GC in {0} mode", GCSettings.IsServerGC ? "server":"workstation");
m_signalReg = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
{
m_log.Info("Received SIGTERM, shutting down");
MainConsole.Instance.RunCommand("shutdown");
});
}
/// <summary>
@@ -299,11 +307,7 @@ namespace OpenSim
+ " --mergeReplaceObjects if scene as a object with same id, replace it\n"
+ " without this option, skip loading that object\n"
+ "--skip-assets will load the OAR but ignore the assets it contains.\n"
+ "--force-assets will load the OAR and try to upload the assets it contains.\n"
+ " it will REPLACE those assets on local region cache\n"
+ " it will also try to upload them to service, but that only work if they are not present"
+ " Avoid using this except for some recovery attempts"
+ "--default-user will use this user for any objects with an owner whose UUID is not found in the grid.\n"
+ "--default-user will use this user for any objects and parcels with an owner whose UUID is not found in the grid.\n"
+ "--no-objects suppresses the addition of any objects (good for loading only the terrain).\n"
+ "--rotation specified rotation to be applied to the oar. Specified in degrees.\n"
+ "--bounding-origin will only place objects that after displacement and rotation fall within the bounding cube who's position starts at <x,y,z>. Defaults to <0,0,0>.\n"
@@ -321,7 +325,7 @@ namespace OpenSim
m_console.Commands.AddCommand("Archiving", false, "save oar",
//"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]",
"save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]",
"save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [--tenant=<uuid>] [<OAR path>]",
"Save a region's data to an OAR archive.",
// "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine
"-h|--home=<url> adds the url of the profile service to the saved user information.\n"
@@ -331,6 +335,7 @@ namespace OpenSim
+ " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n"
+ "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n"
+ " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n"
+ "--tenant=<uuid> only save objects owned by tenant with uuid.\n"
+ "--all saves all the regions in the simulator, instead of just the current region.\n"
+ "The OAR path must be a filesystem path."
+ " If this is not given then the oar is saved to region.oar in the current directory.",
@@ -524,8 +529,8 @@ namespace OpenSim
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
if (presence.Firstname.Equals(mainParams[2], StringComparison.OrdinalIgnoreCase) &&
presence.Lastname.Equals(mainParams[3],StringComparison.OrdinalIgnoreCase))
if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) &&
presence.Lastname.ToLower().Equals(mainParams[3].ToLower()))
{
MainConsole.Instance.Output(
"Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}",
@@ -1520,5 +1525,7 @@ namespace OpenSim
result = result.TrimEnd(' ');
return result;
}
}
}

View File

@@ -855,8 +855,6 @@ namespace OpenSim.Region.ClientStack.Linden
int skipedMeshs = 0;
float primScaleMin = m_ModelCost.PrimScaleMin;
OSD tmp;
// build prims from instances
for (int i = 0; i < instance_list.Count; i++)
{
@@ -872,58 +870,71 @@ namespace OpenSim.Region.ClientStack.Linden
}
OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
PrimitiveBaseShape pbs = null;
if (inner_instance_list.TryGetValue("mesh", out tmp)) // seems to happen always but ...
if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
{
int meshindx = tmp.AsInteger();
if (meshindx >= 0 && meshAssets.Count > meshindx)
int meshindx = inner_instance_list["mesh"].AsInteger();
if (meshAssets.Count > meshindx)
{
if(meshesSides != null && meshesSides.Length > meshindx)
pbs = PrimitiveBaseShape.CreateMesh(meshesSides[meshindx], meshAssets[meshindx]);
pbs = PrimitiveBaseShape.CreateMesh(meshesSides[i], meshAssets[meshindx]);
else
pbs = PrimitiveBaseShape.CreateMesh(face_list.Count, meshAssets[meshindx]);
}
}
if(pbs == null) // fallback
pbs = PrimitiveBaseShape.CreateBox();
pbs ??= PrimitiveBaseShape.CreateBox(); //fallback
Primitive.TextureEntry textureEntry = new(Primitive.TextureEntry.WHITE_TEXTURE);
Primitive.TextureEntry textureEntry
= new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
for (uint face = 0; face < face_list.Count; face++)
{
OSDMap faceMap = (OSDMap)face_list[(int)face];
Primitive.TextureEntryFace f = textureEntry.CreateFace(face); //clone the default
if (faceMap.ContainsKey("fullbright"))
f.Fullbright = faceMap["fullbright"].AsBoolean();
if (faceMap.ContainsKey("diffuse_color"))
f.RGBA = faceMap["diffuse_color"].AsColor4();
if (faceMap.TryGetBool("fullbright", out bool fullbright))
f.Fullbright = fullbright;
int textureNum = faceMap["image"].AsInteger();
float imagerot = faceMap["imagerot"].AsInteger();
float offsets = (float)faceMap["offsets"].AsReal();
float offsett = (float)faceMap["offsett"].AsReal();
float scales = (float)faceMap["scales"].AsReal();
float scalet = (float)faceMap["scalet"].AsReal();
if (faceMap.TryGetColor4("diffuse_color", out Color4 rgba))
f.RGBA = rgba;
if(faceMap.TryGetInt("image", out int textureNum) && textureNum >= 0 && textureNum < textures.Count)
f.TextureID = textures[textureNum];
if(faceMap.TryGetFloat("imagerot", out float imagerot) && imagerot != 0)
if (imagerot != 0)
f.Rotation = imagerot;
if(faceMap.TryGetFloat("offsets", out float offsets) && offsets != 0)
if (offsets != 0)
f.OffsetU = offsets;
if(faceMap.TryGetFloat("offsett", out float offsett) && offsett != 0)
if (offsett != 0)
f.OffsetV = offsett;
if(faceMap.TryGetFloat("scales", out float scales) && scales != 0)
if (scales != 0)
f.RepeatU = scales;
if(faceMap.TryGetFloat("scalet", out float scalet) && scalet != 0)
if (scalet != 0)
f.RepeatV = scalet;
if (textures.Count > textureNum)
f.TextureID = textures[textureNum];
textureEntry.FaceTextures[face] = f;
}
pbs.TextureEntry = textureEntry.GetBytes(face_list.Count);
if(face_list.Count > 0)
{
int last = face_list.Count - 1;
// we do need a better te compacting code
textureEntry.DefaultTexture = textureEntry.FaceTextures[last];
textureEntry.FaceTextures[last] = null;
pbs.TextureEntry = textureEntry.GetBytes(last);
}
Vector3 position = inner_instance_list["position"].AsVector3();
Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

View File

@@ -168,5 +168,6 @@ namespace OpenSim.Region.ClientStack.Linden
{
_ = new BunchOfCaps(m_Scene, agentID, caps, ConfigOptions);
}
}
}

View File

@@ -28,7 +28,6 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Collections.Generic;
using System.Text;
@@ -36,22 +35,27 @@ using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Capabilities;
using Nini.Config;
using log4net;
using System.Reflection;
using System.IO.Compression;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using Nini.Config;
namespace OpenSim.Region.ClientStack.Linden
{
public struct ModelPrimLimits
{
}
public class ModelCost
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// upload fee defaults
// fees are normalized to 1.0
@@ -98,6 +102,7 @@ namespace OpenSim.Region.ClientStack.Linden
public float PhysicalPrimScaleMax = 10f;
public int ObjectLinkedPartsMax = 512;
public ModelCost(Scene scene)
{
PrimScaleMin = scene.m_minNonphys;
@@ -159,7 +164,7 @@ namespace OpenSim.Region.ClientStack.Linden
if (ObjectLinkedPartsMax != 0 && numberInstances > ObjectLinkedPartsMax)
{
error = $"Model would have more than {ObjectLinkedPartsMax} linked prims";
error = "Model would have more than " + ObjectLinkedPartsMax.ToString() + " linked prims";
return false;
}
@@ -178,7 +183,7 @@ namespace OpenSim.Region.ClientStack.Linden
// textures cost
if (resources.texture_list != null && resources.texture_list.Array.Count > 0)
{
float textures_cost = resources.texture_list.Array.Count * basicCost;
float textures_cost = (float)(resources.texture_list.Array.Count * basicCost);
textures_cost *= ModelTextureCostFactor;
itmp = (int)(textures_cost + 0.5f); // round
@@ -194,7 +199,7 @@ namespace OpenSim.Region.ClientStack.Linden
bool curskeleton;
bool curAvatarPhys;
List<ameshCostParam> meshsCosts = [];
List<ameshCostParam> meshsCosts = new List<ameshCostParam>();
if (resources.mesh_list != null && resources.mesh_list.Array.Count > 0)
{
@@ -231,7 +236,7 @@ namespace OpenSim.Region.ClientStack.Linden
int mesh;
List<string> skipedSmall = [];
int skipedSmall = 0;
for (int i = 0; i < numberInstances; i++)
{
Hashtable inst = (Hashtable)resources.instance_list.Array[i];
@@ -248,14 +253,13 @@ namespace OpenSim.Region.ClientStack.Linden
if (scale.X < PrimScaleMin || scale.Y < PrimScaleMin || scale.Z < PrimScaleMin)
{
//m_log.WarnFormat("[MESHUPLOADER]: Mesh {0} below min scale", inst["mesh_name"].ToString());
skipedSmall.Add(inst["mesh_name"].ToString());
skipedSmall++;
continue;
}
if (scale.X > NonPhysicalPrimScaleMax || scale.Y > NonPhysicalPrimScaleMax || scale.Z > NonPhysicalPrimScaleMax)
{
error = $"Model contains parts with sides larger than {NonPhysicalPrimScaleMax}m. Please ajust scale";
error = "Model contains parts with sides larger than " + NonPhysicalPrimScaleMax.ToString() + "m. Please ajust scale";
return false;
}
@@ -263,9 +267,9 @@ namespace OpenSim.Region.ClientStack.Linden
{
mesh = (int)inst["mesh"];
if (mesh < 0 || mesh >= numberMeshs)
if (mesh >= numberMeshs)
{
error = "Incoherent model information.";
error = "Incoerent model information.";
return false;
}
@@ -293,43 +297,18 @@ namespace OpenSim.Region.ClientStack.Linden
meshsfee += primCreationCost;
}
if (skipedSmall.Count > 0)
if (skipedSmall > 0)
{
if (skipedSmall.Count > numberInstances / 2)
if (skipedSmall > numberInstances / 2)
{
error = $"Model contains too many prims smaller than {PrimScaleMin}m minimum allowed size. Please check scaling";
error = "Model contains too many prims smaller than " + PrimScaleMin.ToString() +
"m minimum allowed size. Please check scalling";
return false;
}
else
{
StringBuilder sb = new(256);
sb.Append(skipedSmall.Count);
sb.Append(" of the requested ");
sb.Append(numberInstances);
sb.Append(" model prims will not upload because they are smaller than ");
sb.Append(PrimScaleMin);
sb.Append("m minimum allowed size. Please check scaling of: ");
// The modal has a limited size, so need to cut somewhere
int i = 0;
int t = skipedSmall[i].Length + 1;
while (t < 119)
{
sb.Append(skipedSmall[i]);
sb.Append(' ');
i++;
if(i >= skipedSmall.Count)
break;
t += skipedSmall[i].Length + 1;
}
if (t >= 119 && i < skipedSmall.Count)
{
int c = t - skipedSmall[i].Length + 1;
sb.Append(skipedSmall[i].AsSpan(0, 117 - c));
sb.Append("...");
}
warning += sb.ToString();
}
warning += skipedSmall.ToString() + " of the requested " +numberInstances.ToString() +
" model prims will not upload because they are smaller than " + PrimScaleMin.ToString() +
"m minimum allowed size. Please check scalling ";
}
if (meshcostdata.physics_cost <= meshcostdata.model_streaming_cost)
@@ -588,10 +567,17 @@ namespace OpenSim.Region.ClientStack.Linden
{
using (MemoryStream outMs = new MemoryStream())
{
using (MemoryStream inMs = new MemoryStream(data, offset + 2, size - 2))
using (MemoryStream inMs = new MemoryStream(data, offset, size))
{
using DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress);
decompressionStream.CopyTo(outMs);
using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
{
byte[] readBuffer = new byte[2048];
inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
int readLen = 0;
while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
outMs.Write(readBuffer, 0, readLen);
}
}
outMs.Seek(0, SeekOrigin.Begin);
decodedMeshOsd = OSDParser.DeserializeLLSDBinary(outMs);
@@ -612,7 +598,7 @@ namespace OpenSim.Region.ClientStack.Linden
if (subMeshOsd is OSDMap)
{
OSDMap subtmpmap = (OSDMap)subMeshOsd;
if (subtmpmap.ContainsKey("NoGeometry"))
if (subtmpmap.ContainsKey("NoGeometry") && ((OSDBoolean)subtmpmap["NoGeometry"]))
continue;
if (!subtmpmap.ContainsKey("Position"))

View File

@@ -184,7 +184,6 @@ namespace OpenSim.Region.ClientStack.Linden
if (m_ExportSupported)
extrasMap["ExportSupported"] = true;
m_features["OpenSimExtras"] = extrasMap;
}
}
@@ -435,7 +434,7 @@ namespace OpenSim.Region.ClientStack.Linden
while ((s = sr.ReadLine()) is not null)
{
s = s.Trim(trimc);
if (string.IsNullOrEmpty(s) || s.StartsWith("<!--"))
if (String.IsNullOrEmpty(s) || s.StartsWith("<!--"))
continue;
sb.Append(s);
}

View File

@@ -410,10 +410,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
set { m_startpos = value; }
}
public float StartFar { get; set; }
public float FOV { get; set; } = 1.04f;
public float FOV { get; set; } = 1.25f;
public int viewHeight { get; set; } = 480;
public int viewWidth { get; set; } = 640;
public UUID AgentId { get { return m_agentId; } }
public UUID ScopeId { get { return m_scopeId; } }
public ISceneAgent SceneAgent { get; set; }
@@ -875,6 +876,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
0xff, 0xff, 0, 1, 148 // ID 148 (low frequency bigendian) zero encoded
};
public void SendRegionHandshake()
{
GetViewerCaps(); // make sure this is up to date
@@ -3194,6 +3196,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OutPacket(viewertime, ThrottleOutPacketType.Task);
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
ViewerEffectPacket packet = (ViewerEffectPacket)PacketPool.Instance.GetPacket(PacketType.ViewerEffect);
@@ -3214,10 +3218,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP
AvatarPropertiesReplyPacket avatarReply = (AvatarPropertiesReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPropertiesReply);
avatarReply.AgentData.AgentID = m_agentId;
avatarReply.AgentData.AvatarID = avatarID;
avatarReply.PropertiesData.AboutText = aboutText == null ? [] : Util.StringToBytes1024(aboutText);
if (aboutText != null)
avatarReply.PropertiesData.AboutText = Util.StringToBytes1024(aboutText);
else
avatarReply.PropertiesData.AboutText = Utils.EmptyBytes;
avatarReply.PropertiesData.BornOn = Util.StringToBytes256(bornOn);
avatarReply.PropertiesData.CharterMember = membershipType;
avatarReply.PropertiesData.FLAboutText = flAbout == null ? [] : Util.StringToBytes256(flAbout);
if (flAbout != null)
avatarReply.PropertiesData.FLAboutText = Util.StringToBytes256(flAbout);
else
avatarReply.PropertiesData.FLAboutText = Utils.EmptyBytes;
avatarReply.PropertiesData.Flags = flags;
avatarReply.PropertiesData.FLImageID = flImageID;
avatarReply.PropertiesData.ImageID = imageID;
@@ -3401,6 +3411,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
*/
}
public void SendPartPhysicsProprieties(ISceneEntity entity)
{
IEventQueue eq = Scene.RequestModuleInterface<IEventQueue>();
@@ -3677,15 +3688,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OutPacket(reply, ThrottleOutPacketType.Land);
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, int options)
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
ScriptTeleportRequestPacket packet = (ScriptTeleportRequestPacket)PacketPool.Instance.GetPacket(PacketType.ScriptTeleportRequest);
packet.Header.Zerocoded = true;
packet.Data.ObjectName = Utils.StringToBytes(objName);
packet.Data.SimName = Utils.StringToBytes(simName);
packet.Data.SimPosition = pos;
packet.Data.LookAt = Vector3.Zero;
packet.Options = options == 3 ? [] : [ new(){Flags = (uint)options } ];
packet.Data.LookAt = lookAt;
OutPacket(packet, ThrottleOutPacketType.Task);
}
@@ -4174,7 +4184,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
an.Data = new AvatarNotesReplyPacket.DataBlock
{
TargetID = targetID,
Notes = Utils.StringToBytes(text, 1022)
Notes = Utils.StringToBytes(text)
};
OutPacket(an, ThrottleOutPacketType.Task);
@@ -7534,7 +7544,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
zc.AddShortLimitedUTF8(osUTF8PartText);
//textcolor
zc.AddColorArgb(part.TextColorArgb());
byte[] tc = part.GetTextColor().GetBytes(false);
zc.AddBytes(tc, 4);
}
//media url
@@ -7954,6 +7965,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
else
BlockLengh += extraParamBytes.Length;
byte[] hoverTextColor = null;
osUTF8 osUTF8PartText = part.osUTF8Text;
if (osUTF8PartText != null && osUTF8PartText.Length > 0)
{
@@ -7961,7 +7973,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
BlockLengh += osUTF8PartText.Length;
if (osUTF8PartText[^1] != 0)
++BlockLengh;
BlockLengh += 4;
hoverTextColor = part.GetTextColor().GetBytes(false);
BlockLengh += hoverTextColor.Length;
hastext = true;
}
@@ -8047,6 +8060,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
pathScaleY = 150;
}
// first is primFlags
zc.AddUInt((uint)primflags);
@@ -8088,8 +8102,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
zc.AddBytes(osUTF8PartText.GetArray(), osUTF8PartText.Length);
if (osUTF8PartText[^1] != 0)
zc.AddZeros(1);
zc.AddColorArgb(part.TextColorArgb());
zc.AddBytes(hoverTextColor, hoverTextColor.Length);
}
if (hasmediaurl)
{
@@ -8522,7 +8535,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
)
return true;
float qdelta = MathF.Abs(x.BodyRotation.Dot(ref m_thisAgentUpdateArgs.BodyRotation));
float qdelta = MathF.Abs(x.BodyRotation.Dot(m_thisAgentUpdateArgs.BodyRotation));
return qdelta < QDELTABody; // significant if body rotation above(below cos) threshold
}
@@ -9306,6 +9319,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
avSetStartLocationRequestPacket.StartLocationData.LocationPos.Y = avatar.AbsolutePosition.Y;
}
}
}
c.OnSetStartLocationRequest?.Invoke(c, 0, avSetStartLocationRequestPacket.StartLocationData.LocationPos,
avSetStartLocationRequestPacket.StartLocationData.LocationLookAt,
@@ -9550,7 +9564,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
bool IsPhantom = (data[48] != 0) ? true : false;
handlerUpdatePrimFlags(flags.AgentData.ObjectLocalID, UsePhysics, IsTemporary, IsPhantom, this);
*/
bool UsePhysics = flags.AgentData.UsePhysics;
bool UsePhysics = flags.AgentData.UsePhysics;
bool IsPhantom = flags.AgentData.IsPhantom;
bool IsTemporary = flags.AgentData.IsTemporary;
ObjectFlagUpdatePacket.ExtraPhysicsBlock[] blocks = flags.ExtraPhysics;
@@ -11190,6 +11204,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private static void HandleGetScriptRunning(LLClientView c, Packet Pack)
{
GetScriptRunningPacket scriptRunning = (GetScriptRunningPacket)Pack;
c.OnGetScriptRunning?.Invoke(c, scriptRunning.Script.ObjectID, scriptRunning.Script.ItemID);
}

View File

@@ -144,7 +144,30 @@ namespace OpenSim.Region.ClientStack.LindenUDP
UpdateImageInQueue(imgrequest);
imgrequest.RunUpdate();
// J2KImage imgrequest2 = new J2KImage(this);
// imgrequest2.J2KDecoder = m_j2kDecodeModule;
// imgrequest2.AssetService = m_assetCache;
// imgrequest2.AgentID = m_client.AgentId;
// imgrequest2.InventoryAccessModule = m_client.Scene.RequestModuleInterface<IInventoryAccessModule>();
// imgrequest2.DiscardLevel = newRequest.DiscardLevel;
// imgrequest2.StartPacket = Math.Max(1, newRequest.PacketNumber);
// imgrequest2.Priority = newRequest.Priority;
// imgrequest2.TextureID = newRequest.RequestedAssetID;
// imgrequest2.Priority = newRequest.Priority;
//
// //Add this download to the priority queue
// AddImageToQueue(imgrequest2);
//
// imgrequest2.RunUpdate();
}
// else
// {
// m_log.DebugFormat(
// "[LL IMAGE MANAGER]: Ignoring duplicate of existing request for {0} (sequence {1}) from {2} as its request sequence {3} is not greater",
// newRequest.RequestedAssetID, imgrequest.LastSequence, m_client.Name, newRequest.requestSequence);
// }
}
}
else

View File

@@ -29,7 +29,6 @@ using System;
using System.Runtime.CompilerServices;
using OpenSim.Framework;
using OpenMetaverse;
using System.Runtime.InteropServices;
namespace OpenSim.Region.ClientStack.LindenUDP
{
@@ -89,13 +88,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public unsafe void AddZeros(int len)
{
zerocount += len;
ref byte dst = ref MemoryMarshal.GetArrayDataReference(m_dest);
while (zerocount > 0xff)
{
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = 0xff;
pos++;
m_dest[pos++] = 0x00;
m_dest[pos++] = 0xff;
zerocount -= 256;
}
}
@@ -105,53 +101,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
if (zerocount > 0)
{
ref byte dst = ref MemoryMarshal.GetArrayDataReference(m_dest);
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = (byte)zerocount;
pos++;
m_dest[pos++] = 0x00;
m_dest[pos++] = (byte)zerocount;
}
return pos;
}
public unsafe void AddBytes(byte[] src, int srclen)
{
ref byte dst = ref MemoryMarshal.GetArrayDataReference(m_dest);
for (int i = 0; i < srclen; ++i)
{
byte b = src[i];
if (b == 0x00)
{
if (zerocount != 0xff)
zerocount++;
else
{
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = 0xff;
pos++;
zerocount = 1;
}
}
else
{
if (zerocount != 0)
{
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = (byte)zerocount;
pos++;
zerocount = 0;
}
Unsafe.Add(ref dst, pos) = b;
pos++;
}
}
}
public unsafe void AddBytes(byte* src, int srclen)
{
ref byte dst = ref MemoryMarshal.GetArrayDataReference(m_dest);
for (int i = 0; i < srclen; ++i)
{
if (src[i] == 0x00)
@@ -160,10 +117,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
zerocount++;
else
{
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = 0xff;
pos++;
m_dest[pos++] = 0x00;
m_dest[pos++] = 0xff;
zerocount = 1;
}
}
@@ -171,19 +126,46 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
if (zerocount != 0)
{
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = (byte)zerocount;
pos++;
m_dest[pos++] = 0x00;
m_dest[pos++] = (byte)zerocount;
zerocount = 0;
}
Unsafe.Add(ref dst, pos) = src[i];
pos++;
m_dest[pos++] = src[i];
}
}
}
public void AddByte(byte v)
public unsafe void AddBytes(byte* src, int srclen)
{
for (int i = 0; i < srclen; ++i)
{
if (src[i] == 0x00)
{
if (zerocount != 0xff)
zerocount++;
else
{
m_dest[pos++] = 0x00;
m_dest[pos++] = 0xff;
zerocount = 1;
}
}
else
{
if (zerocount != 0)
{
m_dest[pos++] = 0x00;
m_dest[pos++] = (byte)zerocount;
zerocount = 0;
}
m_dest[pos++] = src[i];
}
}
}
public unsafe void AddByte(byte v)
{
if (v == 0x00)
{
@@ -191,27 +173,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP
zerocount++;
else
{
ref byte dst = ref MemoryMarshal.GetArrayDataReference(m_dest);
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = 0xff;
pos++;
m_dest[pos++] = 0x00;
m_dest[pos++] = 0xff;
zerocount = 1;
}
}
else
{
ref byte dst = ref MemoryMarshal.GetArrayDataReference(m_dest);
if (zerocount != 0)
{
Unsafe.Add(ref dst, pos) = 0x00;
pos++;
Unsafe.Add(ref dst, pos) = (byte)zerocount;
pos++;
m_dest[pos++] = 0x00;
m_dest[pos++] = (byte)zerocount;
zerocount = 0;
}
Unsafe.Add(ref dst, pos) = v;
pos++;
m_dest[pos++] = v;
}
}
@@ -356,23 +332,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
AddBytes(b, 16);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddColorArgb(int argb)
{
uint ua = (uint)argb ^ 0xff000000;
if(ua == 0)
{
AddZeros(4);
}
else
{
AddByte((byte)(ua >> 16));
AddByte((byte)(ua >> 8));
AddByte((byte)ua);
AddByte((byte)(ua >> 24));
}
}
// maxlen <= 255 and includes null termination byte
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void AddShortString(string str, int maxlen)

View File

@@ -82,6 +82,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public CancellationTokenSource InboundCancellationSource = new();
/// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary>
/// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks>
internal bool m_IsRunningOutbound;
@@ -199,6 +200,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
const int SIO_UDP_CONNRESET = -1744830452;
m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try

View File

@@ -31,7 +31,7 @@ using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using Mono.Addins;
using Nini.Config;
@@ -41,6 +41,7 @@ using CSJ2K;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
@@ -136,9 +137,9 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
// If it's cached, return the cached results
if (m_decodedCache.TryGetValue(assetID, out result))
{
//m_log.DebugFormat(
// "[J2KDecoderModule]: Returning existing cached {0} layers j2k decode for {1}",
// result.Length, assetID);
// m_log.DebugFormat(
// "[J2KDecoderModule]: Returning existing cached {0} layers j2k decode for {1}",
// result.Length, assetID);
callback(assetID, result);
}
@@ -185,9 +186,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
public Image DecodeToImage(byte[] j2kData)
{
if (m_useCSJ2K)
{
return J2kImage.FromBytes(j2kData);
}
else
{
ManagedImage mimage;
@@ -369,7 +368,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
}
else if (Cache != null)
{
string assetName = "j2k" + AssetId.ToString();
string assetName = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset;
Cache.Get(assetName, out layerDecodeAsset);

View File

@@ -381,7 +381,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
ad.AttachmentObjectStates = null;
if (attachments.Count > 0)
m_scene.IncomingAttechments(sp, attachments);
m_scene.IncomingAttachments(sp, attachments);
else
sp.GotAttachmentsData = true;
}

View File

@@ -263,10 +263,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
{
//m_log.DebugFormat("[HGFRIENDS MODULE]: Entering StatusNotify for {0}", userID);
// First, let's divide the friends on a per-domain basis
List<FriendInfo> locallst = new(friendList.Count);
List<UUID> hglst = new();
Dictionary<string, List<FriendInfo>> friendsPerDomain = new Dictionary<string, List<FriendInfo>>();
foreach (FriendInfo friend in friendList)
{
if (UUID.TryParse(friend.Friend, out UUID friendID))
@@ -284,12 +283,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
if (LocalStatusNotification(userID, friendID, online))
continue;
if (!friendsPerDomain.TryGetValue(url, out List<FriendInfo> lst))
{
lst = new List<FriendInfo>();
friendsPerDomain[url] = lst;
}
lst.Add(friend);
hglst.Add(friendID);
}
}
}
@@ -299,8 +293,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
if (locallst.Count > 0)
base.StatusNotify(locallst, userID, online);
if(friendsPerDomain.Count > 0)
m_StatusNotifier.Notify(userID, friendsPerDomain, online);
if(hglst.Count > 0)
m_StatusNotifier.Notify(userID, hglst, online);
//m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting StatusNotify for {0}", userID);
}

View File

@@ -26,6 +26,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
m_FriendsModule = friendsModule;
}
// Currently unused
/*
public void Notify(UUID userID, Dictionary<string, List<FriendInfo>> friendsPerDomain, bool online)
{
if(m_FriendsModule is null)
@@ -33,41 +35,85 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
foreach (KeyValuePair<string, List<FriendInfo>> kvp in friendsPerDomain)
{
// For the others, call the user agent service
List<string> ids = new(kvp.Value.Count);
foreach (FriendInfo f in kvp.Value)
ids.Add(f.Friend);
if (ids.Count == 0)
if (kvp.Value.Count == 0)
continue; // no one to notify. caller don't do this
//m_log.DebugFormat("[HG STATUS NOTIFIER]: Notifying {0} friends in {1}", ids.Count, kvp.Key);
// ASSUMPTION: we assume that all users for one home domain
// have exactly the same set of service URLs.
// If this is ever not true, we need to change this.
if (Util.ParseUniversalUserIdentifier(ids[0], out UUID friendID))
FriendInfo id0Info = kvp.Value[0];
string id0 = id0Info.Friend; // the hgname of the first friend
if (Util.ParseUniversalUserIdentifier(id0, out UUID firstID))
{
string friendsServerURI = m_FriendsModule.UserManagementModule.GetUserServerURL(friendID, "FriendsServerURI");
if (!string.IsNullOrEmpty(friendsServerURI))
{
HGFriendsServicesConnector fConn = new(friendsServerURI);
string friendsServerURI = m_FriendsModule.UserManagementModule.GetUserServerURL(firstID, "FriendsServerURI");
if (string.IsNullOrEmpty(friendsServerURI))
continue;
List<UUID> friendsOnline = fConn.StatusNotification(ids, userID, online);
if (friendsOnline.Count > 0)
HGFriendsServicesConnector fConn = new(friendsServerURI);
List<string> ids = new(kvp.Value.Count);
foreach (FriendInfo f in kvp.Value)
{
if (Util.ParseUniversalUserIdentifier(f.Friend, out UUID friendID))
ids.Add(friendID.ToString());
}
if (ids.Count == 0)
continue;
// Note: first argument in StatusNotification needs to be
// a List<string> of UUIDs, not a List<string> of hgnames!
List<UUID> friendsOnline = fConn.StatusNotification(ids, userID, online);
if (friendsOnline.Count == 0)
continue;
IClientAPI client = m_FriendsModule.LocateClientObject(userID);
if(client is not null)
{
m_log.DebugFormat("[HG STATUS NOTIFIER]: Notifying {0} friends in {1}", friendsOnline.Count, kvp.Key);
m_FriendsModule.CacheFriendsOnline(userID, friendsOnline, online);
if(online)
client?.SendAgentOnline(friendsOnline.ToArray());
else
client?.SendAgentOffline(friendsOnline.ToArray());
}
}
}
}
*/
public void Notify(UUID userID, List<UUID>friendIds, bool online)
{
if(m_FriendsModule is null)
return;
if (friendIds.Count == 0)
return; // no one to notify. caller don't do this
m_log.DebugFormat("[HG STATUS NOTIFIER]: Notifying {0} foreign friends", friendIds.Count);
foreach (UUID friendID in friendIds)
{
string friendsServerURI = m_FriendsModule.UserManagementModule.GetUserServerURL(friendID, "FriendsServerURI");
if (!string.IsNullOrEmpty(friendsServerURI))
{
HGFriendsServicesConnector fConn = new(friendsServerURI);
List<UUID> friendsOnline = fConn.StatusNotification(new List<string> { friendID.ToString() }, userID, online);
if (friendsOnline.Count > 0)
{
IClientAPI client = m_FriendsModule.LocateClientObject(userID);
if(client is not null)
{
IClientAPI client = m_FriendsModule.LocateClientObject(userID);
if(client is not null)
{
m_FriendsModule.CacheFriendsOnline(userID, friendsOnline, online);
if(online)
client?.SendAgentOnline(friendsOnline.ToArray());
else
client?.SendAgentOffline(friendsOnline.ToArray());
}
m_FriendsModule.CacheFriendsOnline(userID, friendsOnline, online);
if(online)
client?.SendAgentOnline(friendsOnline.ToArray());
else
client?.SendAgentOffline(friendsOnline.ToArray());
}
}
}
}
}
}
}

View File

@@ -26,7 +26,9 @@
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
@@ -52,10 +54,10 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected List<Scene> m_Scenes = [];
protected List<Scene> m_Scenes = new List<Scene>();
protected IInstantMessage m_IMService;
protected Dictionary<UUID, object> m_UserLocationMap = new();
protected Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
public event UndeliveredMessage OnUndeliveredMessage;
@@ -64,7 +66,8 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
get
{
m_uMan ??= m_Scenes[0].RequestModuleInterface<IUserManagement>();
if (m_uMan == null)
m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>();
return m_uMan;
}
}
@@ -78,7 +81,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
return;
}
InstantMessageServerConnector imServer = new(config, MainServer.Instance, this);
InstantMessageServerConnector imServer = new InstantMessageServerConnector(config, MainServer.Instance, this);
m_IMService = imServer.GetService();
m_Enabled = true;
}
@@ -90,7 +93,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
lock (m_Scenes)
{
m_log.Debug($"[HG MESSAGE TRANSFER]: Message transfer module {Name} active");
m_log.DebugFormat("[HG MESSAGE TRANSFER]: Message transfer module {0} active", Name);
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
@@ -129,9 +132,9 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
get { return null; }
}
public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result, bool ToRootOnly = false)
public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new(im.toAgentID);
UUID toAgentID = new UUID(im.toAgentID);
if (toAgentID.IsZero())
return;
@@ -156,7 +159,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
}
}
}
if (!ToRootOnly && achildsp != null)
if(achildsp != null)
{
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", user.Name, toAgentID);
achildsp.ControllingClient.SendInstantMessage(im);

View File

@@ -51,9 +51,9 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
protected string m_MessageKey = string.Empty;
protected string m_MessageKey = String.Empty;
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, UUID> m_UserRegionMap = new();
protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
public event UndeliveredMessage OnUndeliveredMessage;
@@ -64,7 +64,8 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
get
{
m_PresenceService ??= m_Scenes[0].RequestModuleInterface<IPresenceService>();
if (m_PresenceService == null)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
return m_PresenceService;
}
}
@@ -79,7 +80,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
return;
}
m_MessageKey = cnf.GetString("MessageKey", string.Empty);
m_MessageKey = cnf.GetString("MessageKey", String.Empty);
}
m_log.Debug("[MESSAGE TRANSFER]: Module enabled");
m_Enabled = true;
@@ -137,7 +138,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
get { return null; }
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result, bool ToRootOnly = false)
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
if (toAgentID.IsZero())
@@ -164,13 +165,14 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
}
}
}
if (!ToRootOnly && achildsp != null)
if (achildsp != null)
{
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", sp.Name, toAgentID);
achildsp.ControllingClient.SendInstantMessage(im);
result(true);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
SendGridInstantMessageViaXMLRPC(im, result);

View File

@@ -206,6 +206,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
return;
}
// Record the creator of this item for user record purposes (which might go away soon)
m_userUuids[inventoryItem.CreatorIdAsUuid] = 1;

View File

@@ -45,22 +45,23 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGLureModule")]
public class HGLureModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private readonly List<Scene> m_scenes = [];
private readonly List<Scene> m_scenes = new List<Scene>();
private IMessageTransferModule m_TransferModule = null;
private bool m_Enabled = false;
private GridInfo m_thisGridInfo;
private readonly ExpiringCacheOS<UUID, GridInstantMessage> m_PendingLures = new(3600000);
private readonly ExpiringCacheOS<UUID, GridInstantMessage> m_PendingLures = new ExpiringCacheOS<UUID, GridInstantMessage>(3600000);
public void Initialise(IConfigSource config)
{
if (config.Configs["Messaging"] != null)
{
if (config.Configs["Messaging"].GetString("LureModule", string.Empty) == Name)
if (config.Configs["Messaging"].GetString("LureModule", string.Empty) == "HGLureModule")
{
m_Enabled = true;
}
@@ -89,7 +90,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
if (m_TransferModule == null)
{
m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
m_TransferModule =
scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
m_log.Error("[LURE MODULE]: No message transfer module, lures will not work!");
@@ -145,7 +148,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
{
if (im.dialog == (byte)InstantMessageDialog.RequestLure)
{
m_TransferModule?.SendInstantMessage(im, delegate (bool success) { }, true);
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate (bool success) { });
}
}
@@ -154,7 +158,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
if (im.dialog == (byte)InstantMessageDialog.RequestTeleport
|| im.dialog == (byte)InstantMessageDialog.GodLikeRequestTeleport)
{
UUID sessionID = new(im.imSessionID);
UUID sessionID = new UUID(im.imSessionID);
if (!m_PendingLures.Contains(sessionID))
{
@@ -164,19 +168,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
// Forward. We do this, because the IM module explicitly rejects
// IMs of this type
m_TransferModule?.SendInstantMessage(im, delegate(bool success) { }, true);
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success) { });
}
else if (im.dialog == (byte)InstantMessageDialog.RequestLure)
{
m_TransferModule?.SendInstantMessage(im, delegate (bool success) { }, true);
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate (bool success) { });
}
}
public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client)
{
if (client.Scene is not Scene scene)
return;
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)(client.Scene);
ScenePresence presence = scene.GetScenePresence(client.AgentId);
message += "@" + m_thisGridInfo.GateKeeperURLNoEndSlash;
@@ -185,24 +192,29 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
UUID sessionID = UUID.Random();
GridInstantMessage m = new(scene, client.AgentId,
GridInstantMessage m = new GridInstantMessage(scene, client.AgentId,
client.FirstName+" "+client.LastName, targetid,
(byte)InstantMessageDialog.RequestTeleport, false,
message, sessionID, false, presence.AbsolutePosition,
[], true);
Array.Empty<byte>(), true);
m.RegionID = client.Scene.RegionInfo.RegionID.Guid;
m_log.Debug($"[HG LURE MODULE]: RequestTeleport sessionID={m.imSessionID}, regionID={m.RegionID}, message={m.message}");
m_log.DebugFormat("[HG LURE MODULE]: RequestTeleport sessionID={0}, regionID={1}, message={2}", m.imSessionID, m.RegionID, m.message);
m_PendingLures.Add(sessionID, m, 7200000); // 2 hours
m_TransferModule?.SendInstantMessage(m, delegate(bool success) { }, true);
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(m,
delegate(bool success) { });
}
}
public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client)
{
if (client.Scene is not Scene)
if (!(client.Scene is Scene))
return;
//Scene scene = (Scene)(client.Scene);
if (m_PendingLures.TryGetValue(lureID, out GridInstantMessage im))
{
m_PendingLures.Remove(lureID);
@@ -216,24 +228,26 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
private void Lure(IClientAPI client, uint teleportflags, GridInstantMessage im)
{
Scene scene = client.Scene as Scene;
UUID regionID = new(im.RegionID);
UUID regionID = new UUID(im.RegionID);
GridRegion region = scene.GridService.GetRegionByUUID(scene.RegionInfo.ScopeID, regionID);
if (region != null)
scene.RequestTeleportLocation(client, region.RegionHandle, im.Position + new Vector3(0.5f, 0.5f, 0f), Vector3.UnitX, teleportflags);
else // we don't have that region here. Check if it's HG
{
string[] parts = im.message.Split(['@']);
string[] parts = im.message.Split(new char[] { '@' });
if (parts.Length > 1)
{
string url = parts[parts.Length - 1]; // the last part
if (m_thisGridInfo.IsLocalGrid(url, true) == 0)
{
m_log.Debug($"[HG LURE MODULE]: Luring agent to grid {url} region {im.RegionID} position {im.Position}");
m_log.DebugFormat("[HG LURE MODULE]: Luring agent to grid {0} region {1} position {2}", url, im.RegionID, im.Position);
GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
GridRegion gatekeeper = new GridRegion { ServerURI = url };
GridRegion gatekeeper = new GridRegion();
gatekeeper.ServerURI = url;
string homeURI = scene.GetAgentHomeURI(client.AgentId);
GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, regionID, client.AgentId, homeURI, out string message);
string message;
GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, regionID, client.AgentId, homeURI, out message);
if (finalDestination != null)
{
ScenePresence sp = scene.GetScenePresence(client.AgentId);
@@ -251,7 +265,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
}
else
{
m_log.Info("$[HG LURE MODULE]: Lure failed: {message}");
m_log.InfoFormat("[HG LURE MODULE]: Lure failed: {0}", message);
client.SendAgentAlertMessage(message, true);
}
}

View File

@@ -41,9 +41,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LureModule")]
public class LureModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private readonly List<Scene> m_scenes = [];
private readonly List<Scene> m_scenes = new List<Scene>();
private IMessageTransferModule m_TransferModule = null;
private bool m_Enabled = false;
@@ -52,7 +53,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
{
if (config.Configs["Messaging"] != null)
{
if (config.Configs["Messaging"].GetString("LureModule", "LureModule") == Name)
if (config.Configs["Messaging"].GetString(
"LureModule", "LureModule") ==
"LureModule")
{
m_Enabled = true;
m_log.DebugFormat("[LURE MODULE]: {0} enabled", Name);
@@ -92,9 +95,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
m_Enabled = false;
m_scenes.Clear();
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
scene.EventManager.OnIncomingInstantMessage -=
OnGridInstantMessage;
}
}
}
public void RemoveRegion(Scene scene)
@@ -106,7 +111,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
{
m_scenes.Remove(scene);
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
scene.EventManager.OnIncomingInstantMessage -=
OnGridInstantMessage;
}
}
@@ -146,7 +152,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client)
{
if (client.Scene is not Scene)
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)(client.Scene);
@@ -164,7 +170,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
(uint)presence.AbsolutePosition.Y,
(uint)presence.AbsolutePosition.Z + 2);
m_log.Debug($"[LURE MODULE]: TP invite with message {message}, type {lureType}");
m_log.DebugFormat("[LURE MODULE]: TP invite with message {0}, type {1}", message, lureType);
GridInstantMessage m;
@@ -194,13 +200,25 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client)
{
if (client.Scene is not Scene scene)
if (!(client.Scene is Scene))
return;
Util.ParseFakeParcelID(lureID, out ulong handle, out uint x, out uint y, out uint z);
Scene scene = (Scene)(client.Scene);
Vector3 position = new(x , y , z);
scene.RequestTeleportLocation(client, handle, position, Vector3.Zero, teleportFlags);
ulong handle = 0;
uint x = 128;
uint y = 128;
uint z = 70;
Util.ParseFakeParcelID(lureID, out handle, out x, out y, out z);
Vector3 position = new Vector3();
position.X = (float)x;
position.Y = (float)y;
position.Z = (float)z;
scene.RequestTeleportLocation(client, handle, position,
Vector3.Zero, teleportFlags);
}
private void OnGridInstantMessage(GridInstantMessage msg)
@@ -212,7 +230,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Lure
msg.dialog != (byte)InstantMessageDialog.RequestLure)
return;
m_TransferModule?.SendInstantMessage(msg, delegate(bool success) { });
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(msg,
delegate(bool success) { });
}
}
}
}

View File

@@ -45,6 +45,7 @@ using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.UserProfilesService;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Region.CoreModules.Avatar.Friends;
namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
@@ -60,12 +61,10 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
// The pair of Dictionaries are used to handle the switching of classified ads
// by maintaining a cache of classified id to creator id mappings and an interest
// count. The entries are removed when the interest count reaches 0.
readonly Dictionary<UUID, UUID> m_classifiedCache = [];
readonly Dictionary<UUID, int> m_classifiedInterest = [];
readonly Dictionary<UUID, UUID> m_classifiedCache = new();
readonly Dictionary<UUID, int> m_classifiedInterest = new();
readonly ExpiringCacheOS<UUID, UserProfileCacheEntry> m_profilesCache = new(60000);
IGroupsModule m_groupsModule = null;
IUserManagement m_userManagementModule = null;
private readonly JsonRpcRequestManager rpc = new();
private bool m_allowUserProfileWebURLs = true;
@@ -78,150 +77,128 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
public int reqtype;
}
private readonly ConcurrentStack<AsyncPropsRequest> m_asyncLocalRequests = new();
private readonly object m_asyncLocalRequestsLock = new();
private bool m_asyncLocalRequestsRunning = false;
private readonly ConcurrentStack<AsyncPropsRequest> m_asyncHGRequests = new();
private readonly object m_asyncHGRequestsLock = new();
private bool m_asyncHGRequestsRunning = false;
private readonly ConcurrentStack<AsyncPropsRequest> m_asyncRequests = new();
private readonly object m_asyncRequestsLock = new();
private bool m_asyncRequestsRunning = false;
private void ProcessLocalRequests()
private void ProcessRequests()
{
lock(m_asyncLocalRequestsLock)
lock(m_asyncRequestsLock)
{
while (m_asyncLocalRequests.TryPop(out AsyncPropsRequest req))
while (m_asyncRequests.TryPop(out AsyncPropsRequest req))
{
IClientAPI client = req.client;
if(!client.IsActive)
continue;
ProcessRequest(req);
}
m_asyncLocalRequestsRunning = false;
}
}
private void ProcessHGRequests()
{
lock(m_asyncHGRequestsLock)
{
while (m_asyncHGRequests.TryPop(out AsyncPropsRequest req))
{
IClientAPI client = req.client;
if(!client.IsActive)
continue;
ProcessRequest(req);
}
m_asyncHGRequestsRunning = false;
}
}
private void ProcessRequest(AsyncPropsRequest req)
{
try
{
IClientAPI client = req.client;
if(req.reqtype == 0)
{
ScenePresence p = req.presence;
bool foreign = GetUserProfileServerURI(req.agent, out string serverURI);
bool ok = serverURI.Length > 0;
byte[] membershipType = new byte[1];
string born = string.Empty;
uint flags = 0x00;
if (ok && GetUserAccountData(req.agent, out UserAccount acc))
try
{
flags = (uint)(acc.UserFlags & 0xff);
IClientAPI client = req.client;
if(!client.IsActive)
continue;
if (acc.UserTitle.Length == 0)
membershipType[0] = (byte)((acc.UserFlags & 0x0f00) >> 8);
else
membershipType = Utils.StringToBytes(acc.UserTitle);
int val_born = acc.Created;
if (val_born != 0)
born = Util.ToDateTime(val_born).ToString("M/d/yyyy", CultureInfo.InvariantCulture);
}
else
ok = false;
UserProfileProperties props = new() { UserId = req.agent };
if (ok)
ok = GetProfileData(ref props, foreign, serverURI, out string result);
if (!ok)
props.AboutText = "Profile not available at this time. User may still be unknown to this grid";
if (!m_allowUserProfileWebURLs)
props.WebUrl = "";
GroupMembershipData[] agentGroups = null;
if(ok && m_groupsModule is not null)
agentGroups = m_groupsModule.GetMembershipData(req.agent);
HashSet<IClientAPI> clients;
lock (m_profilesCache)
{
if (!m_profilesCache.TryGetValue(props.UserId, out UserProfileCacheEntry uce) || uce is null)
uce = new UserProfileCacheEntry();
uce.props = props;
uce.born = born;
uce.membershipType = membershipType;
uce.flags = flags;
clients = uce.ClientsWaitingProps;
uce.ClientsWaitingProps = null;
uce.avatarGroups = agentGroups;
m_profilesCache.AddOrUpdate(props.UserId, uce, PROFILECACHEEXPIRE);
}
if (IsFriendOnline(req.client, req.agent))
flags |= (uint)ProfileFlags.Online;
else
flags &= (uint)~ProfileFlags.Online;
if (clients is null)
{
client.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
client.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
if (agentGroups is not null)
client.SendAvatarGroupsReply(req.agent, agentGroups);
}
else
{
if (!clients.Contains(client) && client.IsActive)
if(req.reqtype == 0)
{
client.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
ScenePresence p = req.presence;
client.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
if (agentGroups is not null)
client.SendAvatarGroupsReply(req.agent, agentGroups);
}
foreach (IClientAPI cli in clients)
{
if (!cli.IsActive)
continue;
cli.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
bool foreign = GetUserProfileServerURI(req.agent, out string serverURI);
bool ok = serverURI.Length > 0;
cli.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
if (agentGroups is not null)
cli.SendAvatarGroupsReply(req.agent, agentGroups);
Byte[] membershipType = new Byte[1];
string born = string.Empty;
uint flags = 0x00;
if (ok && GetUserAccountData(req.agent, out UserAccount acc))
{
flags = (uint)(acc.UserFlags & 0xff);
if (acc.UserTitle.Length == 0)
membershipType[0] = (byte)((acc.UserFlags & 0x0f00) >> 8);
else
membershipType = Utils.StringToBytes(acc.UserTitle);
int val_born = acc.Created;
if (val_born != 0)
born = Util.ToDateTime(val_born).ToString("M/d/yyyy", CultureInfo.InvariantCulture);
}
else
ok = false;
UserProfileProperties props = new() { UserId = req.agent };
if (ok)
ok = GetProfileData(ref props, foreign, serverURI, out string result);
if (!ok)
props.AboutText = "Profile not available at this time. User may still be unknown to this grid";
if (!m_allowUserProfileWebURLs)
props.WebUrl = "";
GroupMembershipData[] agentGroups = null;
if(ok && m_groupsModule is not null)
agentGroups = m_groupsModule.GetMembershipData(req.agent);
HashSet<IClientAPI> clients;
lock (m_profilesCache)
{
if (!m_profilesCache.TryGetValue(props.UserId, out UserProfileCacheEntry uce) || uce is null)
uce = new UserProfileCacheEntry();
uce.props = props;
uce.born = born;
uce.membershipType = membershipType;
uce.flags = flags;
clients = uce.ClientsWaitingProps;
uce.ClientsWaitingProps = null;
uce.avatarGroups = agentGroups;
m_profilesCache.AddOrUpdate(props.UserId, uce, PROFILECACHEEXPIRE);
}
if (IsFriendOnline(req.client, req.agent))
flags |= (uint)ProfileFlags.Online;
else
flags &= (uint)~ProfileFlags.Online;
if (clients is null)
{
client.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
client.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
if (agentGroups is not null)
client.SendAvatarGroupsReply(req.agent, agentGroups);
}
else
{
if (!clients.Contains(client) && client.IsActive)
{
client.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
client.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
if (agentGroups is not null)
client.SendAvatarGroupsReply(req.agent, agentGroups);
}
foreach (IClientAPI cli in clients)
{
if (!cli.IsActive)
continue;
cli.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
cli.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
if (agentGroups is not null)
cli.SendAvatarGroupsReply(req.agent, agentGroups);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[UserProfileModule]: Process fail {0} : {1}", e.Message, e.StackTrace);
}
}
}
catch (Exception e)
{
m_log.Error($"[UserProfileModule]: Process fail {e.Message} : {e.StackTrace}");
m_asyncRequestsRunning = false;
}
}
@@ -254,6 +231,16 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
set;
}
IProfileModule ProfileModule
{
get; set;
}
IUserManagement UserManagementModule
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether this
/// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
@@ -264,7 +251,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
public bool Enabled
{
get;
private set;
set;
}
private GridInfo m_thisGridInfo;
@@ -281,6 +268,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
public void Initialise(IConfigSource source)
{
Config = source;
ReplaceableInterface = typeof(IProfileModule);
IConfig profileConfig = Config.Configs["UserProfiles"];
@@ -312,19 +300,10 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
m_allowUserProfileWebURLs = profileConfig.GetBoolean("AllowUserProfileWebURLs", m_allowUserProfileWebURLs);
m_log.Debug("[UserProfileModule]: Full Profiles Enabled");
MainConsole.Instance.Commands.AddCommand("Debug", false, "profiles status",
"profiles status",
"Show user profile Queues count",
HandleShowStatus);
ReplaceableInterface = null;
Enabled = true;
}
private void HandleShowStatus(string module, string[] cmdparms)
{
MainConsole.Instance.Output($"Profile requests in '{Scene.Name}' Local: {m_asyncLocalRequests.Count} HG: {m_asyncHGRequests.Count}");
}
/// <summary>
/// Adds the region.
/// </summary>
@@ -339,6 +318,10 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
Scene = scene;
m_thisGridInfo ??= scene.SceneGridInfo;
Scene.RegisterModuleInterface<IProfileModule>(this);
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnClientClosed += OnClientClosed;
UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
}
/// <summary>
@@ -370,19 +353,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
if(!Enabled)
return;
m_groupsModule = Scene.RequestModuleInterface<IGroupsModule>();
m_userManagementModule = Scene.RequestModuleInterface<IUserManagement>();
if(m_userManagementModule is null)
{
m_log.Error("[UserProfileModule]: UserManagementModule not loaded. Profiles Disabled");
Enabled = false;
return;
}
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnClientClosed += OnClientClosed;
}
/// <summary>
@@ -398,7 +369,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
/// </value>
public Type ReplaceableInterface
{
get { return null; }
get; private set;
}
/// <summary>
@@ -458,9 +429,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
void OnClientClosed(UUID AgentId, Scene scene)
{
if(!scene.TryGetScenePresence(AgentId, out ScenePresence sp))
return;
ScenePresence sp = scene.GetScenePresence(AgentId);
IClientAPI client = sp.ControllingClient;
if (client is null)
return;
@@ -760,7 +729,6 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
remoteClient.SendAgentAlertMessage("Error fetching classifieds", false);
return;
}
parameters = (OSDMap)osdtmp;
OSDArray list = (OSDArray)parameters["result"];
bool exists = list.Cast<OSDMap>().Where(map => map.ContainsKey("classifieduuid"))
@@ -1250,9 +1218,9 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
UserProfilePick pick = null;
Dictionary<UUID, string> curpicks = GetPicks(creatorID);
if(curpicks is not null && !curpicks.ContainsKey(pickID))
if(!curpicks.ContainsKey(pickID))
{
if(curpicks.Count >= Constants.MaxProfilePicks)
if(curpicks is not null && curpicks.Count >= Constants.MaxProfilePicks)
{
remoteClient.SendAvatarPicksReply(remoteClient.AgentId, curpicks);
return;
@@ -1675,46 +1643,124 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
reqtype = 0
};
if(m_userManagementModule.IsLocalGridUser(avatarID))
{
m_asyncLocalRequests.Push(req);
m_asyncRequests.Push(req);
if (Monitor.TryEnter(m_asyncLocalRequestsLock))
if (Monitor.TryEnter(m_asyncRequestsLock))
{
if (!m_asyncRequestsRunning)
{
try
{
if (!m_asyncLocalRequestsRunning)
{
m_asyncLocalRequestsRunning = true;
Util.FireAndForget(x => ProcessLocalRequests());
}
}
finally
{
Monitor.Exit(m_asyncLocalRequestsLock);
}
m_asyncRequestsRunning = true;
Util.FireAndForget(x => ProcessRequests());
}
Monitor.Exit(m_asyncRequestsLock);
}
/*
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
}
else
{
m_asyncHGRequests.Push(req);
userInfo = new Dictionary<string, object>();
}
if (Monitor.TryEnter(m_asyncHGRequestsLock))
Byte[] membershipType = new Byte[1];
string born = string.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle.Length == 0)
membershipType[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
else
membershipType = Utils.StringToBytes(account.UserTitle);
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserAccountData(avatarID, out userInfo) == true)
{
try
{
if (!m_asyncHGRequestsRunning)
{
m_asyncHGRequestsRunning = true;
Util.FireAndForget(x => ProcessHGRequests());
}
}
finally
{
Monitor.Exit(m_asyncHGRequestsLock);
}
if ((string)userInfo["user_title"].Length == 0)
membershipType[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
else
membershipType = Utils.StringToBytes((string)userInfo["user_title"]);
int val_born = (int)userInfo["user_created"];
if(val_born != 0)
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
props = new UserProfileProperties();
props.UserId = avatarID;
string result = string.Empty;
if(!GetProfileData(ref props, foreign, serverURI, out result))
{
props.AboutText ="Profile not available at this time. User may still be unknown to this grid";
}
if(!m_allowUserProfileWebURLs)
props.WebUrl ="";
HashSet<IClientAPI> clients;
lock(m_profilesCache)
{
if(!m_profilesCache.TryGetValue(props.UserId, out uce) || uce == null)
uce = new UserProfileCacheEntry();
uce.props = props;
uce.born = born;
uce.membershipType = membershipType;
uce.flags = flags;
clients = uce.ClientsWaitingProps;
uce.ClientsWaitingProps = null;
m_profilesCache.AddOrUpdate(props.UserId, uce, PROFILECACHEEXPIRE);
}
// if on same region force online
if(p != null && !p.IsDeleted)
flags |= 0x10;
if(clients == null)
{
remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
}
else
{
if(!clients.Contains(remoteClient))
clients.Add(remoteClient);
foreach(IClientAPI cli in clients)
{
if(!cli.IsActive)
continue;
cli.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
cli.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
(uint)props.SkillsMask, props.SkillsText, props.Language);
}
}
*/
}
/// <summary>
@@ -1763,7 +1809,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
/// </returns>
bool GetProfileData(ref UserProfileProperties properties, bool foreign, string serverURI, out string message)
{
if (string.IsNullOrEmpty(serverURI))
if (String.IsNullOrEmpty(serverURI))
{
message = "User profile service unknown at this time";
return false;
@@ -1830,7 +1876,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
bool GetUserAccountData(UUID userID, out UserAccount account)
{
account = null;
if (m_userManagementModule.IsLocalGridUser(userID))
if (UserManagementModule.IsLocalGridUser(userID))
{
// Is local
IUserAccountService uas = Scene.UserAccountService;
@@ -1840,8 +1886,8 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
else
{
// Is Foreign
string home_url = m_userManagementModule.GetUserServerURL(userID, "HomeURI", out bool recentFailedWeb);
if (recentFailedWeb || string.IsNullOrEmpty(home_url))
string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI", out bool recentFailedWeb);
if (recentFailedWeb || String.IsNullOrEmpty(home_url))
return false;
UserAgentServiceConnector uConn = new(home_url);
@@ -1854,7 +1900,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
catch (Exception e)
{
m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
m_userManagementModule.UserWebFailed(userID);
UserManagementModule.UserWebFailed(userID);
return false;
}
@@ -1887,9 +1933,9 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
/// </param>
bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
if (!m_userManagementModule.IsLocalGridUser(userID))
if (!UserManagementModule.IsLocalGridUser(userID))
{
serverURI = m_userManagementModule.GetUserServerURL(userID, "ProfileServerURI", out bool failed);
serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI", out bool failed);
if(failed)
serverURI = string.Empty;
// Is Foreign
@@ -1908,7 +1954,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
if(imageID.IsZero())
return;
string assetServerURI = m_userManagementModule.GetUserServerURL(agent, "AssetServerURI");
string assetServerURI = UserManagementModule.GetUserServerURL(agent, "AssetServerURI");
if(string.IsNullOrWhiteSpace(assetServerURI))
return;
@@ -1946,10 +1992,9 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
if(client.SceneAgent is ScenePresence sp && sp.IsViewerUIGod)
{
Services.Interfaces.PresenceInfo[] pi = Scene.PresenceService?.GetAgents([agent.ToString()]);
Services.Interfaces.PresenceInfo[] pi = Scene.PresenceService?.GetAgents(new string[] { agent.ToString() });
return pi is not null && pi.Length > 0;
}
return false;
}

View File

@@ -1319,6 +1319,13 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason, out bool logout)
{
if (sp.GotAttachmentsData == false)
{
logout = false;
reason = "Cannot leave region yet, attachments are still loading";
return false;
}
GridRegion source = new(m_sceneRegionInfo)
{
RawServerURI = m_thisGridInfo.GateKeeperURL
@@ -2854,7 +2861,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
return true;
}
private int GetStateSource(SceneObjectGroup sog)
public int GetStateSource(SceneObjectGroup sog)
{
ScenePresence sp = m_scene.GetScenePresence(sog.OwnerID);

View File

@@ -258,6 +258,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason, out bool logout)
{
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI);
reason = string.Empty;
logout = false;
int flags = Scene.GridService.GetRegionFlags(m_sceneRegionInfo.ScopeID, reg.RegionID);
@@ -651,17 +652,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
if (OwnerID.IsZero())
{
m_log.DebugFormat(
"[HG TRANSFER MODULE]: Denied object {0}({1}) entry into {2} because ownerID is zero",
"[HG ENTITY TRANSFER MODULE]: Denied object {0}({1}) entry into {2} because ownerID is zero",
so.Name, so.UUID, m_sceneName);
return false;
}
if (m_sceneRegionInfo.EstateSettings.IsBanned(OwnerID))
if (!m_scene.Permissions.IsAdministrator(so.OwnerID) && m_sceneRegionInfo.EstateSettings.IsBanned(OwnerID))
{
m_log.DebugFormat(
"[HG TRANSFER MODULE]: Denied prim crossing of {0} {1} into {2} for banned avatar {3}",
so.Name, so.UUID, m_sceneName, so.OwnerID);
$"[HG ENTITY TRANSFER MODULE]: Denied {so.Name} {so.UUID} into { m_sceneName} of banned owner {so.OwnerID}");
return false;
}
@@ -676,8 +675,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
if (m_scene.GetScenePresence(OwnerID) == null)
{
m_log.DebugFormat(
"[HG TRANSFER MODULE]: Denied attachment {0}({1}) owner {2} not in region {3}",
so.Name, so.UUID, OwnerID, m_sceneName);
$"[HG ENTITY TRANSFER MODULE]: Denied attachment {so.Name}({so.UUID}) owner {so.OwnerID} not in region {m_sceneName}");
return false;
}
@@ -803,72 +801,124 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
}
else
{
if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
if (sp.IsDeleted)
return false;
if (m_sceneRegionInfo.EstateSettings.IsBanned(sp.UUID))
{
ScenePresence defsp = sp;
List<SceneObjectGroup> deftatt = attachments;
List<SceneObjectGroup> toadd = new List<SceneObjectGroup>(deftatt.Count);
m_incomingSceneObjectEngine.QueueJob(
string.Format("HG UUID Gather attachments {0}", defsp.Name), () =>
m_log.DebugFormat(
"[HG ENTITY TRANSFER]: Denied Attachments for banned avatar {0}", sp.Name);
return false;
}
// Upstream does let the avi in, even if their assetserver can't be reached
// The visitor will obviously be without visible attachments in this case
if (aCircuit.ServiceURLs == null || !aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
{
sp.GotAttachmentsData = true;
return true;
}
ScenePresence defsp = sp;
List<SceneObjectGroup> deftatt = new(attachments.Count);
List<SceneObjectGroup> defhuds = new();
int requestStartTick = Environment.TickCount;
// Prioritize non-HUDS, as AOs, dance huds etc can hold a lot of assets
foreach (SceneObjectGroup sog in attachments)
{
if (sog.AttachmentPoint >= 31 && sog.AttachmentPoint <= 38)
{
defhuds.Add(sog);
}
else
{
deftatt.Add(sog);
}
}
deftatt.AddRange(defhuds);
IClientAPI remoteClient = sp.ControllingClient;
UUID groupID = remoteClient.ActiveGroupId;
m_incomingSceneObjectEngine.QueueJob(
string.Format("HG UUID Gather attachments {0}", defsp.Name), () =>
{
string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, url, ids);
foreach (SceneObjectGroup sog in deftatt)
{
string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, url, ids);
foreach (SceneObjectGroup defso in deftatt)
if(sog.OwnerID.NotEqual(defsp.UUID))
{
if(defso.OwnerID.NotEqual(defsp.UUID))
{
m_log.ErrorFormat(
"[HG TRANSFER MODULE] attachment {0}({1} owner {2} does not match HG avatarID {3}",
defso.Name, defso.UUID, defso.OwnerID, defsp.UUID);
continue;
}
uuidGatherer.AddForInspection(defso);
while (!uuidGatherer.Complete)
{
if (sp.IsDeleted)
{
deftatt = null;
defsp = null;
uuidGatherer = null;
toadd = null;
return;
}
uuidGatherer.GatherNext();
}
toadd.Add(defso);
m_log.ErrorFormat(
"[HG ENTITY TRANSFER] Owner ({0}) of attachment '{1}' does not match HG visitor's ID ({2})",
sog.OwnerID, sog.Name, defsp.UUID);
continue;
}
deftatt = null;
// get asset uuids for scene object
uuidGatherer.AddForInspection(sog);
while (!uuidGatherer.Complete)
{
if (sp.IsDeleted)
{
deftatt = null;
defsp = null;
uuidGatherer = null;
return;
}
uuidGatherer.GatherNext();
}
// fetch assets for scene object
foreach (UUID id in ids.Keys)
{
int tickStart = Util.EnvironmentTickCount();
uuidGatherer.FetchAsset(id);
int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
if (sp.IsDeleted || ticksElapsed > 30000)
{
m_log.WarnFormat(
"[HG ENTITY TRANSFER]: Aborting fetch attachments assets for HG user {0}", sp.Name);
"[HG ENTITY TRANSFER]: Aborting fetching assets for for HG visitor {0}", defsp.Name);
deftatt = null;
defsp = null;
uuidGatherer = null;
toadd = null;
return;
}
}
ids.Clear(); // this scene object is done fetching
base.HandleIncomingAttachments(sp, toadd);
// add scene object
if (!m_scene.AddSceneObject(sog))
{
m_log.DebugFormat(
"[HG ENTITY TRANSFER]: Could not add attachment '{0}' for HG visitor {1}",
sog.Name, defsp.Name);
} else {
sog.SetGroup(groupID, remoteClient);
if (sog.ContainsScripts())
{
sog.RootPart.ParentGroup.CreateScriptInstances(
0, false, Scene.DefaultScriptEngine, GetStateSource(sog));
sog.aggregateScriptEvents();
sog.ResumeScripts();
}
}
}
defsp = null;
uuidGatherer = null;
toadd = null;
},
OwnerID.ToString());
}
deftatt = null;
defsp = null;
uuidGatherer = null;
sp.GotAttachmentsData = true;
string loadtime = Convert.ToString(Environment.TickCount - requestStartTick);
remoteClient.SendAlertMessage("Your avatar has finished loading ("+loadtime+"ms)");
// at this point the job engine is done
},
OwnerID.ToString());
}
}

View File

@@ -195,17 +195,11 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
// The act of gathering UUIDs downloads some assets from the remote server
// but not all...
if(string.IsNullOrEmpty(userAssetURL))
{
m_log.Debug($"[HG ASSET MAPPER]: Problems getting item asset {assetID}. Asset server unknown");
return;
}
HGUuidGatherer uuidGatherer = new(m_scene.AssetService, userAssetURL);
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, userAssetURL);
uuidGatherer.AddForInspection(assetID);
uuidGatherer.GatherAll();
m_log.Debug($"[HG ASSET MAPPER]: Preparing to get {uuidGatherer.GatheredUuids.Count} assets");
m_log.DebugFormat("[HG ASSET MAPPER]: Preparing to get {0} assets", uuidGatherer.GatheredUuids.Count);
bool success = true;
foreach (UUID uuid in uuidGatherer.GatheredUuids.Keys)
{
@@ -217,9 +211,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
// maybe all pieces got here...
if (!success)
m_log.Debug($"[HG ASSET MAPPER]: Problems getting item asset {assetID} from asset server {userAssetURL}");
m_log.DebugFormat("[HG ASSET MAPPER]: Problems getting item {0} from asset server {1}", assetID, userAssetURL);
else
m_log.Debug($"[HG ASSET MAPPER]: Successfully got item asset {assetID} from asset server {userAssetURL}");
m_log.DebugFormat("[HG ASSET MAPPER]: Successfully got item {0} from asset server {1}", assetID, userAssetURL);
}
public void Post(UUID assetID, UUID ownerID, string userAssetURL)
@@ -240,7 +234,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
// Check which assets already exist in the destination server
string url = userAssetURL;
if (!url.EndsWith('/') && !url.EndsWith('='))
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
string[] remoteAssetIDs = new string[uuidGatherer.GatheredUuids.Count];

View File

@@ -405,11 +405,6 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
assetServerURL = UserManagementModule.GetUserServerURL(userID, "AssetServerURI");
assetServerURL = assetServerURL.Trim('/');
}
if(assetServerURL.Length == 0)
{
m_log.Debug($"[HGScene]: user {userID} asset server returned empty url");
return false;
}
return true;
}
}
@@ -422,12 +417,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
}
else
{
if(assetServerURL.Length == 0)
{
m_log.Debug($"[HGScene]: user {userID} asset server returned empty url");
return false;
}
m_log.Debug($"[HGScene]: user {userID} has foreign assets {assetServerURL}");
m_log.DebugFormat("[HGScene]: user {0} has foreign assets {1}", userID, assetServerURL);
return true;
}
}

View File

@@ -421,9 +421,6 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
{
UUID oldID;
if( Face == -9999)
return UUID.Zero;
lock (part)
{
// mostly keep the values from before
@@ -541,9 +538,11 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
UUID oldID = UpdatePart(part, asset.FullID);
if ((Disp & DISP_EXPIRE) != 0 && oldID.IsNotZero() )
if (!oldID.IsZero() && ((Disp & DISP_EXPIRE) != 0))
{
oldAsset ??= scene.AssetService.Get(oldID.ToString());
if (oldAsset == null)
oldAsset = scene.AssetService.Get(oldID.ToString());
if (oldAsset != null)
{
if (oldAsset.Temporary)

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