aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework
diff options
context:
space:
mode:
authorMelanie2018-09-12 13:22:17 +0100
committerMelanie2018-09-12 13:22:17 +0100
commite874e3a2ad47af6a045dbe3f4dd91364cd92750a (patch)
treea92dc21f85d01e421842cb2fbfa4ecdf3430334a /OpenSim/Framework
parentSquelch "connection reset by peer" exceptions (diff)
parentoooops (diff)
downloadopensim-SC-e874e3a2ad47af6a045dbe3f4dd91364cd92750a.zip
opensim-SC-e874e3a2ad47af6a045dbe3f4dd91364cd92750a.tar.gz
opensim-SC-e874e3a2ad47af6a045dbe3f4dd91364cd92750a.tar.bz2
opensim-SC-e874e3a2ad47af6a045dbe3f4dd91364cd92750a.tar.xz
Merge branch 'master' of opensimulator.org:/var/git/opensim
Diffstat (limited to 'OpenSim/Framework')
-rw-r--r--OpenSim/Framework/AgentUpdateArgs.cs1
-rw-r--r--OpenSim/Framework/AnimationSet.cs22
-rw-r--r--OpenSim/Framework/AssetLoader/Filesystem/AssetLoaderFileSystem.cs4
-rw-r--r--OpenSim/Framework/AvatarWearable.cs8
-rw-r--r--OpenSim/Framework/BlockingQueue.cs148
-rw-r--r--OpenSim/Framework/Cache.cs24
-rw-r--r--OpenSim/Framework/ChildAgentDataUpdate.cs9
-rw-r--r--OpenSim/Framework/Client/IClientIPEndpoint.cs2
-rw-r--r--OpenSim/Framework/ClientInfo.cs10
-rw-r--r--OpenSim/Framework/ClientManager.cs48
-rw-r--r--OpenSim/Framework/Console/LocalConsole.cs25
-rw-r--r--OpenSim/Framework/Console/RemoteConsole.cs4
-rw-r--r--OpenSim/Framework/Crc32.cs139
-rw-r--r--OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs64
-rw-r--r--OpenSim/Framework/EstateSettings.cs82
-rw-r--r--OpenSim/Framework/IClientAPI.cs14
-rw-r--r--OpenSim/Framework/ILandChannel.cs6
-rw-r--r--OpenSim/Framework/ILandObject.cs2
-rw-r--r--OpenSim/Framework/IMoneyModule.cs1
-rw-r--r--OpenSim/Framework/InventoryItemBase.cs36
-rw-r--r--OpenSim/Framework/LLSDxmlEncode.cs725
-rw-r--r--OpenSim/Framework/LandData.cs12
-rw-r--r--OpenSim/Framework/MinHeap.cs150
-rw-r--r--OpenSim/Framework/Monitoring/JobEngine.cs92
-rw-r--r--OpenSim/Framework/Monitoring/ServerStatsCollector.cs8
-rw-r--r--OpenSim/Framework/Monitoring/Stats/Stat.cs4
-rw-r--r--OpenSim/Framework/Monitoring/Watchdog.cs40
-rw-r--r--OpenSim/Framework/Monitoring/WorkManager.cs17
-rw-r--r--OpenSim/Framework/MuteData.cs (renamed from OpenSim/Framework/GcNotify.cs)41
-rw-r--r--OpenSim/Framework/NetworkServersInfo.cs4
-rw-r--r--OpenSim/Framework/PermissionsUtil.cs48
-rw-r--r--OpenSim/Framework/PhysicsInertia.cs261
-rw-r--r--OpenSim/Framework/PrimitiveBaseShape.cs109
-rw-r--r--OpenSim/Framework/PriorityQueue.cs21
-rw-r--r--OpenSim/Framework/RegionInfo.cs38
-rw-r--r--OpenSim/Framework/RestClient.cs25
-rw-r--r--OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs3
-rw-r--r--OpenSim/Framework/Servers/BaseOpenSimServer.cs45
-rw-r--r--OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs295
-rw-r--r--OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs2
-rw-r--r--OpenSim/Framework/Servers/HttpServer/OSHttpResponse.cs19
-rw-r--r--OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs9
-rw-r--r--OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs18
-rw-r--r--OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs216
-rw-r--r--OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs7
-rw-r--r--OpenSim/Framework/Servers/MainServer.cs28
-rw-r--r--OpenSim/Framework/Servers/ServerBase.cs109
-rw-r--r--OpenSim/Framework/Servers/Tests/VersionInfoTests.cs9
-rw-r--r--OpenSim/Framework/Util.cs279
-rw-r--r--OpenSim/Framework/VersionInfo.cs6
-rw-r--r--OpenSim/Framework/WebUtil.cs121
51 files changed, 2448 insertions, 962 deletions
diff --git a/OpenSim/Framework/AgentUpdateArgs.cs b/OpenSim/Framework/AgentUpdateArgs.cs
index f04d692..cd1c3a0 100644
--- a/OpenSim/Framework/AgentUpdateArgs.cs
+++ b/OpenSim/Framework/AgentUpdateArgs.cs
@@ -83,6 +83,7 @@ namespace OpenSim.Framework
83 public bool UseClientAgentPosition; 83 public bool UseClientAgentPosition;
84 public bool NeedsCameraCollision; 84 public bool NeedsCameraCollision;
85 public uint lastpacketSequence; 85 public uint lastpacketSequence;
86 public double lastUpdateTS;
86 87
87 public AgentUpdateArgs() 88 public AgentUpdateArgs()
88 { 89 {
diff --git a/OpenSim/Framework/AnimationSet.cs b/OpenSim/Framework/AnimationSet.cs
index 87c4a78..8753088 100644
--- a/OpenSim/Framework/AnimationSet.cs
+++ b/OpenSim/Framework/AnimationSet.cs
@@ -31,7 +31,8 @@ using OpenMetaverse;
31 31
32namespace OpenSim.Framework 32namespace OpenSim.Framework
33{ 33{
34 public delegate bool AnimationSetValidator(UUID animID); 34// public delegate bool AnimationSetValidator(UUID animID);
35 public delegate uint AnimationSetValidator(UUID animID);
35 36
36 public class AnimationSet 37 public class AnimationSet
37 { 38 {
@@ -141,7 +142,7 @@ namespace OpenSim.Framework
141 assetData += String.Format("{0} {1} {2}\n", kvp.Key, kvp.Value.Value.ToString(), kvp.Value.Key); 142 assetData += String.Format("{0} {1} {2}\n", kvp.Key, kvp.Value.Value.ToString(), kvp.Value.Key);
142 return System.Text.Encoding.ASCII.GetBytes(assetData); 143 return System.Text.Encoding.ASCII.GetBytes(assetData);
143 } 144 }
144 145/*
145 public bool Validate(AnimationSetValidator val) 146 public bool Validate(AnimationSetValidator val)
146 { 147 {
147 if (m_parseError) 148 if (m_parseError)
@@ -164,5 +165,22 @@ namespace OpenSim.Framework
164 165
165 return allOk; 166 return allOk;
166 } 167 }
168*/
169 public uint Validate(AnimationSetValidator val)
170 {
171 if (m_parseError)
172 return 0;
173
174 uint ret = 0x7fffffff;
175 uint t;
176 foreach (KeyValuePair<string, KeyValuePair<string, UUID>> kvp in m_animations)
177 {
178 t = val(kvp.Value.Value);
179 if (t == 0)
180 return 0;
181 ret &= t;
182 }
183 return ret;
184 }
167 } 185 }
168} 186}
diff --git a/OpenSim/Framework/AssetLoader/Filesystem/AssetLoaderFileSystem.cs b/OpenSim/Framework/AssetLoader/Filesystem/AssetLoaderFileSystem.cs
index 097ad7d..efccc35 100644
--- a/OpenSim/Framework/AssetLoader/Filesystem/AssetLoaderFileSystem.cs
+++ b/OpenSim/Framework/AssetLoader/Filesystem/AssetLoaderFileSystem.cs
@@ -42,11 +42,13 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
42 public class AssetLoaderFileSystem : IAssetLoader 42 public class AssetLoaderFileSystem : IAssetLoader
43 { 43 {
44 private static readonly UUID LIBRARY_OWNER_ID = new UUID("11111111-1111-0000-0000-000100bba000"); 44 private static readonly UUID LIBRARY_OWNER_ID = new UUID("11111111-1111-0000-0000-000100bba000");
45 private static readonly string LIBRARY_OWNER_IDstr = "11111111-1111-0000-0000-000100bba000";
46
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46 48
47 protected static AssetBase CreateAsset(string assetIdStr, string name, string path, sbyte type) 49 protected static AssetBase CreateAsset(string assetIdStr, string name, string path, sbyte type)
48 { 50 {
49 AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type, LIBRARY_OWNER_ID.ToString()); 51 AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type, LIBRARY_OWNER_IDstr);
50 52
51 if (!String.IsNullOrEmpty(path)) 53 if (!String.IsNullOrEmpty(path))
52 { 54 {
diff --git a/OpenSim/Framework/AvatarWearable.cs b/OpenSim/Framework/AvatarWearable.cs
index 0e8f960..fddd0f0 100644
--- a/OpenSim/Framework/AvatarWearable.cs
+++ b/OpenSim/Framework/AvatarWearable.cs
@@ -91,11 +91,11 @@ namespace OpenSim.Framework
91 public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111"); 91 public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111");
92 public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120"); 92 public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120");
93 93
94// public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8"); 94 public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8");
95// public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594"); 95 public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594");
96 96
97// public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1"); 97 public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1");
98// public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007"); 98 public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007");
99 99
100 protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>(); 100 protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>();
101 protected List<UUID> m_ids = new List<UUID>(); 101 protected List<UUID> m_ids = new List<UUID>();
diff --git a/OpenSim/Framework/BlockingQueue.cs b/OpenSim/Framework/BlockingQueue.cs
deleted file mode 100644
index 2461049..0000000
--- a/OpenSim/Framework/BlockingQueue.cs
+++ /dev/null
@@ -1,148 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using System.Threading;
30
31namespace OpenSim.Framework
32{
33 public class BlockingQueue<T>
34 {
35 private readonly Queue<T> m_pqueue = new Queue<T>();
36 private readonly Queue<T> m_queue = new Queue<T>();
37 private readonly object m_queueSync = new object();
38
39 public void PriorityEnqueue(T value)
40 {
41 lock (m_queueSync)
42 {
43 m_pqueue.Enqueue(value);
44 Monitor.Pulse(m_queueSync);
45 }
46 }
47
48 public void Enqueue(T value)
49 {
50 lock (m_queueSync)
51 {
52 m_queue.Enqueue(value);
53 Monitor.Pulse(m_queueSync);
54 }
55 }
56
57 public T Dequeue()
58 {
59 lock (m_queueSync)
60 {
61 while (m_queue.Count < 1 && m_pqueue.Count < 1)
62 {
63 Monitor.Wait(m_queueSync);
64 }
65
66 if (m_pqueue.Count > 0)
67 return m_pqueue.Dequeue();
68
69 if (m_queue.Count > 0)
70 return m_queue.Dequeue();
71 return default(T);
72 }
73 }
74
75 public T Dequeue(int msTimeout)
76 {
77 lock (m_queueSync)
78 {
79 if (m_queue.Count < 1 && m_pqueue.Count < 1)
80 {
81 if(!Monitor.Wait(m_queueSync, msTimeout))
82 return default(T);
83 }
84
85 if (m_pqueue.Count > 0)
86 return m_pqueue.Dequeue();
87 if (m_queue.Count > 0)
88 return m_queue.Dequeue();
89 return default(T);
90 }
91 }
92
93 /// <summary>
94 /// Indicate whether this queue contains the given item.
95 /// </summary>
96 /// <remarks>
97 /// This method is not thread-safe. Do not rely on the result without consistent external locking.
98 /// </remarks>
99 public bool Contains(T item)
100 {
101 lock (m_queueSync)
102 {
103 if (m_queue.Count < 1 && m_pqueue.Count < 1)
104 return false;
105
106 if (m_pqueue.Contains(item))
107 return true;
108 return m_queue.Contains(item);
109 }
110 }
111
112 /// <summary>
113 /// Return a count of the number of requests on this queue.
114 /// </summary>
115 public int Count()
116 {
117 lock (m_queueSync)
118 return m_queue.Count + m_pqueue.Count;
119 }
120
121 /// <summary>
122 /// Return the array of items on this queue.
123 /// </summary>
124 /// <remarks>
125 /// This method is not thread-safe. Do not rely on the result without consistent external locking.
126 /// </remarks>
127 public T[] GetQueueArray()
128 {
129 lock (m_queueSync)
130 {
131 if (m_queue.Count < 1 && m_pqueue.Count < 1)
132 return new T[0];
133
134 return m_queue.ToArray();
135 }
136 }
137
138 public void Clear()
139 {
140 lock (m_queueSync)
141 {
142 m_pqueue.Clear();
143 m_queue.Clear();
144 Monitor.Pulse(m_queueSync);
145 }
146 }
147 }
148}
diff --git a/OpenSim/Framework/Cache.cs b/OpenSim/Framework/Cache.cs
index 7ccc320..3ca85d7 100644
--- a/OpenSim/Framework/Cache.cs
+++ b/OpenSim/Framework/Cache.cs
@@ -390,17 +390,21 @@ namespace OpenSim.Framework
390 390
391 Object data = fetch(index); 391 Object data = fetch(index);
392 392
393 if (data == null && (m_Flags & CacheFlags.CacheMissing) == 0) 393 if (data == null)
394 return null;
395
396 lock (m_Index)
397 { 394 {
398 CacheItemBase missing = new CacheItemBase(index); 395 if((m_Flags & CacheFlags.CacheMissing) != 0)
399 if (!m_Index.Contains(missing)) 396 {
400 { 397 lock (m_Index)
401 m_Index.Add(missing); 398 {
402 m_Lookup[index] = missing; 399 CacheItemBase missing = new CacheItemBase(index);
403 } 400 if (!m_Index.Contains(missing))
401 {
402 m_Index.Add(missing);
403 m_Lookup[index] = missing;
404 }
405 }
406 }
407 return null;
404 } 408 }
405 409
406 Store(index, data); 410 Store(index, data);
diff --git a/OpenSim/Framework/ChildAgentDataUpdate.cs b/OpenSim/Framework/ChildAgentDataUpdate.cs
index d6d8dde..ee5007a 100644
--- a/OpenSim/Framework/ChildAgentDataUpdate.cs
+++ b/OpenSim/Framework/ChildAgentDataUpdate.cs
@@ -375,6 +375,7 @@ namespace OpenSim.Framework
375 public string ActiveGroupTitle = null; 375 public string ActiveGroupTitle = null;
376 public UUID agentCOF; 376 public UUID agentCOF;
377 public byte CrossingFlags; 377 public byte CrossingFlags;
378 public byte CrossExtraFlags;
378 379
379 public Dictionary<ulong, string> ChildrenCapSeeds = null; 380 public Dictionary<ulong, string> ChildrenCapSeeds = null;
380 public Animation[] Anims; 381 public Animation[] Anims;
@@ -454,6 +455,8 @@ namespace OpenSim.Framework
454 455
455 args["agent_cof"] = OSD.FromUUID(agentCOF); 456 args["agent_cof"] = OSD.FromUUID(agentCOF);
456 args["crossingflags"] = OSD.FromInteger(CrossingFlags); 457 args["crossingflags"] = OSD.FromInteger(CrossingFlags);
458 if(CrossingFlags != 0)
459 args["crossExtraFlags"] = OSD.FromInteger(CrossExtraFlags);
457 460
458 args["active_group_id"] = OSD.FromUUID(ActiveGroupID); 461 args["active_group_id"] = OSD.FromUUID(ActiveGroupID);
459 args["active_group_name"] = OSD.FromString(ActiveGroupName); 462 args["active_group_name"] = OSD.FromString(ActiveGroupName);
@@ -646,6 +649,12 @@ namespace OpenSim.Framework
646 if (args.ContainsKey("crossingflags") && args["crossingflags"] != null) 649 if (args.ContainsKey("crossingflags") && args["crossingflags"] != null)
647 CrossingFlags = (byte)args["crossingflags"].AsInteger(); 650 CrossingFlags = (byte)args["crossingflags"].AsInteger();
648 651
652 if(CrossingFlags != 0)
653 {
654 if (args.ContainsKey("crossExtraFlags") && args["crossExtraFlags"] != null)
655 CrossExtraFlags = (byte)args["crossExtraFlags"].AsInteger();
656 }
657
649 if (args.ContainsKey("active_group_id") && args["active_group_id"] != null) 658 if (args.ContainsKey("active_group_id") && args["active_group_id"] != null)
650 ActiveGroupID = args["active_group_id"].AsUUID(); 659 ActiveGroupID = args["active_group_id"].AsUUID();
651 660
diff --git a/OpenSim/Framework/Client/IClientIPEndpoint.cs b/OpenSim/Framework/Client/IClientIPEndpoint.cs
index 2b99bf0..2194616 100644
--- a/OpenSim/Framework/Client/IClientIPEndpoint.cs
+++ b/OpenSim/Framework/Client/IClientIPEndpoint.cs
@@ -34,6 +34,6 @@ namespace OpenSim.Framework.Client
34{ 34{
35 public interface IClientIPEndpoint 35 public interface IClientIPEndpoint
36 { 36 {
37 IPAddress EndPoint { get; } 37 IPEndPoint RemoteEndPoint { get; }
38 } 38 }
39} 39}
diff --git a/OpenSim/Framework/ClientInfo.cs b/OpenSim/Framework/ClientInfo.cs
index 98e4465..a1ca9bc 100644
--- a/OpenSim/Framework/ClientInfo.cs
+++ b/OpenSim/Framework/ClientInfo.cs
@@ -36,14 +36,8 @@ namespace OpenSim.Framework
36 public readonly DateTime StartedTime = DateTime.Now; 36 public readonly DateTime StartedTime = DateTime.Now;
37 public AgentCircuitData agentcircuit = null; 37 public AgentCircuitData agentcircuit = null;
38 38
39 public Dictionary<uint, byte[]> needAck;
40
41 public List<byte[]> out_packets = new List<byte[]>();
42 public Dictionary<uint, uint> pendingAcks = new Dictionary<uint,uint>();
43 public EndPoint proxyEP; 39 public EndPoint proxyEP;
44 40
45 public uint sequence;
46 public byte[] usecircuit;
47 public EndPoint userEP; 41 public EndPoint userEP;
48 42
49 public int resendThrottle; 43 public int resendThrottle;
@@ -59,9 +53,5 @@ namespace OpenSim.Framework
59 public int targetThrottle; 53 public int targetThrottle;
60 54
61 public int maxThrottle; 55 public int maxThrottle;
62
63 public Dictionary<string, int> SyncRequests = new Dictionary<string,int>();
64 public Dictionary<string, int> AsyncRequests = new Dictionary<string,int>();
65 public Dictionary<string, int> GenericRequests = new Dictionary<string,int>();
66 } 56 }
67} 57}
diff --git a/OpenSim/Framework/ClientManager.cs b/OpenSim/Framework/ClientManager.cs
index baff2f4..45c54e4 100644
--- a/OpenSim/Framework/ClientManager.cs
+++ b/OpenSim/Framework/ClientManager.cs
@@ -27,10 +27,8 @@
27 27
28using System; 28using System;
29using System.Collections.Generic; 29using System.Collections.Generic;
30using System.Reflection;
31using System.Net; 30using System.Net;
32using OpenMetaverse; 31using OpenMetaverse;
33using OpenMetaverse.Packets;
34 32
35namespace OpenSim.Framework 33namespace OpenSim.Framework
36{ 34{
@@ -76,20 +74,16 @@ namespace OpenSim.Framework
76 { 74 {
77 lock (m_syncRoot) 75 lock (m_syncRoot)
78 { 76 {
79 if (m_dict1.ContainsKey(value.AgentId) || m_dict2.ContainsKey(value.RemoteEndPoint)) 77 // allow self healing
80 return false; 78// if (m_dict1.ContainsKey(value.AgentId) || m_dict2.ContainsKey(value.RemoteEndPoint))
79// return false;
81 80
82 m_dict1[value.AgentId] = value; 81 m_dict1[value.AgentId] = value;
83 m_dict2[value.RemoteEndPoint] = value; 82 m_dict2[value.RemoteEndPoint] = value;
84 83
85 IClientAPI[] oldArray = m_array; 84 // dict1 is the master
86 int oldLength = oldArray.Length; 85 IClientAPI[] newArray = new IClientAPI[m_dict1.Count];
87 86 m_dict1.Values.CopyTo(newArray, 0);
88 IClientAPI[] newArray = new IClientAPI[oldLength + 1];
89 for (int i = 0; i < oldLength; i++)
90 newArray[i] = oldArray[i];
91 newArray[oldLength] = value;
92
93 m_array = newArray; 87 m_array = newArray;
94 } 88 }
95 89
@@ -112,22 +106,12 @@ namespace OpenSim.Framework
112 m_dict1.Remove(key); 106 m_dict1.Remove(key);
113 m_dict2.Remove(value.RemoteEndPoint); 107 m_dict2.Remove(value.RemoteEndPoint);
114 108
115 IClientAPI[] oldArray = m_array; 109 IClientAPI[] newArray = new IClientAPI[m_dict1.Count];
116 int oldLength = oldArray.Length; 110 m_dict1.Values.CopyTo(newArray, 0);
117
118 IClientAPI[] newArray = new IClientAPI[oldLength - 1];
119 int j = 0;
120 for (int i = 0; i < oldLength; i++)
121 {
122 if (oldArray[i] != value)
123 newArray[j++] = oldArray[i];
124 }
125
126 m_array = newArray; 111 m_array = newArray;
127 return true; 112 return true;
128 } 113 }
129 } 114 }
130
131 return false; 115 return false;
132 } 116 }
133 117
@@ -197,25 +181,11 @@ namespace OpenSim.Framework
197 } 181 }
198 182
199 /// <summary> 183 /// <summary>
200 /// Performs a given task in parallel for each of the elements in the
201 /// collection
202 /// </summary>
203 /// <param name="action">Action to perform on each element</param>
204 public void ForEach(Action<IClientAPI> action)
205 {
206 IClientAPI[] localArray = m_array;
207 Parallel.For(0, localArray.Length,
208 delegate(int i)
209 { action(localArray[i]); }
210 );
211 }
212
213 /// <summary>
214 /// Performs a given task synchronously for each of the elements in 184 /// Performs a given task synchronously for each of the elements in
215 /// the collection 185 /// the collection
216 /// </summary> 186 /// </summary>
217 /// <param name="action">Action to perform on each element</param> 187 /// <param name="action">Action to perform on each element</param>
218 public void ForEachSync(Action<IClientAPI> action) 188 public void ForEach(Action<IClientAPI> action)
219 { 189 {
220 IClientAPI[] localArray = m_array; 190 IClientAPI[] localArray = m_array;
221 for (int i = 0; i < localArray.Length; i++) 191 for (int i = 0; i < localArray.Length; i++)
diff --git a/OpenSim/Framework/Console/LocalConsole.cs b/OpenSim/Framework/Console/LocalConsole.cs
index 73f0323..ba32f50 100644
--- a/OpenSim/Framework/Console/LocalConsole.cs
+++ b/OpenSim/Framework/Console/LocalConsole.cs
@@ -46,6 +46,7 @@ namespace OpenSim.Framework.Console
46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 46 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
47 private string m_historyPath; 47 private string m_historyPath;
48 private bool m_historyEnable; 48 private bool m_historyEnable;
49 private bool m_historytimestamps;
49 50
50 // private readonly object m_syncRoot = new object(); 51 // private readonly object m_syncRoot = new object();
51 private const string LOGLEVEL_NONE = "(none)"; 52 private const string LOGLEVEL_NONE = "(none)";
@@ -98,15 +99,30 @@ namespace OpenSim.Framework.Console
98 string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt"); 99 string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt");
99 int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100); 100 int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100);
100 m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile)); 101 m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile));
101 m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1}", m_historySize, m_historyPath); 102 m_historytimestamps = startupConfig.GetBoolean("ConsoleHistoryTimeStamp", false);
103 m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1} {2} timestamps",
104 m_historySize, m_historyPath, m_historytimestamps?"with":"without");
102 105
103 if (File.Exists(m_historyPath)) 106 if (File.Exists(m_historyPath))
104 { 107 {
108 List<string> originallines = new List<string>();
105 using (StreamReader history_file = new StreamReader(m_historyPath)) 109 using (StreamReader history_file = new StreamReader(m_historyPath))
106 { 110 {
107 string line; 111 string line;
108 while ((line = history_file.ReadLine()) != null) 112 while ((line = history_file.ReadLine()) != null)
109 { 113 {
114 originallines.Add(line);
115 if(line.StartsWith("["))
116 {
117 int indx = line.IndexOf("]:> ");
118 if(indx > 0)
119 {
120 if(indx + 4 >= line.Length)
121 line = String.Empty;
122 else
123 line = line.Substring(indx + 4);
124 }
125 }
110 m_history.Add(line); 126 m_history.Add(line);
111 } 127 }
112 } 128 }
@@ -114,11 +130,14 @@ namespace OpenSim.Framework.Console
114 if (m_history.Count > m_historySize) 130 if (m_history.Count > m_historySize)
115 { 131 {
116 while (m_history.Count > m_historySize) 132 while (m_history.Count > m_historySize)
133 {
117 m_history.RemoveAt(0); 134 m_history.RemoveAt(0);
135 originallines.RemoveAt(0);
136 }
118 137
119 using (StreamWriter history_file = new StreamWriter(m_historyPath)) 138 using (StreamWriter history_file = new StreamWriter(m_historyPath))
120 { 139 {
121 foreach (string line in m_history) 140 foreach (string line in originallines)
122 { 141 {
123 history_file.WriteLine(line); 142 history_file.WriteLine(line);
124 } 143 }
@@ -141,6 +160,8 @@ namespace OpenSim.Framework.Console
141 m_history.Add(text); 160 m_history.Add(text);
142 if (m_historyEnable) 161 if (m_historyEnable)
143 { 162 {
163 if (m_historytimestamps)
164 text = String.Format("[{0} {1}]:> {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), text);
144 File.AppendAllText(m_historyPath, text + Environment.NewLine); 165 File.AppendAllText(m_historyPath, text + Environment.NewLine);
145 } 166 }
146 } 167 }
diff --git a/OpenSim/Framework/Console/RemoteConsole.cs b/OpenSim/Framework/Console/RemoteConsole.cs
index f59c902..b90b75f 100644
--- a/OpenSim/Framework/Console/RemoteConsole.cs
+++ b/OpenSim/Framework/Console/RemoteConsole.cs
@@ -403,7 +403,7 @@ namespace OpenSim.Framework.Console
403 string uri = "/ReadResponses/" + sessionID.ToString() + "/"; 403 string uri = "/ReadResponses/" + sessionID.ToString() + "/";
404 404
405 m_Server.AddPollServiceHTTPHandler( 405 m_Server.AddPollServiceHTTPHandler(
406 uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, sessionID,25000)); // 25 secs timeout 406 uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, null, sessionID,25000)); // 25 secs timeout
407 407
408 // Our reply is an XML document. 408 // Our reply is an XML document.
409 // TODO: Change this to Linq.Xml 409 // TODO: Change this to Linq.Xml
@@ -687,7 +687,6 @@ namespace OpenSim.Framework.Console
687 result["int_response_code"] = 200; 687 result["int_response_code"] = 200;
688 result["content_type"] = "application/xml"; 688 result["content_type"] = "application/xml";
689 result["keepalive"] = false; 689 result["keepalive"] = false;
690 result["reusecontext"] = false;
691 result = CheckOrigin(result); 690 result = CheckOrigin(result);
692 691
693 return result; 692 return result;
@@ -713,7 +712,6 @@ namespace OpenSim.Framework.Console
713 result["int_response_code"] = 200; 712 result["int_response_code"] = 200;
714 result["content_type"] = "text/xml"; 713 result["content_type"] = "text/xml";
715 result["keepalive"] = false; 714 result["keepalive"] = false;
716 result["reusecontext"] = false;
717 result = CheckOrigin(result); 715 result = CheckOrigin(result);
718 716
719 return result; 717 return result;
diff --git a/OpenSim/Framework/Crc32.cs b/OpenSim/Framework/Crc32.cs
new file mode 100644
index 0000000..7ad1566
--- /dev/null
+++ b/OpenSim/Framework/Crc32.cs
@@ -0,0 +1,139 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Security.Cryptography;
30
31namespace OpenSim.Framework
32{
33 // this is more generic than openmetaverse CRC32
34
35 public class Crc32 : HashAlgorithm
36 {
37 public const UInt32 DefaultPolynomial = 0xedb88320;
38 public const UInt32 DefaultSeed = 0xffffffff;
39
40 private UInt32 hash;
41 private UInt32 seed;
42 private UInt32[] table;
43 private static UInt32[] defaultTable;
44
45 public Crc32()
46 {
47 table = InitializeTable(DefaultPolynomial);
48 seed = DefaultSeed;
49 Initialize();
50 }
51
52 public Crc32(UInt32 polynomial, UInt32 seed)
53 {
54 table = InitializeTable(polynomial);
55 this.seed = seed;
56 Initialize();
57 }
58
59 public override void Initialize()
60 {
61 hash = seed;
62 }
63
64 protected override void HashCore(byte[] buffer, int start, int length)
65 {
66 hash = CalculateHash(table, hash, buffer, start, length);
67 }
68
69 protected override byte[] HashFinal()
70 {
71 byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
72 this.HashValue = hashBuffer;
73 return hashBuffer;
74 }
75
76 public override int HashSize
77 {
78 get { return 32; }
79 }
80
81 public static UInt32 Compute(byte[] buffer)
82 {
83 return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
84 }
85
86 public static UInt32 Compute(UInt32 seed, byte[] buffer)
87 {
88 return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
89 }
90
91 public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
92 {
93 return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
94 }
95
96 private static UInt32[] InitializeTable(UInt32 polynomial)
97 {
98 if (polynomial == DefaultPolynomial && defaultTable != null)
99 return defaultTable;
100
101 UInt32[] createTable = new UInt32[256];
102 for (int i = 0; i < 256; i++)
103 {
104 UInt32 entry = (UInt32)i;
105 for (int j = 0; j < 8; j++)
106 if ((entry & 1) == 1)
107 entry = (entry >> 1) ^ polynomial;
108 else
109 entry = entry >> 1;
110 createTable[i] = entry;
111 }
112
113 if (polynomial == DefaultPolynomial)
114 defaultTable = createTable;
115
116 return createTable;
117 }
118
119 private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
120 {
121 UInt32 crc = seed;
122 for (int i = start; i < size; i++)
123 unchecked
124 {
125 crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
126 }
127 return crc;
128 }
129
130 private byte[] UInt32ToBigEndianBytes(UInt32 x)
131 {
132 return new byte[] {
133 (byte)((x >> 24) & 0xff),
134 (byte)((x >> 16) & 0xff),
135 (byte)((x >> 8) & 0xff),
136 (byte)(x & 0xff) };
137 }
138 }
139}
diff --git a/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs b/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
index 55ec13e..816523b 100644
--- a/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
+++ b/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
@@ -74,21 +74,19 @@ namespace OpenSim.Framework
74 { 74 {
75 rwLock.EnterWriteLock(); 75 rwLock.EnterWriteLock();
76 gotLock = true; 76 gotLock = true;
77 if (Dictionary1.ContainsKey(key1))
78 {
79 if (!Dictionary2.ContainsKey(key2))
80 throw new ArgumentException("key1 exists in the dictionary but not key2");
81 }
82 else if (Dictionary2.ContainsKey(key2))
83 {
84 if (!Dictionary1.ContainsKey(key1))
85 throw new ArgumentException("key2 exists in the dictionary but not key1");
86 }
87 Dictionary1[key1] = value;
88 Dictionary2[key2] = value;
77 } 89 }
78
79 if (Dictionary1.ContainsKey(key1))
80 {
81 if (!Dictionary2.ContainsKey(key2))
82 throw new ArgumentException("key1 exists in the dictionary but not key2");
83 }
84 else if (Dictionary2.ContainsKey(key2))
85 {
86 if (!Dictionary1.ContainsKey(key1))
87 throw new ArgumentException("key2 exists in the dictionary but not key1");
88 }
89
90 Dictionary1[key1] = value;
91 Dictionary2[key2] = value;
92 } 90 }
93 finally 91 finally
94 { 92 {
@@ -112,10 +110,9 @@ namespace OpenSim.Framework
112 { 110 {
113 rwLock.EnterWriteLock(); 111 rwLock.EnterWriteLock();
114 gotLock = true; 112 gotLock = true;
113 Dictionary1.Remove(key1);
114 success = Dictionary2.Remove(key2);
115 } 115 }
116
117 Dictionary1.Remove(key1);
118 success = Dictionary2.Remove(key2);
119 } 116 }
120 finally 117 finally
121 { 118 {
@@ -151,8 +148,12 @@ namespace OpenSim.Framework
151 { 148 {
152 if (kvp.Value.Equals(value)) 149 if (kvp.Value.Equals(value))
153 { 150 {
154 Dictionary1.Remove(key1); 151 try { }
155 Dictionary2.Remove(kvp.Key); 152 finally
153 {
154 Dictionary1.Remove(key1);
155 Dictionary2.Remove(kvp.Key);
156 }
156 found = true; 157 found = true;
157 break; 158 break;
158 } 159 }
@@ -193,8 +194,12 @@ namespace OpenSim.Framework
193 { 194 {
194 if (kvp.Value.Equals(value)) 195 if (kvp.Value.Equals(value))
195 { 196 {
196 Dictionary2.Remove(key2); 197 try { }
197 Dictionary1.Remove(kvp.Key); 198 finally
199 {
200 Dictionary2.Remove(key2);
201 Dictionary1.Remove(kvp.Key);
202 }
198 found = true; 203 found = true;
199 break; 204 break;
200 } 205 }
@@ -224,10 +229,9 @@ namespace OpenSim.Framework
224 { 229 {
225 rwLock.EnterWriteLock(); 230 rwLock.EnterWriteLock();
226 gotLock = true; 231 gotLock = true;
232 Dictionary1.Clear();
233 Dictionary2.Clear();
227 } 234 }
228
229 Dictionary1.Clear();
230 Dictionary2.Clear();
231 } 235 }
232 finally 236 finally
233 { 237 {
@@ -485,15 +489,15 @@ namespace OpenSim.Framework
485 try {} 489 try {}
486 finally 490 finally
487 { 491 {
488 rwLock.EnterUpgradeableReadLock(); 492 rwLock.EnterWriteLock();
489 gotWriteLock = true; 493 gotWriteLock = true;
490 }
491 494
492 for (int i = 0; i < list.Count; i++) 495 for (int i = 0; i < list.Count; i++)
493 Dictionary1.Remove(list[i]); 496 Dictionary1.Remove(list[i]);
494 497
495 for (int i = 0; i < list2.Count; i++) 498 for (int i = 0; i < list2.Count; i++)
496 Dictionary2.Remove(list2[i]); 499 Dictionary2.Remove(list2[i]);
500 }
497 } 501 }
498 finally 502 finally
499 { 503 {
diff --git a/OpenSim/Framework/EstateSettings.cs b/OpenSim/Framework/EstateSettings.cs
index 7134cbf..1b5ebfa 100644
--- a/OpenSim/Framework/EstateSettings.cs
+++ b/OpenSim/Framework/EstateSettings.cs
@@ -44,7 +44,6 @@ namespace OpenSim.Framework
44 // Only the client uses these 44 // Only the client uses these
45 // 45 //
46 private uint m_EstateID = 0; 46 private uint m_EstateID = 0;
47
48 public uint EstateID 47 public uint EstateID
49 { 48 {
50 get { return m_EstateID; } 49 get { return m_EstateID; }
@@ -52,7 +51,6 @@ namespace OpenSim.Framework
52 } 51 }
53 52
54 private string m_EstateName = "My Estate"; 53 private string m_EstateName = "My Estate";
55
56 public string EstateName 54 public string EstateName
57 { 55 {
58 get { return m_EstateName; } 56 get { return m_EstateName; }
@@ -60,7 +58,6 @@ namespace OpenSim.Framework
60 } 58 }
61 59
62 private bool m_AllowLandmark = true; 60 private bool m_AllowLandmark = true;
63
64 public bool AllowLandmark 61 public bool AllowLandmark
65 { 62 {
66 get { return m_AllowLandmark; } 63 get { return m_AllowLandmark; }
@@ -68,7 +65,6 @@ namespace OpenSim.Framework
68 } 65 }
69 66
70 private bool m_AllowParcelChanges = true; 67 private bool m_AllowParcelChanges = true;
71
72 public bool AllowParcelChanges 68 public bool AllowParcelChanges
73 { 69 {
74 get { return m_AllowParcelChanges; } 70 get { return m_AllowParcelChanges; }
@@ -76,7 +72,6 @@ namespace OpenSim.Framework
76 } 72 }
77 73
78 private bool m_AllowSetHome = true; 74 private bool m_AllowSetHome = true;
79
80 public bool AllowSetHome 75 public bool AllowSetHome
81 { 76 {
82 get { return m_AllowSetHome; } 77 get { return m_AllowSetHome; }
@@ -84,7 +79,6 @@ namespace OpenSim.Framework
84 } 79 }
85 80
86 private uint m_ParentEstateID = 1; 81 private uint m_ParentEstateID = 1;
87
88 public uint ParentEstateID 82 public uint ParentEstateID
89 { 83 {
90 get { return m_ParentEstateID; } 84 get { return m_ParentEstateID; }
@@ -92,7 +86,6 @@ namespace OpenSim.Framework
92 } 86 }
93 87
94 private float m_BillableFactor = 0.0f; 88 private float m_BillableFactor = 0.0f;
95
96 public float BillableFactor 89 public float BillableFactor
97 { 90 {
98 get { return m_BillableFactor; } 91 get { return m_BillableFactor; }
@@ -100,7 +93,6 @@ namespace OpenSim.Framework
100 } 93 }
101 94
102 private int m_PricePerMeter = 1; 95 private int m_PricePerMeter = 1;
103
104 public int PricePerMeter 96 public int PricePerMeter
105 { 97 {
106 get { return m_PricePerMeter; } 98 get { return m_PricePerMeter; }
@@ -108,7 +100,6 @@ namespace OpenSim.Framework
108 } 100 }
109 101
110 private int m_RedirectGridX = 0; 102 private int m_RedirectGridX = 0;
111
112 public int RedirectGridX 103 public int RedirectGridX
113 { 104 {
114 get { return m_RedirectGridX; } 105 get { return m_RedirectGridX; }
@@ -116,7 +107,6 @@ namespace OpenSim.Framework
116 } 107 }
117 108
118 private int m_RedirectGridY = 0; 109 private int m_RedirectGridY = 0;
119
120 public int RedirectGridY 110 public int RedirectGridY
121 { 111 {
122 get { return m_RedirectGridY; } 112 get { return m_RedirectGridY; }
@@ -126,7 +116,6 @@ namespace OpenSim.Framework
126 // Used by the sim 116 // Used by the sim
127 // 117 //
128 private bool m_UseGlobalTime = true; 118 private bool m_UseGlobalTime = true;
129
130 public bool UseGlobalTime 119 public bool UseGlobalTime
131 { 120 {
132 get { return m_UseGlobalTime; } 121 get { return m_UseGlobalTime; }
@@ -134,7 +123,6 @@ namespace OpenSim.Framework
134 } 123 }
135 124
136 private bool m_FixedSun = false; 125 private bool m_FixedSun = false;
137
138 public bool FixedSun 126 public bool FixedSun
139 { 127 {
140 get { return m_FixedSun; } 128 get { return m_FixedSun; }
@@ -142,7 +130,6 @@ namespace OpenSim.Framework
142 } 130 }
143 131
144 private double m_SunPosition = 0.0; 132 private double m_SunPosition = 0.0;
145
146 public double SunPosition 133 public double SunPosition
147 { 134 {
148 get { return m_SunPosition; } 135 get { return m_SunPosition; }
@@ -150,7 +137,6 @@ namespace OpenSim.Framework
150 } 137 }
151 138
152 private bool m_AllowVoice = true; 139 private bool m_AllowVoice = true;
153
154 public bool AllowVoice 140 public bool AllowVoice
155 { 141 {
156 get { return m_AllowVoice; } 142 get { return m_AllowVoice; }
@@ -158,7 +144,6 @@ namespace OpenSim.Framework
158 } 144 }
159 145
160 private bool m_AllowDirectTeleport = true; 146 private bool m_AllowDirectTeleport = true;
161
162 public bool AllowDirectTeleport 147 public bool AllowDirectTeleport
163 { 148 {
164 get { return m_AllowDirectTeleport; } 149 get { return m_AllowDirectTeleport; }
@@ -166,23 +151,22 @@ namespace OpenSim.Framework
166 } 151 }
167 152
168 private bool m_DenyAnonymous = false; 153 private bool m_DenyAnonymous = false;
169
170 public bool DenyAnonymous 154 public bool DenyAnonymous
171 { 155 {
172 get { return m_DenyAnonymous; } 156 get { return m_DenyAnonymous; }
173 set { m_DenyAnonymous = value; } 157 set { m_DenyAnonymous = value; }
174 } 158 }
175 159
160 // no longer in used, may be reassigned
176 private bool m_DenyIdentified = false; 161 private bool m_DenyIdentified = false;
177
178 public bool DenyIdentified 162 public bool DenyIdentified
179 { 163 {
180 get { return m_DenyIdentified; } 164 get { return m_DenyIdentified; }
181 set { m_DenyIdentified = value; } 165 set { m_DenyIdentified = value; }
182 } 166 }
183 167
168 // no longer in used, may be reassigned
184 private bool m_DenyTransacted = false; 169 private bool m_DenyTransacted = false;
185
186 public bool DenyTransacted 170 public bool DenyTransacted
187 { 171 {
188 get { return m_DenyTransacted; } 172 get { return m_DenyTransacted; }
@@ -190,7 +174,6 @@ namespace OpenSim.Framework
190 } 174 }
191 175
192 private bool m_AbuseEmailToEstateOwner = false; 176 private bool m_AbuseEmailToEstateOwner = false;
193
194 public bool AbuseEmailToEstateOwner 177 public bool AbuseEmailToEstateOwner
195 { 178 {
196 get { return m_AbuseEmailToEstateOwner; } 179 get { return m_AbuseEmailToEstateOwner; }
@@ -198,7 +181,6 @@ namespace OpenSim.Framework
198 } 181 }
199 182
200 private bool m_BlockDwell = false; 183 private bool m_BlockDwell = false;
201
202 public bool BlockDwell 184 public bool BlockDwell
203 { 185 {
204 get { return m_BlockDwell; } 186 get { return m_BlockDwell; }
@@ -206,7 +188,6 @@ namespace OpenSim.Framework
206 } 188 }
207 189
208 private bool m_EstateSkipScripts = false; 190 private bool m_EstateSkipScripts = false;
209
210 public bool EstateSkipScripts 191 public bool EstateSkipScripts
211 { 192 {
212 get { return m_EstateSkipScripts; } 193 get { return m_EstateSkipScripts; }
@@ -214,7 +195,6 @@ namespace OpenSim.Framework
214 } 195 }
215 196
216 private bool m_ResetHomeOnTeleport = false; 197 private bool m_ResetHomeOnTeleport = false;
217
218 public bool ResetHomeOnTeleport 198 public bool ResetHomeOnTeleport
219 { 199 {
220 get { return m_ResetHomeOnTeleport; } 200 get { return m_ResetHomeOnTeleport; }
@@ -222,15 +202,13 @@ namespace OpenSim.Framework
222 } 202 }
223 203
224 private bool m_TaxFree = false; 204 private bool m_TaxFree = false;
225 205 public bool TaxFree // this is now AllowAccessOverride, keeping same name to reuse DB entries
226 public bool TaxFree
227 { 206 {
228 get { return m_TaxFree; } 207 get { return m_TaxFree; }
229 set { m_TaxFree = value; } 208 set { m_TaxFree = value; }
230 } 209 }
231 210
232 private bool m_PublicAccess = true; 211 private bool m_PublicAccess = true;
233
234 public bool PublicAccess 212 public bool PublicAccess
235 { 213 {
236 get { return m_PublicAccess; } 214 get { return m_PublicAccess; }
@@ -246,7 +224,6 @@ namespace OpenSim.Framework
246 } 224 }
247 225
248 private UUID m_EstateOwner = UUID.Zero; 226 private UUID m_EstateOwner = UUID.Zero;
249
250 public UUID EstateOwner 227 public UUID EstateOwner
251 { 228 {
252 get { return m_EstateOwner; } 229 get { return m_EstateOwner; }
@@ -254,7 +231,6 @@ namespace OpenSim.Framework
254 } 231 }
255 232
256 private bool m_DenyMinors = false; 233 private bool m_DenyMinors = false;
257
258 public bool DenyMinors 234 public bool DenyMinors
259 { 235 {
260 get { return m_DenyMinors; } 236 get { return m_DenyMinors; }
@@ -280,7 +256,6 @@ namespace OpenSim.Framework
280 } 256 }
281 257
282 private List<UUID> l_EstateAccess = new List<UUID>(); 258 private List<UUID> l_EstateAccess = new List<UUID>();
283
284 public UUID[] EstateAccess 259 public UUID[] EstateAccess
285 { 260 {
286 get { return l_EstateAccess.ToArray(); } 261 get { return l_EstateAccess.ToArray(); }
@@ -288,13 +263,15 @@ namespace OpenSim.Framework
288 } 263 }
289 264
290 private List<UUID> l_EstateGroups = new List<UUID>(); 265 private List<UUID> l_EstateGroups = new List<UUID>();
291
292 public UUID[] EstateGroups 266 public UUID[] EstateGroups
293 { 267 {
294 get { return l_EstateGroups.ToArray(); } 268 get { return l_EstateGroups.ToArray(); }
295 set { l_EstateGroups = new List<UUID>(value); } 269 set { l_EstateGroups = new List<UUID>(value); }
296 } 270 }
297 271
272 public bool DoDenyMinors = true;
273 public bool DoDenyAnonymous = true;
274
298 public EstateSettings() 275 public EstateSettings()
299 { 276 {
300 } 277 }
@@ -402,14 +379,14 @@ namespace OpenSim.Framework
402 379
403 if (!HasAccess(avatarID)) 380 if (!HasAccess(avatarID))
404 { 381 {
405 if (DenyMinors) 382 if (DoDenyMinors && DenyMinors)
406 { 383 {
407 if ((userFlags & 32) == 0) 384 if ((userFlags & 32) == 0)
408 { 385 {
409 return true; 386 return true;
410 } 387 }
411 } 388 }
412 if (DenyAnonymous) 389 if (DoDenyAnonymous && DenyAnonymous)
413 { 390 {
414 if ((userFlags & 4) == 0) 391 if ((userFlags & 4) == 0)
415 { 392 {
@@ -572,14 +549,41 @@ namespace OpenSim.Framework
572 549
573 // EstateBans are special 550 // EstateBans are special
574 if (map.ContainsKey("EstateBans")) 551 if (map.ContainsKey("EstateBans"))
575 { 552 {
576 var banData = ((Dictionary<string, object>)map["EstateBans"]).Values; 553 if(map["EstateBans"] is string)
577 EstateBan[] bans = new EstateBan[banData.Count]; 554 {
578 int b = 0; 555 // JSON encoded bans map
579 foreach (Dictionary<string, object> ban in banData) 556 Dictionary<string, EstateBan> bdata = new Dictionary<string, EstateBan>();
580 bans[b++] = new EstateBan(ban); 557 try
581 PropertyInfo bansProperty = this.GetType().GetProperty("EstateBans", BindingFlags.Public | BindingFlags.Instance); 558 {
582 bansProperty.SetValue(this, bans, null); 559 // bypass libovm, we dont need even more useless high level maps
560 // this should only be called once.. but no problem, i hope
561 // (other uses may need more..)
562 LitJson.JsonMapper.RegisterImporter<string, UUID>((input) => new UUID(input));
563 bdata = LitJson.JsonMapper.ToObject<Dictionary<string,EstateBan>>((string)map["EstateBans"]);
564 }
565 // catch(Exception e)
566 catch
567 {
568 return;
569 }
570 EstateBan[] jbans = new EstateBan[bdata.Count];
571 bdata.Values.CopyTo(jbans,0);
572
573 PropertyInfo jbansProperty = this.GetType().GetProperty("EstateBans", BindingFlags.Public | BindingFlags.Instance);
574 jbansProperty.SetValue(this, jbans, null);
575 }
576 else
577 {
578 var banData = ((Dictionary<string, object>)map["EstateBans"]).Values;
579 EstateBan[] bans = new EstateBan[banData.Count];
580
581 int b = 0;
582 foreach (Dictionary<string, object> ban in banData)
583 bans[b++] = new EstateBan(ban);
584 PropertyInfo bansProperty = this.GetType().GetProperty("EstateBans", BindingFlags.Public | BindingFlags.Instance);
585 bansProperty.SetValue(this, bans, null);
586 }
583 } 587 }
584 } 588 }
585 } 589 }
diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs
index ab6d58f..f8bf583 100644
--- a/OpenSim/Framework/IClientAPI.cs
+++ b/OpenSim/Framework/IClientAPI.cs
@@ -443,7 +443,7 @@ namespace OpenSim.Framework
443 public delegate void DeclineCallingCard(IClientAPI remoteClient, UUID transactionID); 443 public delegate void DeclineCallingCard(IClientAPI remoteClient, UUID transactionID);
444 444
445 public delegate void SoundTrigger( 445 public delegate void SoundTrigger(
446 UUID soundId, UUID ownerid, UUID objid, UUID parentid, double Gain, Vector3 Position, UInt64 Handle, float radius); 446 UUID soundId, UUID ownerid, UUID objid, UUID parentid, double Gain, Vector3 Position, UInt64 Handle);
447 447
448 public delegate void StartLure(byte lureType, string message, UUID targetID, IClientAPI client); 448 public delegate void StartLure(byte lureType, string message, UUID targetID, IClientAPI client);
449 public delegate void TeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client); 449 public delegate void TeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client);
@@ -685,9 +685,10 @@ namespace OpenSim.Framework
685 ExtraData = 1 << 20, 685 ExtraData = 1 << 20,
686 Sound = 1 << 21, 686 Sound = 1 << 21,
687 Joint = 1 << 22, 687 Joint = 1 << 22,
688 FullUpdate = 0x3fffffff, 688 FullUpdate = 0x0fffffff,
689 CancelKill = 0x7fffffff, 689 SendInTransit = 0x20000000,
690 Kill = 0x80000000 690 CancelKill = 0x4fffffff, // 1 << 30
691 Kill = 0x80000000 // 1 << 31
691 } 692 }
692 693
693/* included in .net 4.0 694/* included in .net 4.0
@@ -1187,7 +1188,8 @@ namespace OpenSim.Framework
1187 void SetAgentThrottleSilent(int throttle, int setting); 1188 void SetAgentThrottleSilent(int throttle, int setting);
1188 int GetAgentThrottleSilent(int throttle); 1189 int GetAgentThrottleSilent(int throttle);
1189 1190
1190 void SendAvatarDataImmediate(ISceneEntity avatar); 1191 void SendEntityFullUpdateImmediate(ISceneEntity entity);
1192 void SendEntityTerseUpdateImmediate(ISceneEntity entity);
1191 1193
1192 /// <summary> 1194 /// <summary>
1193 /// Send a positional, velocity, etc. update to the viewer for a given entity. 1195 /// Send a positional, velocity, etc. update to the viewer for a given entity.
@@ -1483,7 +1485,7 @@ namespace OpenSim.Framework
1483 void SendUserInfoReply(bool imViaEmail, bool visible, string email); 1485 void SendUserInfoReply(bool imViaEmail, bool visible, string email);
1484 1486
1485 void SendUseCachedMuteList(); 1487 void SendUseCachedMuteList();
1486 1488 void SendEmpytMuteList();
1487 void SendMuteListUpdate(string filename); 1489 void SendMuteListUpdate(string filename);
1488 1490
1489 void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals); 1491 void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals);
diff --git a/OpenSim/Framework/ILandChannel.cs b/OpenSim/Framework/ILandChannel.cs
index 44a24b9..e5ea596 100644
--- a/OpenSim/Framework/ILandChannel.cs
+++ b/OpenSim/Framework/ILandChannel.cs
@@ -33,6 +33,8 @@ namespace OpenSim.Region.Framework.Interfaces
33{ 33{
34 public interface ILandChannel 34 public interface ILandChannel
35 { 35 {
36
37 float BanLineSafeHeight {get;}
36 /// <summary> 38 /// <summary>
37 /// Get all parcels 39 /// Get all parcels
38 /// </summary> 40 /// </summary>
@@ -76,6 +78,8 @@ namespace OpenSim.Region.Framework.Interfaces
76 /// <returns></returns> 78 /// <returns></returns>
77 ILandObject GetLandObject(int localID); 79 ILandObject GetLandObject(int localID);
78 80
81 ILandObject GetLandObject(UUID GlobalID);
82
79 /// <summary> 83 /// <summary>
80 /// Clear the land channel of all parcels. 84 /// Clear the land channel of all parcels.
81 /// </summary> 85 /// </summary>
@@ -86,6 +90,7 @@ namespace OpenSim.Region.Framework.Interfaces
86 90
87 bool IsForcefulBansAllowed(); 91 bool IsForcefulBansAllowed();
88 void UpdateLandObject(int localID, LandData data); 92 void UpdateLandObject(int localID, LandData data);
93 void SendParcelsOverlay(IClientAPI client);
89 void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient); 94 void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient);
90 void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel); 95 void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel);
91 void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel); 96 void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel);
@@ -94,6 +99,5 @@ namespace OpenSim.Region.Framework.Interfaces
94 void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id); 99 void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id);
95 void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id); 100 void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id);
96 void sendClientInitialLandInfo(IClientAPI remoteClient); 101 void sendClientInitialLandInfo(IClientAPI remoteClient);
97
98 } 102 }
99} 103}
diff --git a/OpenSim/Framework/ILandObject.cs b/OpenSim/Framework/ILandObject.cs
index f3b850d..a783256 100644
--- a/OpenSim/Framework/ILandObject.cs
+++ b/OpenSim/Framework/ILandObject.cs
@@ -189,5 +189,7 @@ namespace OpenSim.Framework
189 /// </summary> 189 /// </summary>
190 /// <returns>The music url.</returns> 190 /// <returns>The music url.</returns>
191 string GetMusicUrl(); 191 string GetMusicUrl();
192
193 void Clear();
192 } 194 }
193} 195}
diff --git a/OpenSim/Framework/IMoneyModule.cs b/OpenSim/Framework/IMoneyModule.cs
index be45438..c72c742 100644
--- a/OpenSim/Framework/IMoneyModule.cs
+++ b/OpenSim/Framework/IMoneyModule.cs
@@ -41,6 +41,7 @@ namespace OpenSim.Framework
41 void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData = ""); 41 void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData = "");
42 void ApplyUploadCharge(UUID agentID, int amount, string text); 42 void ApplyUploadCharge(UUID agentID, int amount, string text);
43 void MoveMoney(UUID fromUser, UUID toUser, int amount, string text); 43 void MoveMoney(UUID fromUser, UUID toUser, int amount, string text);
44 bool MoveMoney(UUID fromUser, UUID toUser, int amount, MoneyTransactionType type, string text);
44 45
45 int UploadCharge { get; } 46 int UploadCharge { get; }
46 int GroupCreationCharge { get; } 47 int GroupCreationCharge { get; }
diff --git a/OpenSim/Framework/InventoryItemBase.cs b/OpenSim/Framework/InventoryItemBase.cs
index c359a0c..b7f27bd 100644
--- a/OpenSim/Framework/InventoryItemBase.cs
+++ b/OpenSim/Framework/InventoryItemBase.cs
@@ -26,6 +26,7 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Text;
29using OpenMetaverse; 30using OpenMetaverse;
30 31
31namespace OpenSim.Framework 32namespace OpenSim.Framework
@@ -415,5 +416,40 @@ namespace OpenSim.Framework
415 { 416 {
416 return MemberwiseClone(); 417 return MemberwiseClone();
417 } 418 }
419
420 public void ToLLSDxml(StringBuilder lsl)
421 {
422 LLSDxmlEncode.AddMap(lsl);
423 LLSDxmlEncode.AddElem("parent_id", Folder, lsl);
424 LLSDxmlEncode.AddElem("asset_id", AssetID, lsl);
425 LLSDxmlEncode.AddElem("item_id", ID, lsl);
426
427 LLSDxmlEncode.AddMap("permissions",lsl);
428 LLSDxmlEncode.AddElem("creator_id", CreatorIdAsUuid, lsl);
429 LLSDxmlEncode.AddElem("owner_id", Owner, lsl);
430 LLSDxmlEncode.AddElem("group_id", GroupID, lsl);
431 LLSDxmlEncode.AddElem("base_mask", (int)CurrentPermissions, lsl);
432 LLSDxmlEncode.AddElem("owner_mask", (int)CurrentPermissions, lsl);
433 LLSDxmlEncode.AddElem("group_mask", (int)GroupPermissions, lsl);
434 LLSDxmlEncode.AddElem("everyone_mask", (int)EveryOnePermissions, lsl);
435 LLSDxmlEncode.AddElem("next_owner_mask", (int)NextPermissions, lsl);
436 LLSDxmlEncode.AddElem("is_owner_group", GroupOwned, lsl);
437 LLSDxmlEncode.AddEndMap(lsl);
438
439 LLSDxmlEncode.AddElem("type", AssetType, lsl);
440 LLSDxmlEncode.AddElem("inv_type", InvType, lsl);
441 LLSDxmlEncode.AddElem("flags", ((int)Flags) & 0xff, lsl);
442
443 LLSDxmlEncode.AddMap("sale_info",lsl);
444 LLSDxmlEncode.AddElem("sale_price", SalePrice, lsl);
445 LLSDxmlEncode.AddElem("sale_type", SaleType, lsl);
446 LLSDxmlEncode.AddEndMap(lsl);
447
448 LLSDxmlEncode.AddElem("name", Name, lsl);
449 LLSDxmlEncode.AddElem("desc", Description, lsl);
450 LLSDxmlEncode.AddElem("created_at", CreationDate, lsl);
451
452 LLSDxmlEncode.AddEndMap(lsl);
453 }
418 } 454 }
419} 455}
diff --git a/OpenSim/Framework/LLSDxmlEncode.cs b/OpenSim/Framework/LLSDxmlEncode.cs
new file mode 100644
index 0000000..ed5c4db
--- /dev/null
+++ b/OpenSim/Framework/LLSDxmlEncode.cs
@@ -0,0 +1,725 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28// a class for low level LLSD encoding into a provided StringBuilder
29// for cases where we already need to know the low level detail
30// and so using something like OSD or even protbuf is just a pure waste
31
32using System;
33using System.Globalization;
34using System.Text;
35using OpenMetaverse;
36
37namespace OpenSim.Framework
38{
39 public static class LLSDxmlEncode
40 {
41 static readonly DateTime depoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
42
43 public static void AddStart(StringBuilder sb, bool addxmlversion = false)
44 {
45 if(addxmlversion)
46 sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd>"); // legacy llsd xml name still valid
47 else
48 sb.Append("<llsd>");
49 }
50
51 // got tired of creating a stringbuilder all the time;
52 public static StringBuilder Start(int size = 256, bool addxmlversion = false)
53 {
54 StringBuilder sb = new StringBuilder(size);
55 if(addxmlversion)
56 sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd>"); // legacy llsd xml name still valid
57 else
58 sb.Append("<llsd>");
59 return sb;
60 }
61
62 public static void AddEnd(StringBuilder sb)
63 {
64 sb.Append("</llsd>");
65 }
66
67 public static string End(StringBuilder sb)
68 {
69 sb.Append("</llsd>");
70 return sb.ToString();
71 }
72
73 // map == a list of key value pairs
74 public static void AddMap(StringBuilder sb)
75 {
76 sb.Append("<map>");
77 }
78
79 public static void AddEndMap(StringBuilder sb)
80 {
81 sb.Append("</map>");
82 }
83
84 public static void AddEmptyMap(StringBuilder sb)
85 {
86 sb.Append("<map />");
87 }
88
89 // array == a list values
90 public static void AddArray(StringBuilder sb)
91 {
92 sb.Append("<array>");
93 }
94
95 public static void AddEndArray(StringBuilder sb)
96 {
97 sb.Append("</array>");
98 }
99
100 public static void AddEmptyArray(StringBuilder sb)
101 {
102 sb.Append("<array />");
103 }
104
105 // undefined or null
106 public static void AddUnknownElem(StringBuilder sb)
107 {
108 sb.Append("<undef />");
109 }
110
111 public static void AddElem(bool e, StringBuilder sb)
112 {
113 if(e)
114 sb.Append("<boolean>1</boolean>");
115 else
116 sb.Append("<boolean />");
117 }
118
119 public static void AddElem(byte e, StringBuilder sb)
120 {
121 if(e == 0)
122 sb.Append("<integer />");
123 else
124 {
125 sb.Append("<integer>");
126 sb.Append(e.ToString());
127 sb.Append("</integer>");
128 }
129 }
130
131 public static void AddElem(byte[] e, StringBuilder sb)
132 {
133 if(e == null || e.Length == 0)
134 sb.Append("binary />");
135 else
136 {
137 sb.Append("<binary>"); // encode64 is default
138 sb.Append(Convert.ToBase64String(e,Base64FormattingOptions.None));
139 sb.Append("</binary>");
140 }
141 }
142
143 public static void AddElem(int e, StringBuilder sb)
144 {
145 if(e == 0)
146 sb.Append("<integer />");
147 else
148 {
149 sb.Append("<integer>");
150 sb.Append(e.ToString());
151 sb.Append("</integer>");
152 }
153 }
154
155 public static void AddElem(float e, StringBuilder sb)
156 {
157 if(e == 0)
158 sb.Append("<real />");
159 else
160 {
161 sb.Append("<real>");
162 sb.Append(e.ToString(CultureInfo.InvariantCulture));
163 sb.Append("</real>");
164 }
165 }
166
167 public static void AddElem(Vector2 e, StringBuilder sb)
168 {
169 sb.Append("<map><key>x</key>");
170
171 if(e.X == 0)
172 sb.Append("<real /><key>y</key>");
173 else
174 {
175 sb.Append("<real>");
176 sb.Append(e.X.ToString(CultureInfo.InvariantCulture));
177 sb.Append("</real><key>y</key>");
178 }
179
180 if(e.Y == 0)
181 sb.Append("<real /></map>");
182 else
183 {
184 sb.Append("<real>");
185 sb.Append(e.Y.ToString(CultureInfo.InvariantCulture));
186 sb.Append("</real></map>");
187 }
188 }
189
190 public static void AddElem(Vector3 e, StringBuilder sb)
191 {
192 sb.Append("<map>key>x</key>");
193
194 if(e.X == 0)
195 sb.Append("<real /><key>y</key>");
196 else
197 {
198 sb.Append("<real>");
199 sb.Append(e.X.ToString(CultureInfo.InvariantCulture));
200 sb.Append("</real><key>y</key>");
201 }
202
203 if(e.Y == 0)
204 sb.Append("<real /><key>z</key>");
205 else
206 {
207 sb.Append("<real>");
208 sb.Append(e.Y.ToString(CultureInfo.InvariantCulture));
209 sb.Append("</real><key>z</key>");
210 }
211
212 if(e.Z == 0)
213 sb.Append("<real /></map>");
214 else
215 {
216 sb.Append("<real>");
217 sb.Append(e.Z.ToString(CultureInfo.InvariantCulture));
218 sb.Append("</real></map>");
219 }
220 }
221
222 public static void AddElem(Quaternion e, StringBuilder sb)
223 {
224 sb.Append("<map><key>x</key>");
225
226 if(e.X == 0)
227 sb.Append("<real /><key>y</key>");
228 else
229 {
230 sb.Append("<real>");
231 sb.Append(e.X.ToString(CultureInfo.InvariantCulture));
232 sb.Append("</real><key>y</key>");
233 }
234
235 if(e.Y == 0)
236 sb.Append("<real /><key>z</key>");
237 else
238 {
239 sb.Append("<real>");
240 sb.Append(e.Y.ToString(CultureInfo.InvariantCulture));
241 sb.Append("</real><key>z</key>");
242 }
243 if(e.Z == 0)
244 sb.Append("<real /><key>w</key>");
245 else
246 {
247 sb.Append("<real>");
248 sb.Append(e.Z.ToString(CultureInfo.InvariantCulture));
249 sb.Append("</real><key>w</key>");
250 }
251
252 if(e.W == 0)
253 sb.Append("<real /></map>");
254 else
255 {
256 sb.Append("<real>");
257 sb.Append(e.W.ToString(CultureInfo.InvariantCulture));
258 sb.Append("</real></map>");
259 }
260 }
261
262 public static void AddElem(double e, StringBuilder sb)
263 {
264 if(e == 0)
265 sb.Append("<real />");
266 else
267 {
268 sb.Append("<real>");
269 sb.Append(e.ToString(CultureInfo.InvariantCulture));
270 sb.Append("</real>");
271 }
272 }
273
274 public static void AddElem(UUID e, StringBuilder sb)
275 {
276 if(e == UUID.Zero)
277 sb.Append("<uuid />");
278 else
279 {
280 sb.Append("<uuid>");
281 EscapeToXML(e.ToString(), sb);
282 sb.Append("</uuid>");
283 }
284 }
285
286 public static void AddElem(string e, StringBuilder sb)
287 {
288 if(String.IsNullOrEmpty(e))
289 sb.Append("<string />");
290 else
291 {
292 sb.Append("<string>");
293 EscapeToXML(e.ToString(), sb);
294 sb.Append("</string>");
295 }
296 }
297
298 public static void AddRawElem(string e, StringBuilder sb)
299 {
300 if(String.IsNullOrEmpty(e))
301 sb.Append("<string />");
302 else
303 {
304 sb.Append("<string>");
305 sb.Append(e);
306 sb.Append("</string>");
307 }
308 }
309
310 public static void AddElem(Uri e, StringBuilder sb)
311 {
312 if(e == null)
313 {
314 sb.Append("<uri />");
315 return;
316 }
317
318 string s;
319 if (e.IsAbsoluteUri)
320 s = e.AbsoluteUri;
321 else
322 s = e.ToString();
323
324 if(String.IsNullOrEmpty(s))
325 sb.Append("<uri />");
326 else
327 {
328 sb.Append("<uri>");
329 sb.Append(s);
330 sb.Append("</uri>");
331 }
332 }
333
334 public static void AddElem(DateTime e, StringBuilder sb)
335 {
336 DateTime u = e.ToUniversalTime();
337 if(u == depoch)
338 {
339 sb.Append("<date />");
340 return;
341 }
342 string format;
343 if(u.Hour == 0 && u.Minute == 0 && u.Second == 0)
344 format = "yyyy-MM-dd";
345 else if (u.Millisecond > 0)
346 format = "yyyy-MM-ddTHH:mm:ss.ffZ";
347 else
348 format = "yyyy-MM-ddTHH:mm:ssZ";
349 sb.Append("<date>");
350 sb.Append(u.ToString(format,CultureInfo.InvariantCulture));
351 sb.Append("</date>");
352 }
353
354//************ key value *******************
355// assumes name is a valid llsd key
356
357 public static void AddMap(string name, StringBuilder sb)
358 {
359 sb.Append("<key>");
360 sb.Append(name);
361 sb.Append("</key><map>");
362 }
363
364 public static void AddEmptyMap(string name, StringBuilder sb)
365 {
366 sb.Append("<key>");
367 sb.Append(name);
368 sb.Append("</key><map />");
369 }
370
371 // array == a list values
372 public static void AddArray(string name, StringBuilder sb)
373 {
374 sb.Append("<key>");
375 sb.Append(name);
376 sb.Append("</key><array>");
377 }
378
379 public static void AddEmptyArray(string name, StringBuilder sb)
380 {
381 sb.Append("<key>");
382 sb.Append(name);
383 sb.Append("</key><array />");
384 }
385
386 // undefined or null
387 public static void AddUnknownElem(string name, StringBuilder sb)
388 {
389 sb.Append("<key>");
390 sb.Append(name);
391 sb.Append("</key><undef />");
392 }
393
394 public static void AddElem(string name, bool e, StringBuilder sb)
395 {
396 sb.Append("<key>");
397 sb.Append(name);
398 sb.Append("</key>");
399
400 if(e)
401 sb.Append("<boolean>1</boolean>");
402 else
403 sb.Append("<boolean />");
404 }
405
406 public static void AddElem(string name, byte e, StringBuilder sb)
407 {
408 sb.Append("<key>");
409 sb.Append(name);
410 sb.Append("</key>");
411
412 if(e == 0)
413 sb.Append("<integer />");
414 else
415 {
416 sb.Append("<integer>");
417 sb.Append(e.ToString());
418 sb.Append("</integer>");
419 }
420 }
421
422 public static void AddElem(string name, byte[] e, StringBuilder sb)
423 {
424 sb.Append("<key>");
425 sb.Append(name);
426 sb.Append("</key>");
427
428 if(e == null || e.Length == 0)
429 sb.Append("binary />");
430 else
431 {
432 sb.Append("<binary>"); // encode64 is default
433 sb.Append(Convert.ToBase64String(e,Base64FormattingOptions.None));
434 sb.Append("</binary>");
435 }
436 }
437
438 public static void AddElem(string name, int e, StringBuilder sb)
439 {
440 sb.Append("<key>");
441 sb.Append(name);
442 sb.Append("</key>");
443
444 if(e == 0)
445 sb.Append("<integer />");
446 else
447 {
448 sb.Append("<integer>");
449 sb.Append(e.ToString());
450 sb.Append("</integer>");
451 }
452 }
453
454 public static void AddElem(string name, float e, StringBuilder sb)
455 {
456 sb.Append("<key>");
457 sb.Append(name);
458 sb.Append("</key>");
459
460 if(e == 0)
461 sb.Append("<real />");
462 else
463 {
464 sb.Append("<real>");
465 sb.Append(e.ToString(CultureInfo.InvariantCulture));
466 sb.Append("</real>");
467 }
468 }
469
470 public static void AddElem(string name, Vector2 e, StringBuilder sb)
471 {
472 sb.Append("<key>");
473 sb.Append(name);
474 sb.Append("</key><map><key>x</key>");
475
476 if(e.X == 0)
477 sb.Append("<real /><key>y</key>");
478 else
479 {
480 sb.Append("<real>");
481 sb.Append(e.X.ToString(CultureInfo.InvariantCulture));
482 sb.Append("</real><key>y</key>");
483 }
484
485 if(e.Y == 0)
486 sb.Append("<real /></map>");
487 else
488 {
489 sb.Append("<real>");
490 sb.Append(e.Y.ToString(CultureInfo.InvariantCulture));
491 sb.Append("</real></map>");
492 }
493 }
494
495 public static void AddElem(string name, Vector3 e, StringBuilder sb)
496 {
497 sb.Append("<key>");
498 sb.Append(name);
499 sb.Append("</key><map>key>x</key>");
500
501 if(e.X == 0)
502 sb.Append("<real /><key>y</key>");
503 else
504 {
505 sb.Append("<real>");
506 sb.Append(e.X.ToString(CultureInfo.InvariantCulture));
507 sb.Append("</real><key>y</key>");
508 }
509
510 if(e.Y == 0)
511 sb.Append("<real /><key>z</key>");
512 else
513 {
514 sb.Append("<real>");
515 sb.Append(e.Y.ToString(CultureInfo.InvariantCulture));
516 sb.Append("</real><key>z</key>");
517 }
518
519 if(e.Z == 0)
520 sb.Append("<real /></map>");
521 else
522 {
523 sb.Append("<real>");
524 sb.Append(e.Z.ToString(CultureInfo.InvariantCulture));
525 sb.Append("</real></map>");
526 }
527 }
528
529 public static void AddElem(string name, Quaternion e, StringBuilder sb)
530 {
531 sb.Append("<key>");
532 sb.Append(name);
533 sb.Append("</key><map><key>x</key>");
534
535 if(e.X == 0)
536 sb.Append("<real /><key>y</key>");
537 else
538 {
539 sb.Append("<real>");
540 sb.Append(e.X.ToString(CultureInfo.InvariantCulture));
541 sb.Append("</real><key>y</key>");
542 }
543
544 if(e.Y == 0)
545 sb.Append("<real /><key>z</key>");
546 else
547 {
548 sb.Append("<real>");
549 sb.Append(e.Y.ToString(CultureInfo.InvariantCulture));
550 sb.Append("</real><key>z</key>");
551 }
552 if(e.Z == 0)
553 sb.Append("<real /><key>w</key>");
554 else
555 {
556 sb.Append("<real>");
557 sb.Append(e.Z.ToString(CultureInfo.InvariantCulture));
558 sb.Append("</real><key>w</key>");
559 }
560
561 if(e.W == 0)
562 sb.Append("<real /></map>");
563 else
564 {
565 sb.Append("<real>");
566 sb.Append(e.W.ToString(CultureInfo.InvariantCulture));
567 sb.Append("</real></map>");
568 }
569 }
570
571 public static void AddElem(string name, double e, StringBuilder sb)
572 {
573 sb.Append("<key>");
574 sb.Append(name);
575 sb.Append("</key>");
576
577 if(e == 0)
578 sb.Append("<real />");
579 else
580 {
581 sb.Append("<real>");
582 sb.Append(e.ToString(CultureInfo.InvariantCulture));
583 sb.Append("</real>");
584 }
585 }
586
587 public static void AddElem(string name, UUID e, StringBuilder sb)
588 {
589 sb.Append("<key>");
590 sb.Append(name);
591 sb.Append("</key>");
592
593 if(e == UUID.Zero)
594 sb.Append("<uuid />");
595 else
596 {
597 sb.Append("<uuid>");
598 EscapeToXML(e.ToString(), sb);
599 sb.Append("</uuid>");
600 }
601 }
602
603 public static void AddElem(string name, string e, StringBuilder sb)
604 {
605 sb.Append("<key>");
606 sb.Append(name);
607 sb.Append("</key>");
608
609 if(String.IsNullOrEmpty(e))
610 sb.Append("<string />");
611 else
612 {
613 sb.Append("<string>");
614 EscapeToXML(e.ToString(), sb);
615 sb.Append("</string>");
616 }
617 }
618
619 public static void AddRawElem(string name, string e, StringBuilder sb)
620 {
621 sb.Append("<key>");
622 sb.Append(name);
623 sb.Append("</key>");
624
625 if(String.IsNullOrEmpty(e))
626 sb.Append("<string />");
627 else
628 {
629 sb.Append("<string>");
630 sb.Append(e);
631 sb.Append("</string>");
632 }
633 }
634
635 public static void AddElem(string name, Uri e, StringBuilder sb)
636 {
637 sb.Append("<key>");
638 sb.Append(name);
639 sb.Append("</key>");
640
641 if(e == null)
642 {
643 sb.Append("<uri />");
644 return;
645 }
646
647 string s;
648 if (e.IsAbsoluteUri)
649 s = e.AbsoluteUri;
650 else
651 s = e.ToString();
652
653 if(String.IsNullOrEmpty(s))
654 sb.Append("<uri />");
655 else
656 {
657 sb.Append("<uri>");
658 sb.Append(s);
659 sb.Append("</uri>");
660 }
661 }
662
663 public static void AddElem(string name, DateTime e, StringBuilder sb)
664 {
665 sb.Append("<key>");
666 sb.Append(name);
667 sb.Append("</key>");
668
669 DateTime u = e.ToUniversalTime();
670 if(u == depoch)
671 {
672 sb.Append("<date />");
673 return;
674 }
675 string format;
676 if(u.Hour == 0 && u.Minute == 0 && u.Second == 0)
677 format = "yyyy-MM-dd";
678 else if (u.Millisecond > 0)
679 format = "yyyy-MM-ddTHH:mm:ss.ffZ";
680 else
681 format = "yyyy-MM-ddTHH:mm:ssZ";
682 sb.Append("<date>");
683 sb.Append(u.ToString(format,CultureInfo.InvariantCulture));
684 sb.Append("</date>");
685 }
686
687 public static void AddLLSD(string e, StringBuilder sb)
688 {
689 sb.Append(e);
690 }
691
692 public static void EscapeToXML(string s, StringBuilder sb)
693 {
694 int i;
695 char c;
696 int len = s.Length;
697
698 for (i = 0; i < len; i++)
699 {
700 c = s[i];
701 switch (c)
702 {
703 case '<':
704 sb.Append("&lt;");
705 break;
706 case '>':
707 sb.Append("&gt;");
708 break;
709 case '&':
710 sb.Append("&amp;");
711 break;
712 case '"':
713 sb.Append("&quot;");
714 break;
715 case '\\':
716 sb.Append("&apos;");
717 break;
718 default:
719 sb.Append(c);
720 break;
721 }
722 }
723 }
724 }
725}
diff --git a/OpenSim/Framework/LandData.cs b/OpenSim/Framework/LandData.cs
index 13d2977..13b58be 100644
--- a/OpenSim/Framework/LandData.cs
+++ b/OpenSim/Framework/LandData.cs
@@ -97,7 +97,9 @@ namespace OpenSim.Framework
97 private bool _mediaLoop = false; 97 private bool _mediaLoop = false;
98 private bool _obscureMusic = false; 98 private bool _obscureMusic = false;
99 private bool _obscureMedia = false; 99 private bool _obscureMedia = false;
100 private float _dwell = 0; 100
101 private float m_dwell = 0;
102 public double LastDwellTimeMS;
101 103
102 public bool SeeAVs { get; set; } 104 public bool SeeAVs { get; set; }
103 public bool AnyAVSounds { get; set; } 105 public bool AnyAVSounds { get; set; }
@@ -111,11 +113,12 @@ namespace OpenSim.Framework
111 { 113 {
112 get 114 get
113 { 115 {
114 return _dwell; 116 return m_dwell;
115 } 117 }
116 set 118 set
117 { 119 {
118 _dwell = value; 120 m_dwell = value;
121 LastDwellTimeMS = Util.GetTimeStampMS();
119 } 122 }
120 } 123 }
121 124
@@ -735,6 +738,7 @@ namespace OpenSim.Framework
735 SeeAVs = true; 738 SeeAVs = true;
736 AnyAVSounds = true; 739 AnyAVSounds = true;
737 GroupAVSounds = true; 740 GroupAVSounds = true;
741 LastDwellTimeMS = Util.GetTimeStampMS();
738 } 742 }
739 743
740 /// <summary> 744 /// <summary>
@@ -784,7 +788,7 @@ namespace OpenSim.Framework
784 landData._obscureMedia = _obscureMedia; 788 landData._obscureMedia = _obscureMedia;
785 landData._simwideArea = _simwideArea; 789 landData._simwideArea = _simwideArea;
786 landData._simwidePrims = _simwidePrims; 790 landData._simwidePrims = _simwidePrims;
787 landData._dwell = _dwell; 791 landData.m_dwell = m_dwell;
788 landData.SeeAVs = SeeAVs; 792 landData.SeeAVs = SeeAVs;
789 landData.AnyAVSounds = AnyAVSounds; 793 landData.AnyAVSounds = AnyAVSounds;
790 landData.GroupAVSounds = GroupAVSounds; 794 landData.GroupAVSounds = GroupAVSounds;
diff --git a/OpenSim/Framework/MinHeap.cs b/OpenSim/Framework/MinHeap.cs
index 99ac25d..68f6668 100644
--- a/OpenSim/Framework/MinHeap.cs
+++ b/OpenSim/Framework/MinHeap.cs
@@ -45,8 +45,8 @@ namespace OpenSim.Framework
45 45
46 internal void Clear() 46 internal void Clear()
47 { 47 {
48 this.index = -1; 48 index = -1;
49 this.heap = null; 49 heap = null;
50 } 50 }
51 } 51 }
52 52
@@ -55,23 +55,26 @@ namespace OpenSim.Framework
55 internal T value; 55 internal T value;
56 internal Handle handle; 56 internal Handle handle;
57 57
58 internal HeapItem(T value, Handle handle) 58 internal HeapItem(T _value, Handle _handle)
59 { 59 {
60 this.value = value; 60 value = _value;
61 this.handle = handle; 61 handle = _handle;
62 } 62 }
63 63
64 internal void Clear() 64 internal void Clear()
65 { 65 {
66 if (this.handle != null) 66 if (handle != null)
67 this.handle.Clear(); 67 {
68 ClearRef(); 68 handle.Clear();
69 handle = null;
70 }
71 value = default(T);
69 } 72 }
70 73
71 internal void ClearRef() 74 internal void ClearRef()
72 { 75 {
73 this.value = default(T); 76 value = default(T);
74 this.handle = null; 77 handle = null;
75 } 78 }
76 } 79 }
77 80
@@ -81,6 +84,7 @@ namespace OpenSim.Framework
81 private int size; 84 private int size;
82 private object sync_root; 85 private object sync_root;
83 private int version; 86 private int version;
87 private int capacity;
84 88
85 private Comparison<T> comparison; 89 private Comparison<T> comparison;
86 90
@@ -90,14 +94,15 @@ namespace OpenSim.Framework
90 public MinHeap(int capacity, IComparer<T> comparer) : 94 public MinHeap(int capacity, IComparer<T> comparer) :
91 this(capacity, new Comparison<T>(comparer.Compare)) { } 95 this(capacity, new Comparison<T>(comparer.Compare)) { }
92 public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison) { } 96 public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison) { }
93 public MinHeap(int capacity, Comparison<T> comparison) 97 public MinHeap(int _capacity, Comparison<T> _comparison)
94 { 98 {
95 this.items = new HeapItem[capacity]; 99 capacity = _capacity;
96 this.comparison = comparison; 100 items = new HeapItem[capacity];
97 this.size = this.version = 0; 101 comparison = _comparison;
102 size = version = 0;
98 } 103 }
99 104
100 public int Count { get { return this.size; } } 105 public int Count { get { return size; } }
101 106
102 public bool IsReadOnly { get { return false; } } 107 public bool IsReadOnly { get { return false; } }
103 108
@@ -108,15 +113,16 @@ namespace OpenSim.Framework
108 get 113 get
109 { 114 {
110 Handle handle = ValidateThisHandle(key); 115 Handle handle = ValidateThisHandle(key);
111 return this.items[handle.index].value; 116 return items[handle.index].value;
112 } 117 }
113 118
114 set 119 set
115 { 120 {
116 Handle handle = ValidateThisHandle(key); 121 Handle handle = ValidateThisHandle(key);
117 this.items[handle.index].value = value; 122 int indx = handle.index;
118 if (!BubbleUp(handle.index)) 123 items[indx].value = value;
119 BubbleDown(handle.index); 124 if (!BubbleUp(indx))
125 BubbleDown(indx);
120 } 126 }
121 } 127 }
122 128
@@ -124,9 +130,9 @@ namespace OpenSim.Framework
124 { 130 {
125 get 131 get
126 { 132 {
127 if (this.sync_root == null) 133 if (sync_root == null)
128 Interlocked.CompareExchange<object>(ref this.sync_root, new object(), null); 134 Interlocked.CompareExchange<object>(ref sync_root, new object(), null);
129 return this.sync_root; 135 return sync_root;
130 } 136 }
131 } 137 }
132 138
@@ -152,27 +158,27 @@ namespace OpenSim.Framework
152 158
153 private void Set(HeapItem item, int index) 159 private void Set(HeapItem item, int index)
154 { 160 {
155 this.items[index] = item; 161 items[index] = item;
156 if (item.handle != null) 162 if (item.handle != null)
157 item.handle.index = index; 163 item.handle.index = index;
158 } 164 }
159 165
160 private bool BubbleUp(int index) 166 private bool BubbleUp(int index)
161 { 167 {
162 HeapItem item = this.items[index]; 168 HeapItem item = items[index];
163 int current, parent; 169 int current, parent;
164 170
165 for (current = index, parent = (current - 1) / 2; 171 for (current = index, parent = (current - 1) / 2;
166 (current > 0) && (this.comparison(this.items[parent].value, item.value)) > 0; 172 (current > 0) && (comparison(items[parent].value, item.value)) > 0;
167 current = parent, parent = (current - 1) / 2) 173 current = parent, parent = (current - 1) / 2)
168 { 174 {
169 Set(this.items[parent], current); 175 Set(items[parent], current);
170 } 176 }
171 177
172 if (current != index) 178 if (current != index)
173 { 179 {
174 Set(item, current); 180 Set(item, current);
175 ++this.version; 181 ++version;
176 return true; 182 return true;
177 } 183 }
178 return false; 184 return false;
@@ -180,24 +186,24 @@ namespace OpenSim.Framework
180 186
181 private void BubbleDown(int index) 187 private void BubbleDown(int index)
182 { 188 {
183 HeapItem item = this.items[index]; 189 HeapItem item = items[index];
184 int current, child; 190 int current, child;
185 191
186 for (current = index, child = (2 * current) + 1; 192 for (current = index, child = (2 * current) + 1;
187 current < this.size / 2; 193 current < size / 2;
188 current = child, child = (2 * current) + 1) 194 current = child, child = (2 * current) + 1)
189 { 195 {
190 if ((child < this.size - 1) && this.comparison(this.items[child].value, this.items[child + 1].value) > 0) 196 if ((child < size - 1) && comparison(items[child].value, items[child + 1].value) > 0)
191 ++child; 197 ++child;
192 if (this.comparison(this.items[child].value, item.value) >= 0) 198 if (comparison(items[child].value, item.value) >= 0)
193 break; 199 break;
194 Set(this.items[child], current); 200 Set(items[child], current);
195 } 201 }
196 202
197 if (current != index) 203 if (current != index)
198 { 204 {
199 Set(item, current); 205 Set(item, current);
200 ++this.version; 206 ++version;
201 } 207 }
202 } 208 }
203 209
@@ -206,7 +212,7 @@ namespace OpenSim.Framework
206 Handle handle = ValidateHandle(key); 212 Handle handle = ValidateHandle(key);
207 if (handle.index > -1) 213 if (handle.index > -1)
208 { 214 {
209 value = this.items[handle.index].value; 215 value = items[handle.index].value;
210 return true; 216 return true;
211 } 217 }
212 value = default(T); 218 value = default(T);
@@ -228,12 +234,12 @@ namespace OpenSim.Framework
228 234
229 public void Add(T value, IHandle ihandle) 235 public void Add(T value, IHandle ihandle)
230 { 236 {
231 if (this.size == this.items.Length) 237 if (size == items.Length)
232 { 238 {
233 int capacity = (int)((this.items.Length * 200L) / 100L); 239 int capacity = (int)((items.Length * 200L) / 100L);
234 if (capacity < (this.items.Length + DEFAULT_CAPACITY)) 240 if (capacity < (items.Length + DEFAULT_CAPACITY))
235 capacity = this.items.Length + DEFAULT_CAPACITY; 241 capacity = items.Length + DEFAULT_CAPACITY;
236 Array.Resize<HeapItem>(ref this.items, capacity); 242 Array.Resize<HeapItem>(ref items, capacity);
237 } 243 }
238 244
239 Handle handle = null; 245 Handle handle = null;
@@ -245,8 +251,8 @@ namespace OpenSim.Framework
245 251
246 HeapItem item = new MinHeap<T>.HeapItem(value, handle); 252 HeapItem item = new MinHeap<T>.HeapItem(value, handle);
247 253
248 Set(item, this.size); 254 Set(item, size);
249 BubbleUp(this.size++); 255 BubbleUp(size++);
250 } 256 }
251 257
252 public void Add(T value) 258 public void Add(T value)
@@ -256,50 +262,54 @@ namespace OpenSim.Framework
256 262
257 public T Min() 263 public T Min()
258 { 264 {
259 if (this.size == 0) 265 if (size == 0)
260 throw new InvalidOperationException("Heap is empty"); 266 throw new InvalidOperationException("Heap is empty");
261 267
262 return this.items[0].value; 268 return items[0].value;
263 } 269 }
264 270
265 public void Clear() 271 public void Clear()
266 { 272 {
267 for (int index = 0; index < this.size; ++index) 273 for (int index = 0; index < size; ++index)
268 this.items[index].Clear(); 274 items[index].Clear();
269 this.size = 0; 275 size = 0;
270 ++this.version; 276 if(items.Length > capacity)
277 items = new HeapItem[capacity];
278 ++version;
271 } 279 }
272 280
273 public void TrimExcess() 281 public void TrimExcess()
274 { 282 {
275 int length = (int)(this.items.Length * 0.9); 283 int length = (int)(items.Length * 0.9);
276 if (this.size < length) 284 if (size < length)
277 Array.Resize<HeapItem>(ref this.items, Math.Min(this.size, DEFAULT_CAPACITY)); 285 Array.Resize<HeapItem>(ref items, Math.Min(size, capacity));
278 } 286 }
279 287
280 private void RemoveAt(int index) 288 private void RemoveAt(int index)
281 { 289 {
282 if (this.size == 0) 290 if (size == 0)
283 throw new InvalidOperationException("Heap is empty"); 291 throw new InvalidOperationException("Heap is empty");
284 if (index >= this.size) 292 if (index >= size)
285 throw new ArgumentOutOfRangeException("index"); 293 throw new ArgumentOutOfRangeException("index");
286 294
287 this.items[index].Clear(); 295 items[index].Clear();
288 if (--this.size > 0 && index != this.size) 296 if (--size > 0 && index != size)
289 { 297 {
290 Set(this.items[this.size], index); 298 Set(items[size], index);
291 this.items[this.size].ClearRef(); 299 items[size].ClearRef();
292 if (!BubbleUp(index)) 300 if (!BubbleUp(index))
293 BubbleDown(index); 301 BubbleDown(index);
294 } 302 }
303 if(size == 0 && items.Length > 4 * capacity)
304 items = new HeapItem[capacity];
295 } 305 }
296 306
297 public T RemoveMin() 307 public T RemoveMin()
298 { 308 {
299 if (this.size == 0) 309 if (size == 0)
300 throw new InvalidOperationException("Heap is empty"); 310 throw new InvalidOperationException("Heap is empty");
301 311
302 HeapItem item = this.items[0]; 312 HeapItem item = items[0];
303 RemoveAt(0); 313 RemoveAt(0);
304 return item.value; 314 return item.value;
305 } 315 }
@@ -307,7 +317,7 @@ namespace OpenSim.Framework
307 public T Remove(IHandle ihandle) 317 public T Remove(IHandle ihandle)
308 { 318 {
309 Handle handle = ValidateThisHandle(ihandle); 319 Handle handle = ValidateThisHandle(ihandle);
310 HeapItem item = this.items[handle.index]; 320 HeapItem item = items[handle.index];
311 RemoveAt(handle.index); 321 RemoveAt(handle.index);
312 return item.value; 322 return item.value;
313 } 323 }
@@ -317,9 +327,9 @@ namespace OpenSim.Framework
317 EqualityComparer<T> comparer = EqualityComparer<T>.Default; 327 EqualityComparer<T> comparer = EqualityComparer<T>.Default;
318 int index; 328 int index;
319 329
320 for (index = 0; index < this.size; ++index) 330 for (index = 0; index < size; ++index)
321 { 331 {
322 if (comparer.Equals(this.items[index].value, value)) 332 if (comparer.Equals(items[index].value, value))
323 return index; 333 return index;
324 } 334 }
325 return -1; 335 return -1;
@@ -356,8 +366,8 @@ namespace OpenSim.Framework
356 if ((length - index) < this.size) 366 if ((length - index) < this.size)
357 throw new ArgumentException("Not enough space available in array starting at index"); 367 throw new ArgumentException("Not enough space available in array starting at index");
358 368
359 for (int i = 0; i < this.size; ++i) 369 for (int i = 0; i < size; ++i)
360 array[index + i] = this.items[i].value; 370 array[index + i] = items[i].value;
361 } 371 }
362 372
363 public void CopyTo(Array array, int index) 373 public void CopyTo(Array array, int index)
@@ -372,13 +382,13 @@ namespace OpenSim.Framework
372 int length = array.Length; 382 int length = array.Length;
373 if ((index < 0) || (index > length)) 383 if ((index < 0) || (index > length))
374 throw new ArgumentOutOfRangeException("index"); 384 throw new ArgumentOutOfRangeException("index");
375 if ((length - index) < this.size) 385 if ((length - index) < size)
376 throw new ArgumentException("Not enough space available in array starting at index"); 386 throw new ArgumentException("Not enough space available in array starting at index");
377 387
378 try 388 try
379 { 389 {
380 for (int i = 0; i < this.size; ++i) 390 for (int i = 0; i < size; ++i)
381 array.SetValue(this.items[i].value, index + i); 391 array.SetValue(items[i].value, index + i);
382 } 392 }
383 catch (ArrayTypeMismatchException) 393 catch (ArrayTypeMismatchException)
384 { 394 {
@@ -388,13 +398,13 @@ namespace OpenSim.Framework
388 398
389 public IEnumerator<T> GetEnumerator() 399 public IEnumerator<T> GetEnumerator()
390 { 400 {
391 int version = this.version; 401 int cversion = version;
392 402
393 for (int index = 0; index < this.size; ++index) 403 for (int index = 0; index < size; ++index)
394 { 404 {
395 if (version != this.version) 405 if (cversion != version)
396 throw new InvalidOperationException("Heap was modified while enumerating"); 406 throw new InvalidOperationException("Heap was modified while enumerating");
397 yield return this.items[index].value; 407 yield return items[index].value;
398 } 408 }
399 } 409 }
400 410
diff --git a/OpenSim/Framework/Monitoring/JobEngine.cs b/OpenSim/Framework/Monitoring/JobEngine.cs
index 0a39e4b..6c388b3 100644
--- a/OpenSim/Framework/Monitoring/JobEngine.cs
+++ b/OpenSim/Framework/Monitoring/JobEngine.cs
@@ -57,7 +57,8 @@ namespace OpenSim.Framework.Monitoring
57 /// <remarks> 57 /// <remarks>
58 /// Will be null if no job is currently running. 58 /// Will be null if no job is currently running.
59 /// </remarks> 59 /// </remarks>
60 public Job CurrentJob { get; private set; } 60 private Job m_currentJob;
61 public Job CurrentJob { get { return m_currentJob;} }
61 62
62 /// <summary> 63 /// <summary>
63 /// Number of jobs waiting to be processed. 64 /// Number of jobs waiting to be processed.
@@ -78,20 +79,19 @@ namespace OpenSim.Framework.Monitoring
78 /// </remarks> 79 /// </remarks>
79 private bool m_warnOverMaxQueue = true; 80 private bool m_warnOverMaxQueue = true;
80 81
81 private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000); 82 private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(5000);
82 83
83 private CancellationTokenSource m_cancelSource; 84 private CancellationTokenSource m_cancelSource;
84 85
85 /// <summary> 86 private int m_timeout = -1;
86 /// Used to signal that we are ready to complete stop. 87
87 /// </summary> 88 private bool m_threadRunnig = false;
88 private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
89 89
90 public JobEngine(string name, string loggingName) 90 public JobEngine(string name, string loggingName, int timeout = -1)
91 { 91 {
92 Name = name; 92 Name = name;
93 LoggingName = loggingName; 93 LoggingName = loggingName;
94 94 m_timeout = timeout;
95 RequestProcessTimeoutOnStop = 5000; 95 RequestProcessTimeoutOnStop = 5000;
96 } 96 }
97 97
@@ -104,18 +104,9 @@ namespace OpenSim.Framework.Monitoring
104 104
105 IsRunning = true; 105 IsRunning = true;
106 106
107 m_finishedProcessingAfterStop.Reset();
108
109 m_cancelSource = new CancellationTokenSource(); 107 m_cancelSource = new CancellationTokenSource();
110 108 WorkManager.RunInThreadPool(ProcessRequests, null, Name, false);
111 WorkManager.StartThread( 109 m_threadRunnig = true;
112 ProcessRequests,
113 Name,
114 ThreadPriority.Normal,
115 false,
116 true,
117 null,
118 int.MaxValue);
119 } 110 }
120 } 111 }
121 112
@@ -131,17 +122,16 @@ namespace OpenSim.Framework.Monitoring
131 m_log.DebugFormat("[JobEngine] Stopping {0}", Name); 122 m_log.DebugFormat("[JobEngine] Stopping {0}", Name);
132 123
133 IsRunning = false; 124 IsRunning = false;
134 125 if(m_threadRunnig)
135 m_finishedProcessingAfterStop.Reset(); 126 {
136 if(m_jobQueue.Count <= 0)
137 m_cancelSource.Cancel(); 127 m_cancelSource.Cancel();
138 128 m_threadRunnig = false;
139 if(m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop)) 129 }
140 m_finishedProcessingAfterStop.Close();
141 } 130 }
142 finally 131 finally
143 { 132 {
144 m_cancelSource.Dispose(); 133 if(m_cancelSource != null)
134 m_cancelSource.Dispose();
145 } 135 }
146 } 136 }
147 } 137 }
@@ -200,6 +190,18 @@ namespace OpenSim.Framework.Monitoring
200 /// </param> 190 /// </param>
201 public bool QueueJob(Job job) 191 public bool QueueJob(Job job)
202 { 192 {
193 lock(JobLock)
194 {
195 if(!IsRunning)
196 return false;
197
198 if(!m_threadRunnig)
199 {
200 WorkManager.RunInThreadPool(ProcessRequests, null, Name, false);
201 m_threadRunnig = true;
202 }
203 }
204
203 if (m_jobQueue.Count < m_jobQueue.BoundedCapacity) 205 if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
204 { 206 {
205 m_jobQueue.Add(job); 207 m_jobQueue.Add(job);
@@ -219,59 +221,53 @@ namespace OpenSim.Framework.Monitoring
219 221
220 m_warnOverMaxQueue = false; 222 m_warnOverMaxQueue = false;
221 } 223 }
222
223 return false; 224 return false;
224 } 225 }
225 } 226 }
226 227
227 private void ProcessRequests() 228 private void ProcessRequests(Object o)
228 { 229 {
229 while(IsRunning || m_jobQueue.Count > 0) 230 while(IsRunning)
230 { 231 {
231 try 232 try
232 { 233 {
233 CurrentJob = m_jobQueue.Take(m_cancelSource.Token); 234 if(!m_jobQueue.TryTake(out m_currentJob, m_timeout, m_cancelSource.Token))
234 }
235 catch(ObjectDisposedException e)
236 {
237 // If we see this whilst not running then it may be due to a race where this thread checks
238 // IsRunning after the stopping thread sets it to false and disposes of the cancellation source.
239 if(IsRunning)
240 throw e;
241 else
242 { 235 {
243 m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue", 236 lock(JobLock)
244 Name,m_jobQueue.Count); 237 m_threadRunnig = false;
245 break; 238 break;
246 } 239 }
247 } 240 }
241 catch(ObjectDisposedException)
242 {
243 m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
244 Name,m_jobQueue.Count);
245 break;
246 }
248 catch(OperationCanceledException) 247 catch(OperationCanceledException)
249 { 248 {
250 break; 249 break;
251 } 250 }
252 251
253 if(LogLevel >= 1) 252 if(LogLevel >= 1)
254 m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,CurrentJob.Name); 253 m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,m_currentJob.Name);
255 254
256 try 255 try
257 { 256 {
258 CurrentJob.Action(); 257 m_currentJob.Action();
259 } 258 }
260 catch(Exception e) 259 catch(Exception e)
261 { 260 {
262 m_log.Error( 261 m_log.Error(
263 string.Format( 262 string.Format(
264 "[{0}]: Job {1} failed, continuing. Exception ",LoggingName,CurrentJob.Name),e); 263 "[{0}]: Job {1} failed, continuing. Exception ",LoggingName,m_currentJob.Name),e);
265 } 264 }
266 265
267 if(LogLevel >= 1) 266 if(LogLevel >= 1)
268 m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,CurrentJob.Name); 267 m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,m_currentJob.Name);
269 268
270 CurrentJob = null; 269 m_currentJob = null;
271 } 270 }
272
273 Watchdog.RemoveThread(false);
274 m_finishedProcessingAfterStop.Set();
275 } 271 }
276 272
277 public class Job 273 public class Job
diff --git a/OpenSim/Framework/Monitoring/ServerStatsCollector.cs b/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
index 3391240..a26a6e0 100644
--- a/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
+++ b/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
@@ -88,7 +88,7 @@ namespace OpenSim.Framework.Monitoring
88 IConfig cfg = source.Configs["Monitoring"]; 88 IConfig cfg = source.Configs["Monitoring"];
89 89
90 if (cfg != null) 90 if (cfg != null)
91 Enabled = cfg.GetBoolean("ServerStatsEnabled", true); 91 Enabled = cfg.GetBoolean("ServerStatsEnabled", false);
92 92
93 if (Enabled) 93 if (Enabled)
94 { 94 {
@@ -98,12 +98,18 @@ namespace OpenSim.Framework.Monitoring
98 98
99 public void Start() 99 public void Start()
100 { 100 {
101 if(!Enabled)
102 return;
103
101 if (RegisteredStats.Count == 0) 104 if (RegisteredStats.Count == 0)
102 RegisterServerStats(); 105 RegisterServerStats();
103 } 106 }
104 107
105 public void Close() 108 public void Close()
106 { 109 {
110 if(!Enabled)
111 return;
112
107 if (RegisteredStats.Count > 0) 113 if (RegisteredStats.Count > 0)
108 { 114 {
109 foreach (Stat stat in RegisteredStats.Values) 115 foreach (Stat stat in RegisteredStats.Values)
diff --git a/OpenSim/Framework/Monitoring/Stats/Stat.cs b/OpenSim/Framework/Monitoring/Stats/Stat.cs
index 2402acd..4b1a229 100644
--- a/OpenSim/Framework/Monitoring/Stats/Stat.cs
+++ b/OpenSim/Framework/Monitoring/Stats/Stat.cs
@@ -242,11 +242,7 @@ namespace OpenSim.Framework.Monitoring
242 public virtual OSDMap ToBriefOSDMap() 242 public virtual OSDMap ToBriefOSDMap()
243 { 243 {
244 OSDMap ret = new OSDMap(); 244 OSDMap ret = new OSDMap();
245
246 ret.Add("Value", OSD.FromReal(Value)); 245 ret.Add("Value", OSD.FromReal(Value));
247
248 double lastChangeOverTime, averageChangeOverTime;
249
250 return ret; 246 return ret;
251 } 247 }
252 248
diff --git a/OpenSim/Framework/Monitoring/Watchdog.cs b/OpenSim/Framework/Monitoring/Watchdog.cs
index 9cc61ee..ad21d93 100644
--- a/OpenSim/Framework/Monitoring/Watchdog.cs
+++ b/OpenSim/Framework/Monitoring/Watchdog.cs
@@ -180,6 +180,33 @@ namespace OpenSim.Framework.Monitoring
180 m_watchdogTimer.Elapsed += WatchdogTimerElapsed; 180 m_watchdogTimer.Elapsed += WatchdogTimerElapsed;
181 } 181 }
182 182
183 public static void Stop()
184 {
185 if(m_threads == null)
186 return;
187
188 lock(m_threads)
189 {
190 m_enabled = false;
191 if(m_watchdogTimer != null)
192 {
193 m_watchdogTimer.Dispose();
194 m_watchdogTimer = null;
195 }
196
197 foreach(ThreadWatchdogInfo twi in m_threads.Values)
198 {
199 Thread t = twi.Thread;
200 // m_log.DebugFormat(
201 // "[WATCHDOG]: Stop: Removing thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId);
202
203 if(t.IsAlive)
204 t.Abort();
205 }
206 m_threads.Clear();
207 }
208 }
209
183 /// <summary> 210 /// <summary>
184 /// Add a thread to the watchdog tracker. 211 /// Add a thread to the watchdog tracker.
185 /// </summary> 212 /// </summary>
@@ -230,14 +257,12 @@ namespace OpenSim.Framework.Monitoring
230 257
231 twi.Cleanup(); 258 twi.Cleanup();
232 m_threads.Remove(threadID); 259 m_threads.Remove(threadID);
233
234 return true; 260 return true;
235 } 261 }
236 else 262 else
237 { 263 {
238 m_log.WarnFormat( 264 m_log.WarnFormat(
239 "[WATCHDOG]: Requested to remove thread with ID {0} but this is not being monitored", threadID); 265 "[WATCHDOG]: Requested to remove thread with ID {0} but this is not being monitored", threadID);
240
241 return false; 266 return false;
242 } 267 }
243 } 268 }
@@ -317,6 +342,8 @@ namespace OpenSim.Framework.Monitoring
317 /// <param name="e"></param> 342 /// <param name="e"></param>
318 private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) 343 private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
319 { 344 {
345 if(!m_enabled)
346 return;
320 int now = Environment.TickCount & Int32.MaxValue; 347 int now = Environment.TickCount & Int32.MaxValue;
321 int msElapsed = now - LastWatchdogThreadTick; 348 int msElapsed = now - LastWatchdogThreadTick;
322 349
@@ -334,21 +361,26 @@ namespace OpenSim.Framework.Monitoring
334 List<ThreadWatchdogInfo> callbackInfos = null; 361 List<ThreadWatchdogInfo> callbackInfos = null;
335 List<ThreadWatchdogInfo> threadsToRemove = null; 362 List<ThreadWatchdogInfo> threadsToRemove = null;
336 363
364 const ThreadState thgone = ThreadState.Stopped;
365
337 lock (m_threads) 366 lock (m_threads)
338 { 367 {
339 foreach(ThreadWatchdogInfo threadInfo in m_threads.Values) 368 foreach(ThreadWatchdogInfo threadInfo in m_threads.Values)
340 { 369 {
341 if(threadInfo.Thread.ThreadState == ThreadState.Stopped) 370 if(!m_enabled)
371 return;
372 if((threadInfo.Thread.ThreadState & thgone) != 0)
342 { 373 {
343 if(threadsToRemove == null) 374 if(threadsToRemove == null)
344 threadsToRemove = new List<ThreadWatchdogInfo>(); 375 threadsToRemove = new List<ThreadWatchdogInfo>();
345 376
346 threadsToRemove.Add(threadInfo); 377 threadsToRemove.Add(threadInfo);
347 378/*
348 if(callbackInfos == null) 379 if(callbackInfos == null)
349 callbackInfos = new List<ThreadWatchdogInfo>(); 380 callbackInfos = new List<ThreadWatchdogInfo>();
350 381
351 callbackInfos.Add(threadInfo); 382 callbackInfos.Add(threadInfo);
383*/
352 } 384 }
353 else if(!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout) 385 else if(!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout)
354 { 386 {
diff --git a/OpenSim/Framework/Monitoring/WorkManager.cs b/OpenSim/Framework/Monitoring/WorkManager.cs
index 43130f9..5d9b185 100644
--- a/OpenSim/Framework/Monitoring/WorkManager.cs
+++ b/OpenSim/Framework/Monitoring/WorkManager.cs
@@ -57,7 +57,7 @@ namespace OpenSim.Framework.Monitoring
57 57
58 static WorkManager() 58 static WorkManager()
59 { 59 {
60 JobEngine = new JobEngine("Non-blocking non-critical job engine", "JOB ENGINE"); 60 JobEngine = new JobEngine("Non-blocking non-critical job engine", "JOB ENGINE", 30000);
61 61
62 StatsManager.RegisterStat( 62 StatsManager.RegisterStat(
63 new Stat( 63 new Stat(
@@ -82,6 +82,12 @@ namespace OpenSim.Framework.Monitoring
82 HandleControlCommand); 82 HandleControlCommand);
83 } 83 }
84 84
85 public static void Stop()
86 {
87 JobEngine.Stop();
88 Watchdog.Stop();
89 }
90
85 /// <summary> 91 /// <summary>
86 /// Start a new long-lived thread. 92 /// Start a new long-lived thread.
87 /// </summary> 93 /// </summary>
@@ -131,7 +137,6 @@ namespace OpenSim.Framework.Monitoring
131 137
132 thread.Start(); 138 thread.Start();
133 139
134
135 return thread; 140 return thread;
136 } 141 }
137 142
@@ -177,9 +182,9 @@ namespace OpenSim.Framework.Monitoring
177 /// <param name="callback"></param> 182 /// <param name="callback"></param>
178 /// <param name="obj"></param> 183 /// <param name="obj"></param>
179 /// <param name="name">The name of the job. This is used in monitoring and debugging.</param> 184 /// <param name="name">The name of the job. This is used in monitoring and debugging.</param>
180 public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name) 185 public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name, bool timeout = true)
181 { 186 {
182 Util.FireAndForget(callback, obj, name); 187 Util.FireAndForget(callback, obj, name, timeout);
183 } 188 }
184 189
185 /// <summary> 190 /// <summary>
@@ -226,10 +231,8 @@ namespace OpenSim.Framework.Monitoring
226 JobEngine.QueueJob(name, () => callback(obj)); 231 JobEngine.QueueJob(name, () => callback(obj));
227 else if (canRunInThisThread) 232 else if (canRunInThisThread)
228 callback(obj); 233 callback(obj);
229 else if (mustNotTimeout)
230 RunInThread(callback, obj, name, log);
231 else 234 else
232 Util.FireAndForget(callback, obj, name); 235 Util.FireAndForget(callback, obj, name, !mustNotTimeout);
233 } 236 }
234 237
235 private static void HandleControlCommand(string module, string[] args) 238 private static void HandleControlCommand(string module, string[] args)
diff --git a/OpenSim/Framework/GcNotify.cs b/OpenSim/Framework/MuteData.cs
index 14a22a6..7c946d6 100644
--- a/OpenSim/Framework/GcNotify.cs
+++ b/OpenSim/Framework/MuteData.cs
@@ -25,38 +25,17 @@
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System; 28using OpenMetaverse;
29using System.Reflection;
30using log4net;
31 29
32public class GcNotify 30namespace OpenSim.Framework
33{ 31{
34 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 32 public class MuteData
35
36 public static bool Enabled
37 {
38 get { return s_initialized; }
39 set
40 {
41 if (!s_initialized && value)
42 new GcNotify();
43
44 s_initialized = value;
45 }
46 }
47
48 private static bool s_initialized = false;
49
50 private GcNotify() {}
51
52 ~GcNotify()
53 { 33 {
54 if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) 34 public UUID AgentID;
55 { 35 public UUID MuteID;
56 m_log.DebugFormat("[GC NOTIFY]: Garbage collection triggered."); 36 public string MuteName;
57 37 public int MuteType;
58 if (Enabled) 38 public int MuteFlags;
59 new GcNotify(); 39 public int Stamp;
60 }
61 } 40 }
62} \ No newline at end of file 41}
diff --git a/OpenSim/Framework/NetworkServersInfo.cs b/OpenSim/Framework/NetworkServersInfo.cs
index dfe9695..d79eb0d 100644
--- a/OpenSim/Framework/NetworkServersInfo.cs
+++ b/OpenSim/Framework/NetworkServersInfo.cs
@@ -37,6 +37,8 @@ namespace OpenSim.Framework
37 public bool isSandbox; 37 public bool isSandbox;
38 public bool HttpUsesSSL = false; 38 public bool HttpUsesSSL = false;
39 public string HttpSSLCN = ""; 39 public string HttpSSLCN = "";
40 public string HttpSSLCertPath = "";
41 public string HttpSSLCNCertPass = "";
40 public uint httpSSLPort = 9001; 42 public uint httpSSLPort = 9001;
41 43
42 // "Out of band" managemnt https 44 // "Out of band" managemnt https
@@ -62,6 +64,8 @@ namespace OpenSim.Framework
62 (uint)config.Configs["Network"].GetInt("http_listener_sslport", ((int)ConfigSettings.DefaultRegionHttpPort+1)); 64 (uint)config.Configs["Network"].GetInt("http_listener_sslport", ((int)ConfigSettings.DefaultRegionHttpPort+1));
63 HttpUsesSSL = config.Configs["Network"].GetBoolean("http_listener_ssl", false); 65 HttpUsesSSL = config.Configs["Network"].GetBoolean("http_listener_ssl", false);
64 HttpSSLCN = config.Configs["Network"].GetString("http_listener_cn", "localhost"); 66 HttpSSLCN = config.Configs["Network"].GetString("http_listener_cn", "localhost");
67 HttpSSLCertPath = config.Configs["Network"].GetString("http_listener_cert_path", HttpSSLCertPath);
68 HttpSSLCNCertPass = config.Configs["Network"].GetString("http_listener_cert_pass", HttpSSLCNCertPass);
65 69
66 // "Out of band management https" 70 // "Out of band management https"
67 ssl_listener = config.Configs["Network"].GetBoolean("https_listener",false); 71 ssl_listener = config.Configs["Network"].GetBoolean("https_listener",false);
diff --git a/OpenSim/Framework/PermissionsUtil.cs b/OpenSim/Framework/PermissionsUtil.cs
index 3dce04d..e50d4df 100644
--- a/OpenSim/Framework/PermissionsUtil.cs
+++ b/OpenSim/Framework/PermissionsUtil.cs
@@ -60,9 +60,57 @@ namespace OpenSim.Framework
60 str += "C"; 60 str += "C";
61 if ((perms & (int)PermissionMask.Transfer) != 0) 61 if ((perms & (int)PermissionMask.Transfer) != 0)
62 str += "T"; 62 str += "T";
63 if ((perms & (int)PermissionMask.Export) != 0)
64 str += "X";
63 if (str == "") 65 if (str == "")
64 str = "."; 66 str = ".";
65 return str; 67 return str;
66 } 68 }
69
70 public static void ApplyFoldedPermissions(uint foldedSourcePerms, ref uint targetPerms)
71 {
72 uint folded = foldedSourcePerms & (uint)PermissionMask.FoldedMask;
73 if(folded == 0 || folded == (uint)PermissionMask.FoldedMask) // invalid we need to ignore, or nothing to do
74 return;
75
76 folded <<= (int)PermissionMask.FoldingShift;
77 folded |= ~(uint)PermissionMask.UnfoldedMask;
78
79 uint tmp = targetPerms;
80 tmp &= folded;
81 targetPerms = tmp;
82 }
83
84 // do not touch MOD
85 public static void ApplyNoModFoldedPermissions(uint foldedSourcePerms, ref uint target)
86 {
87 uint folded = foldedSourcePerms & (uint)PermissionMask.FoldedMask;
88 if(folded == 0 || folded == (uint)PermissionMask.FoldedMask) // invalid we need to ignore, or nothing to do
89 return;
90
91 folded <<= (int)PermissionMask.FoldingShift;
92 folded |= (~(uint)PermissionMask.UnfoldedMask | (uint)PermissionMask.Modify);
93
94 uint tmp = target;
95 tmp &= folded;
96 target = tmp;
97 }
98
99 public static uint FixAndFoldPermissions(uint perms)
100 {
101 uint tmp = perms;
102
103 // C & T rule
104 if((tmp & (uint)(PermissionMask.Copy | PermissionMask.Transfer)) == 0)
105 tmp |= (uint)PermissionMask.Transfer;
106
107 // unlock
108 tmp |= (uint)PermissionMask.Move;
109
110 tmp &= ~(uint)PermissionMask.FoldedMask;
111 tmp |= ((tmp >> (int)PermissionMask.FoldingShift) & (uint)PermissionMask.FoldedMask);
112
113 return tmp;
114 }
67 } 115 }
68} 116}
diff --git a/OpenSim/Framework/PhysicsInertia.cs b/OpenSim/Framework/PhysicsInertia.cs
new file mode 100644
index 0000000..5aae6d5
--- /dev/null
+++ b/OpenSim/Framework/PhysicsInertia.cs
@@ -0,0 +1,261 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using System.Text;
32using System.IO;
33using System.Xml;
34
35namespace OpenSim.Framework
36{
37 public class PhysicsInertiaData
38 {
39 public float TotalMass; // the total mass of a linkset
40 public Vector3 CenterOfMass; // the center of mass position relative to root part position
41 public Vector3 Inertia; // (Ixx, Iyy, Izz) moment of inertia relative to center of mass and principal axis in local coords
42 public Vector4 InertiaRotation; // if principal axis don't match local axis, the principal axis rotation
43 // or the upper triangle of the inertia tensor
44 // Ixy (= Iyx), Ixz (= Izx), Iyz (= Izy))
45
46 public PhysicsInertiaData()
47 {
48 }
49
50 public PhysicsInertiaData(PhysicsInertiaData source)
51 {
52 TotalMass = source.TotalMass;
53 CenterOfMass = source.CenterOfMass;
54 Inertia = source.Inertia;
55 InertiaRotation = source.InertiaRotation;
56 }
57
58 private XmlTextWriter writer;
59
60 private void XWint(string name, int i)
61 {
62 writer.WriteElementString(name, i.ToString());
63 }
64
65 private void XWfloat(string name, float f)
66 {
67 writer.WriteElementString(name, f.ToString(Culture.FormatProvider));
68 }
69
70 private void XWVector(string name, Vector3 vec)
71 {
72 writer.WriteStartElement(name);
73 writer.WriteElementString("X", vec.X.ToString(Culture.FormatProvider));
74 writer.WriteElementString("Y", vec.Y.ToString(Culture.FormatProvider));
75 writer.WriteElementString("Z", vec.Z.ToString(Culture.FormatProvider));
76 writer.WriteEndElement();
77 }
78
79 private void XWVector4(string name, Vector4 quat)
80 {
81 writer.WriteStartElement(name);
82 writer.WriteElementString("X", quat.X.ToString(Culture.FormatProvider));
83 writer.WriteElementString("Y", quat.Y.ToString(Culture.FormatProvider));
84 writer.WriteElementString("Z", quat.Z.ToString(Culture.FormatProvider));
85 writer.WriteElementString("W", quat.W.ToString(Culture.FormatProvider));
86 writer.WriteEndElement();
87 }
88
89 public void ToXml2(XmlTextWriter twriter)
90 {
91 writer = twriter;
92 writer.WriteStartElement("PhysicsInertia");
93
94 XWfloat("MASS", TotalMass);
95 XWVector("CM", CenterOfMass);
96 XWVector("INERTIA", Inertia);
97 XWVector4("IROT", InertiaRotation);
98
99 writer.WriteEndElement();
100 writer = null;
101 }
102
103 XmlReader reader;
104
105 private int XRint()
106 {
107 return reader.ReadElementContentAsInt();
108 }
109
110 private float XRfloat()
111 {
112 return reader.ReadElementContentAsFloat();
113 }
114
115 public Vector3 XRvector()
116 {
117 Vector3 vec;
118 reader.ReadStartElement();
119 vec.X = reader.ReadElementContentAsFloat();
120 vec.Y = reader.ReadElementContentAsFloat();
121 vec.Z = reader.ReadElementContentAsFloat();
122 reader.ReadEndElement();
123 return vec;
124 }
125
126 public Vector4 XRVector4()
127 {
128 Vector4 q;
129 reader.ReadStartElement();
130 q.X = reader.ReadElementContentAsFloat();
131 q.Y = reader.ReadElementContentAsFloat();
132 q.Z = reader.ReadElementContentAsFloat();
133 q.W = reader.ReadElementContentAsFloat();
134 reader.ReadEndElement();
135 return q;
136 }
137
138 public static bool EReadProcessors(
139 Dictionary<string, Action> processors,
140 XmlReader xtr)
141 {
142 bool errors = false;
143
144 string nodeName = string.Empty;
145 while (xtr.NodeType != XmlNodeType.EndElement)
146 {
147 nodeName = xtr.Name;
148
149 Action p = null;
150 if (processors.TryGetValue(xtr.Name, out p))
151 {
152 try
153 {
154 p();
155 }
156 catch
157 {
158 errors = true;
159 if (xtr.NodeType == XmlNodeType.EndElement)
160 xtr.Read();
161 }
162 }
163 else
164 {
165 xtr.ReadOuterXml(); // ignore
166 }
167 }
168
169 return errors;
170 }
171
172 public string ToXml2()
173 {
174 using (StringWriter sw = new StringWriter())
175 {
176 using (XmlTextWriter xwriter = new XmlTextWriter(sw))
177 {
178 ToXml2(xwriter);
179 }
180
181 return sw.ToString();
182 }
183 }
184
185 public static PhysicsInertiaData FromXml2(string text)
186 {
187 if (text == String.Empty)
188 return null;
189
190 bool error;
191 PhysicsInertiaData v;
192 UTF8Encoding enc = new UTF8Encoding();
193 using(MemoryStream ms = new MemoryStream(enc.GetBytes(text)))
194 using(XmlTextReader xreader = new XmlTextReader(ms))
195 {
196 v = new PhysicsInertiaData();
197 v.FromXml2(xreader, out error);
198 }
199
200 if (error)
201 return null;
202
203 return v;
204 }
205
206 public static PhysicsInertiaData FromXml2(XmlReader reader)
207 {
208 PhysicsInertiaData data = new PhysicsInertiaData();
209
210 bool errors = false;
211
212 data.FromXml2(reader, out errors);
213 if (errors)
214 return null;
215
216 return data;
217 }
218
219 private void FromXml2(XmlReader _reader, out bool errors)
220 {
221 errors = false;
222 reader = _reader;
223
224 Dictionary<string, Action> m_XmlProcessors = new Dictionary<string, Action>();
225
226 m_XmlProcessors.Add("MASS", ProcessXR_Mass);
227 m_XmlProcessors.Add("CM", ProcessXR_CM);
228 m_XmlProcessors.Add("INERTIA", ProcessXR_Inertia);
229 m_XmlProcessors.Add("IROT", ProcessXR_InertiaRotation);
230
231 reader.ReadStartElement("PhysicsInertia", String.Empty);
232
233 errors = EReadProcessors(
234 m_XmlProcessors,
235 reader);
236
237 reader.ReadEndElement();
238 reader = null;
239 }
240
241 private void ProcessXR_Mass()
242 {
243 TotalMass = XRfloat();
244 }
245
246 private void ProcessXR_CM()
247 {
248 CenterOfMass = XRvector();
249 }
250
251 private void ProcessXR_Inertia()
252 {
253 Inertia = XRvector();
254 }
255
256 private void ProcessXR_InertiaRotation()
257 {
258 InertiaRotation = XRVector4();
259 }
260 }
261}
diff --git a/OpenSim/Framework/PrimitiveBaseShape.cs b/OpenSim/Framework/PrimitiveBaseShape.cs
index 29985d2..5056c04 100644
--- a/OpenSim/Framework/PrimitiveBaseShape.cs
+++ b/OpenSim/Framework/PrimitiveBaseShape.cs
@@ -328,6 +328,72 @@ namespace OpenSim.Framework
328 return shape; 328 return shape;
329 } 329 }
330 330
331 public static PrimitiveBaseShape CreateMesh(int numberOfFaces, UUID meshAssetID)
332 {
333 PrimitiveBaseShape shape = new PrimitiveBaseShape();
334
335 shape._pathScaleX = 100;
336 shape._pathScaleY = 100;
337
338 if(numberOfFaces <= 0) // oops ?
339 numberOfFaces = 1;
340
341 switch(numberOfFaces)
342 {
343 case 1: // torus
344 shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
345 shape.PathCurve = (byte)Extrusion.Curve1;
346 shape._pathScaleY = 150;
347 break;
348
349 case 2: // torus with hollow (a sl viewer whould see 4 faces on a hollow sphere)
350 shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
351 shape.PathCurve = (byte)Extrusion.Curve1;
352 shape.ProfileHollow = 27500;
353 shape._pathScaleY = 150;
354 break;
355
356 case 3: // cylinder
357 shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
358 shape.PathCurve = (byte)Extrusion.Straight;
359 break;
360
361 case 4: // cylinder with hollow
362 shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
363 shape.PathCurve = (byte)Extrusion.Straight;
364 shape.ProfileHollow = 27500;
365 break;
366
367 case 5: // prism
368 shape.ProfileCurve = (byte)ProfileShape.EquilateralTriangle | (byte)HollowShape.Triangle;
369 shape.PathCurve = (byte)Extrusion.Straight;
370 break;
371
372 case 6: // box
373 shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
374 shape.PathCurve = (byte)Extrusion.Straight;
375 break;
376
377 case 7: // box with hollow
378 shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
379 shape.PathCurve = (byte)Extrusion.Straight;
380 shape.ProfileHollow = 27500;
381 break;
382
383 default: // 8 faces box with cut
384 shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
385 shape.PathCurve = (byte)Extrusion.Straight;
386 shape.ProfileBegin = 9375;
387 break;
388 }
389
390 shape.SculptEntry = true;
391 shape.SculptType = (byte)OpenMetaverse.SculptType.Mesh;
392 shape.SculptTexture = meshAssetID;
393
394 return shape;
395 }
396
331 public void SetScale(float side) 397 public void SetScale(float side)
332 { 398 {
333 _scale = new Vector3(side, side, side); 399 _scale = new Vector3(side, side, side);
@@ -1516,35 +1582,48 @@ namespace OpenSim.Framework
1516 { 1582 {
1517 MediaList ml = new MediaList(); 1583 MediaList ml = new MediaList();
1518 ml.ReadXml(rawXml); 1584 ml.ReadXml(rawXml);
1585 if(ml.Count == 0)
1586 return null;
1519 return ml; 1587 return ml;
1520 } 1588 }
1521 1589
1522 public void ReadXml(string rawXml) 1590 public void ReadXml(string rawXml)
1523 { 1591 {
1524 using (StringReader sr = new StringReader(rawXml)) 1592 try
1525 { 1593 {
1526 using (XmlTextReader xtr = new XmlTextReader(sr)) 1594 using (StringReader sr = new StringReader(rawXml))
1527 { 1595 {
1528 xtr.MoveToContent(); 1596 using (XmlTextReader xtr = new XmlTextReader(sr))
1597 {
1598 xtr.MoveToContent();
1529 1599
1530 string type = xtr.GetAttribute("type"); 1600 string type = xtr.GetAttribute("type");
1531 //m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type); 1601 //m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
1532 1602
1533 if (type != MEDIA_TEXTURE_TYPE) 1603 if (type != MEDIA_TEXTURE_TYPE)
1534 return; 1604 return;
1535 1605
1536 xtr.ReadStartElement("OSMedia"); 1606 xtr.ReadStartElement("OSMedia");
1607 OSD osdp = OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
1608 if(osdp == null || !(osdp is OSDArray))
1609 return;
1537 1610
1538 OSDArray osdMeArray = (OSDArray)OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml()); 1611 OSDArray osdMeArray = osdp as OSDArray;
1539 foreach (OSD osdMe in osdMeArray) 1612 if(osdMeArray.Count == 0)
1540 { 1613 return;
1541 MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
1542 Add(me);
1543 }
1544 1614
1545 xtr.ReadEndElement(); 1615 foreach (OSD osdMe in osdMeArray)
1616 {
1617 MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
1618 Add(me);
1619 }
1620 }
1546 } 1621 }
1547 } 1622 }
1623 catch
1624 {
1625 m_log.Debug("PrimitiveBaseShape] error decoding MOAP xml" );
1626 }
1548 } 1627 }
1549 1628
1550 public void ReadXml(XmlReader reader) 1629 public void ReadXml(XmlReader reader)
diff --git a/OpenSim/Framework/PriorityQueue.cs b/OpenSim/Framework/PriorityQueue.cs
index 5b9185e..22ffcdc 100644
--- a/OpenSim/Framework/PriorityQueue.cs
+++ b/OpenSim/Framework/PriorityQueue.cs
@@ -216,6 +216,27 @@ namespace OpenSim.Framework
216 return false; 216 return false;
217 } 217 }
218 218
219 public bool TryOrderedDequeue(out EntityUpdate value, out Int32 timeinqueue)
220 {
221 // If there is anything in imediate queues, return it first no
222 // matter what else. Breaks fairness. But very useful.
223 for (int iq = 0; iq < NumberOfQueues; iq++)
224 {
225 if (m_heaps[iq].Count > 0)
226 {
227 MinHeapItem item = m_heaps[iq].RemoveMin();
228 m_lookupTable.Remove(item.Value.Entity.LocalId);
229 timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
230 value = item.Value;
231 return true;
232 }
233 }
234
235 timeinqueue = 0;
236 value = default(EntityUpdate);
237 return false;
238 }
239
219 /// <summary> 240 /// <summary>
220 /// Reapply the prioritization function to each of the updates currently 241 /// Reapply the prioritization function to each of the updates currently
221 /// stored in the priority queues. 242 /// stored in the priority queues.
diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs
index 7de8c52..75ed999 100644
--- a/OpenSim/Framework/RegionInfo.cs
+++ b/OpenSim/Framework/RegionInfo.cs
@@ -420,6 +420,7 @@ namespace OpenSim.Framework
420 set { m_remotingPort = value; } 420 set { m_remotingPort = value; }
421 } 421 }
422 422
423
423 /// <value> 424 /// <value>
424 /// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw. 425 /// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
425 /// 426 ///
@@ -427,42 +428,7 @@ namespace OpenSim.Framework
427 /// </value> 428 /// </value>
428 public IPEndPoint ExternalEndPoint 429 public IPEndPoint ExternalEndPoint
429 { 430 {
430 get 431 get { return Util.getEndPoint(m_externalHostName, m_internalEndPoint.Port); }
431 {
432 // Old one defaults to IPv6
433 //return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port);
434
435 IPAddress ia = null;
436 // If it is already an IP, don't resolve it - just return directly
437 if (IPAddress.TryParse(m_externalHostName, out ia))
438 return new IPEndPoint(ia, m_internalEndPoint.Port);
439
440 // Reset for next check
441 ia = null;
442 try
443 {
444 foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName))
445 {
446 if (ia == null)
447 ia = Adr;
448
449 if (Adr.AddressFamily == AddressFamily.InterNetwork)
450 {
451 ia = Adr;
452 break;
453 }
454 }
455 }
456 catch (SocketException e)
457 {
458 throw new Exception(
459 "Unable to resolve local hostname " + m_externalHostName + " innerException of type '" +
460 e + "' attached to this exception", e);
461 }
462
463 return new IPEndPoint(ia, m_internalEndPoint.Port);
464 }
465
466 set { m_externalHostName = value.ToString(); } 432 set { m_externalHostName = value.ToString(); }
467 } 433 }
468 434
diff --git a/OpenSim/Framework/RestClient.cs b/OpenSim/Framework/RestClient.cs
index 0166d9d..4939cf7 100644
--- a/OpenSim/Framework/RestClient.cs
+++ b/OpenSim/Framework/RestClient.cs
@@ -428,22 +428,23 @@ namespace OpenSim.Framework
428 if (WebUtil.DebugLevel >= 5) 428 if (WebUtil.DebugLevel >= 5)
429 WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src); 429 WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);
430 430
431 using (Stream dst = _request.GetRequestStream()) 431
432 try
432 { 433 {
433 m_log.Debug("[REST]: GetRequestStream is ok"); 434 using (Stream dst = _request.GetRequestStream())
434
435 byte[] buf = new byte[1024];
436 int length = src.Read(buf, 0, 1024);
437 m_log.Debug("[REST]: First Read is ok");
438 while (length > 0)
439 { 435 {
440 dst.Write(buf, 0, length); 436// m_log.Debug("[REST]: GetRequestStream is ok");
441 length = src.Read(buf, 0, 1024); 437
438 byte[] buf = new byte[1024];
439 int length = src.Read(buf, 0, 1024);
440// m_log.Debug("[REST]: First Read is ok");
441 while (length > 0)
442 {
443 dst.Write(buf, 0, length);
444 length = src.Read(buf, 0, 1024);
445 }
442 } 446 }
443 }
444 447
445 try
446 {
447 _response = (HttpWebResponse)_request.GetResponse(); 448 _response = (HttpWebResponse)_request.GetResponse();
448 } 449 }
449 catch (WebException e) 450 catch (WebException e)
diff --git a/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs b/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs
index 1523fa9..238ebb1 100644
--- a/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs
+++ b/OpenSim/Framework/Serialization/External/ExternalRepresentationUtils.cs
@@ -156,6 +156,7 @@ namespace OpenSim.Framework.Serialization.External
156 return xml; 156 return xml;
157 157
158 XmlDocument doc = new XmlDocument(); 158 XmlDocument doc = new XmlDocument();
159
159 doc.LoadXml(xml); 160 doc.LoadXml(xml);
160 XmlNodeList sops = doc.GetElementsByTagName("SceneObjectPart"); 161 XmlNodeList sops = doc.GetElementsByTagName("SceneObjectPart");
161 162
@@ -220,7 +221,7 @@ namespace OpenSim.Framework.Serialization.External
220 using (StringWriter sw = new StringWriter()) 221 using (StringWriter sw = new StringWriter())
221 using (XmlTextWriter writer = new XmlTextWriter(sw)) 222 using (XmlTextWriter writer = new XmlTextWriter(sw))
222 using (XmlTextReader wrappedReader = new XmlTextReader(xmlData, XmlNodeType.Element, null)) 223 using (XmlTextReader wrappedReader = new XmlTextReader(xmlData, XmlNodeType.Element, null))
223 using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment })) 224 using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment}))
224 { 225 {
225 TransformXml(reader, writer, sceneName, homeURL, userService, scopeID); 226 TransformXml(reader, writer, sceneName, homeURL, userService, scopeID);
226 227
diff --git a/OpenSim/Framework/Servers/BaseOpenSimServer.cs b/OpenSim/Framework/Servers/BaseOpenSimServer.cs
index f761813..f832f81 100644
--- a/OpenSim/Framework/Servers/BaseOpenSimServer.cs
+++ b/OpenSim/Framework/Servers/BaseOpenSimServer.cs
@@ -33,6 +33,9 @@ using System.Text;
33using System.Text.RegularExpressions; 33using System.Text.RegularExpressions;
34using System.Threading; 34using System.Threading;
35using System.Timers; 35using System.Timers;
36using System.Net;
37using System.Net.Security;
38using System.Security.Cryptography.X509Certificates;
36using log4net; 39using log4net;
37using log4net.Appender; 40using log4net.Appender;
38using log4net.Core; 41using log4net.Core;
@@ -86,6 +89,26 @@ namespace OpenSim.Framework.Servers
86 m_osSecret = UUID.Random().ToString(); 89 m_osSecret = UUID.Random().ToString();
87 } 90 }
88 91
92 private static bool m_NoVerifyCertChain = false;
93 private static bool m_NoVerifyCertHostname = false;
94
95 public static bool ValidateServerCertificate(
96 object sender,
97 X509Certificate certificate,
98 X509Chain chain,
99 SslPolicyErrors sslPolicyErrors)
100 {
101 if (m_NoVerifyCertChain)
102 sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
103
104 if (m_NoVerifyCertHostname)
105 sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
106
107 if (sslPolicyErrors == SslPolicyErrors.None)
108 return true;
109
110 return false;
111 }
89 /// <summary> 112 /// <summary>
90 /// Must be overriden by child classes for their own server specific startup behaviour. 113 /// Must be overriden by child classes for their own server specific startup behaviour.
91 /// </summary> 114 /// </summary>
@@ -96,6 +119,11 @@ namespace OpenSim.Framework.Servers
96 RegisterCommonComponents(Config); 119 RegisterCommonComponents(Config);
97 120
98 IConfig startupConfig = Config.Configs["Startup"]; 121 IConfig startupConfig = Config.Configs["Startup"];
122
123 m_NoVerifyCertChain = startupConfig.GetBoolean("NoVerifyCertChain", m_NoVerifyCertChain);
124 m_NoVerifyCertHostname = startupConfig.GetBoolean("NoVerifyCertHostname", m_NoVerifyCertHostname);
125 ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
126
99 int logShowStatsSeconds = startupConfig.GetInt("LogShowStatsSeconds", m_periodDiagnosticTimerMS / 1000); 127 int logShowStatsSeconds = startupConfig.GetInt("LogShowStatsSeconds", m_periodDiagnosticTimerMS / 1000);
100 m_periodDiagnosticTimerMS = logShowStatsSeconds * 1000; 128 m_periodDiagnosticTimerMS = logShowStatsSeconds * 1000;
101 m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics); 129 m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
@@ -108,13 +136,21 @@ namespace OpenSim.Framework.Servers
108 136
109 protected override void ShutdownSpecific() 137 protected override void ShutdownSpecific()
110 { 138 {
111 m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting..."); 139 Watchdog.Enabled = false;
140 base.ShutdownSpecific();
141
142 MainServer.Stop();
143
144 Thread.Sleep(5000);
145 Util.StopThreadPool();
146 WorkManager.Stop();
112 147
148 Thread.Sleep(1000);
113 RemovePIDFile(); 149 RemovePIDFile();
114 150
115 base.ShutdownSpecific(); 151 m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
116 152
117 if (!SuppressExit) 153 if (!SuppressExit)
118 Environment.Exit(0); 154 Environment.Exit(0);
119 } 155 }
120 156
@@ -163,8 +199,7 @@ namespace OpenSim.Framework.Servers
163 } 199 }
164 catch(Exception e) 200 catch(Exception e)
165 { 201 {
166 m_log.FatalFormat("Fatal error: {0}", 202 m_log.Fatal("Fatal error: " + e.ToString());
167 (e.Message == null || e.Message == String.Empty) ? "Unknown reason":e.Message );
168 Environment.Exit(1); 203 Environment.Exit(1);
169 } 204 }
170 205
diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
index fb92b92..2819bc9 100644
--- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
+++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
@@ -32,6 +32,7 @@ using System.Collections.Specialized;
32using System.IO; 32using System.IO;
33using System.Net; 33using System.Net;
34using System.Net.Sockets; 34using System.Net.Sockets;
35using System.Net.Security;
35using System.Security.Cryptography.X509Certificates; 36using System.Security.Cryptography.X509Certificates;
36using System.Reflection; 37using System.Reflection;
37using System.Globalization; 38using System.Globalization;
@@ -43,10 +44,11 @@ using log4net;
43using Nwc.XmlRpc; 44using Nwc.XmlRpc;
44using OpenMetaverse.StructuredData; 45using OpenMetaverse.StructuredData;
45using CoolHTTPListener = HttpServer.HttpListener; 46using CoolHTTPListener = HttpServer.HttpListener;
46using HttpListener=System.Net.HttpListener; 47using HttpListener = System.Net.HttpListener;
47using LogPrio=HttpServer.LogPrio; 48using LogPrio = HttpServer.LogPrio;
48using OpenSim.Framework.Monitoring; 49using OpenSim.Framework.Monitoring;
49using System.IO.Compression; 50using System.IO.Compression;
51using System.Security.Cryptography;
50 52
51namespace OpenSim.Framework.Servers.HttpServer 53namespace OpenSim.Framework.Servers.HttpServer
52{ 54{
@@ -107,19 +109,26 @@ namespace OpenSim.Framework.Servers.HttpServer
107 new Dictionary<string, WebSocketRequestDelegate>(); 109 new Dictionary<string, WebSocketRequestDelegate>();
108 110
109 protected uint m_port; 111 protected uint m_port;
110 protected uint m_sslport;
111 protected bool m_ssl; 112 protected bool m_ssl;
112 private X509Certificate2 m_cert; 113 private X509Certificate2 m_cert;
113 protected bool m_firstcaps = true;
114 protected string m_SSLCommonName = ""; 114 protected string m_SSLCommonName = "";
115 protected List<string> m_certNames = new List<string>();
116 protected List<string> m_certIPs = new List<string>();
117 protected string m_certCN= "";
118 protected RemoteCertificateValidationCallback m_certificateValidationCallback = null;
115 119
116 protected IPAddress m_listenIPAddress = IPAddress.Any; 120 protected IPAddress m_listenIPAddress = IPAddress.Any;
117 121
118 public PollServiceRequestManager PollServiceRequestManager { get; private set; } 122 public PollServiceRequestManager PollServiceRequestManager { get; private set; }
119 123
124 public string Protocol
125 {
126 get { return m_ssl ? "https://" : "http://"; }
127 }
128
120 public uint SSLPort 129 public uint SSLPort
121 { 130 {
122 get { return m_sslport; } 131 get { return m_port; }
123 } 132 }
124 133
125 public string SSLCommonName 134 public string SSLCommonName
@@ -148,27 +157,166 @@ namespace OpenSim.Framework.Servers.HttpServer
148 m_port = port; 157 m_port = port;
149 } 158 }
150 159
151 public BaseHttpServer(uint port, bool ssl) : this (port) 160 private void load_cert(string CPath, string CPass)
152 { 161 {
153 m_ssl = ssl; 162 try
163 {
164 m_cert = new X509Certificate2(CPath, CPass);
165 X509Extension ext = m_cert.Extensions["2.5.29.17"];
166 if(ext != null)
167 {
168 AsnEncodedData asndata = new AsnEncodedData(ext.Oid, ext.RawData);
169 string datastr = asndata.Format(true);
170 string[] lines = datastr.Split(new char[] {'\n','\r'});
171 foreach(string s in lines)
172 {
173 if(String.IsNullOrEmpty(s))
174 continue;
175 string[] parts = s.Split(new char[] {'='});
176 if(String.IsNullOrEmpty(parts[0]))
177 continue;
178 string entryName = parts[0].Replace(" ","");
179 if(entryName == "DNSName")
180 m_certNames.Add(parts[1]);
181 else if(entryName == "IPAddress")
182 m_certIPs.Add(parts[1]);
183 else if(entryName == "Unknown(135)") // stupid mono
184 {
185 try
186 {
187 if(parts[1].Length == 8)
188 {
189 long tmp = long.Parse(parts[1], NumberStyles.AllowHexSpecifier);
190 tmp = IPAddress.HostToNetworkOrder(tmp);
191 tmp = (long)((ulong) tmp >> 32);
192 IPAddress ia = new IPAddress(tmp);
193 m_certIPs.Add(ia.ToString());
194 }
195 }
196 catch {}
197 }
198 }
199 }
200 m_certCN = m_cert.GetNameInfo(X509NameType.SimpleName, false);
201 }
202 catch
203 {
204 throw new Exception("SSL cert load error");
205 }
154 } 206 }
155 207
156 public BaseHttpServer(uint port, bool ssl, uint sslport, string CN) : this (port, ssl) 208 public BaseHttpServer(uint port, bool ssl, string CN, string CPath, string CPass)
157 { 209 {
158 if (m_ssl) 210 m_port = port;
211 if (ssl)
159 { 212 {
160 m_sslport = sslport; 213 if(string.IsNullOrEmpty(CPath))
214 throw new Exception("invalid main http server cert path");
215
216 if(Uri.CheckHostName(CN) == UriHostNameType.Unknown)
217 throw new Exception("invalid main http server CN (ExternalHostName)");
218
219 m_certNames.Clear();
220 m_certIPs.Clear();
221 m_certCN= "";
222
223 m_ssl = true;
224 load_cert(CPath, CPass);
225
226 if(!CheckSSLCertHost(CN))
227 throw new Exception("invalid main http server CN (ExternalHostName)");
228
229 m_SSLCommonName = CN;
230
231 if(m_cert.Issuer == m_cert.Subject )
232 m_log.Warn("Self signed certificate. Clients need to allow this (some viewers debug option NoVerifySSLcert must be set to true");
161 } 233 }
234 else
235 m_ssl = false;
162 } 236 }
163 237
164 public BaseHttpServer(uint port, bool ssl, string CPath, string CPass) : this (port, ssl) 238 public BaseHttpServer(uint port, bool ssl, string CPath, string CPass)
165 { 239 {
166 if (m_ssl) 240 m_port = port;
241 if (ssl)
167 { 242 {
168 m_cert = new X509Certificate2(CPath, CPass); 243 load_cert(CPath, CPass);
244 if(m_cert.Issuer == m_cert.Subject )
245 m_log.Warn("Self signed certificate. Http clients need to allow this");
246 m_ssl = true;
247 }
248 else
249 m_ssl = false;
250 }
251
252 static bool MatchDNS (string hostname, string dns)
253 {
254 int indx = dns.IndexOf ('*');
255 if (indx == -1)
256 return (String.Compare(hostname, dns, true, CultureInfo.InvariantCulture) == 0);
257
258 int dnslen = dns.Length;
259 dnslen--;
260 if(indx == dnslen)
261 return true; // just * ?
262
263 if(indx > dnslen - 2)
264 return false; // 2 short ?
265
266 if (dns[indx + 1] != '.')
267 return false;
268
269 int indx2 = dns.IndexOf ('*', indx + 1);
270 if (indx2 != -1)
271 return false; // there can only be one;
272
273 string end = dns.Substring(indx + 1);
274 int hostlen = hostname.Length;
275 int endlen = end.Length;
276 int length = hostlen - endlen;
277 if (length <= 0)
278 return false;
279
280 if (String.Compare(hostname, length, end, 0, endlen, true, CultureInfo.InvariantCulture) != 0)
281 return false;
282
283 if (indx == 0)
284 {
285 indx2 = hostname.IndexOf ('.');
286 return ((indx2 == -1) || (indx2 >= length));
287 }
288
289 string start = dns.Substring (0, indx);
290 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);
291 }
292
293 public bool CheckSSLCertHost(string hostname)
294 {
295 UriHostNameType htype = Uri.CheckHostName(hostname);
296
297 if(htype == UriHostNameType.Unknown || htype == UriHostNameType.Basic)
298 return false;
299 if(htype == UriHostNameType.Dns)
300 {
301 foreach(string name in m_certNames)
302 {
303 if(MatchDNS(hostname, name))
304 return true;
305 }
306 if(MatchDNS(hostname, m_certCN))
307 return true;
308 }
309 else
310 {
311 foreach(string ip in m_certIPs)
312 {
313 if (String.Compare(hostname, ip, true, CultureInfo.InvariantCulture) == 0)
314 return true;
315 }
169 } 316 }
170 }
171 317
318 return false;
319 }
172 /// <summary> 320 /// <summary>
173 /// Add a stream handler to the http server. If the handler already exists, then nothing happens. 321 /// Add a stream handler to the http server. If the handler already exists, then nothing happens.
174 /// </summary> 322 /// </summary>
@@ -396,14 +544,10 @@ namespace OpenSim.Framework.Servers.HttpServer
396 if (psEvArgs.Request != null) 544 if (psEvArgs.Request != null)
397 { 545 {
398 OSHttpRequest req = new OSHttpRequest(context, request); 546 OSHttpRequest req = new OSHttpRequest(context, request);
399 547 string requestBody;
400 Stream requestStream = req.InputStream;
401
402 Encoding encoding = Encoding.UTF8; 548 Encoding encoding = Encoding.UTF8;
403 StreamReader reader = new StreamReader(requestStream, encoding); 549 using(StreamReader reader = new StreamReader(req.InputStream, encoding))
404 550 requestBody = reader.ReadToEnd();
405 string requestBody = reader.ReadToEnd();
406 reader.Close();
407 551
408 Hashtable keysvals = new Hashtable(); 552 Hashtable keysvals = new Hashtable();
409 Hashtable headervals = new Hashtable(); 553 Hashtable headervals = new Hashtable();
@@ -461,8 +605,7 @@ namespace OpenSim.Framework.Servers.HttpServer
461 } 605 }
462 606
463 OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context); 607 OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context);
464 resp.ReuseContext = true; 608
465// resp.ReuseContext = false;
466 HandleRequest(req, resp); 609 HandleRequest(req, resp);
467 610
468 // !!!HACK ALERT!!! 611 // !!!HACK ALERT!!!
@@ -494,6 +637,8 @@ namespace OpenSim.Framework.Servers.HttpServer
494 { 637 {
495 try 638 try
496 { 639 {
640 if(request.InputStream != null && request.InputStream.CanRead)
641 request.InputStream.Close();
497 byte[] buffer500 = SendHTML500(response); 642 byte[] buffer500 = SendHTML500(response);
498 response.OutputStream.Write(buffer500, 0, buffer500.Length); 643 response.OutputStream.Write(buffer500, 0, buffer500.Length);
499 response.Send(); 644 response.Send();
@@ -541,7 +686,6 @@ namespace OpenSim.Framework.Servers.HttpServer
541// } 686// }
542// } 687// }
543 688
544 //response.KeepAlive = true;
545 response.SendChunked = false; 689 response.SendChunked = false;
546 690
547 string path = request.RawUrl; 691 string path = request.RawUrl;
@@ -565,15 +709,11 @@ namespace OpenSim.Framework.Servers.HttpServer
565 { 709 {
566 //m_log.Debug("[BASE HTTP SERVER]: Found Caps based HTTP Handler"); 710 //m_log.Debug("[BASE HTTP SERVER]: Found Caps based HTTP Handler");
567 IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler; 711 IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler;
568 Stream requestStream = request.InputStream;
569 712
713 string requestBody;
570 Encoding encoding = Encoding.UTF8; 714 Encoding encoding = Encoding.UTF8;
571 StreamReader reader = new StreamReader(requestStream, encoding); 715 using(StreamReader reader = new StreamReader(request.InputStream, encoding))
572 716 requestBody = reader.ReadToEnd();
573 string requestBody = reader.ReadToEnd();
574
575 reader.Close();
576 //requestStream.Close();
577 717
578 Hashtable keysvals = new Hashtable(); 718 Hashtable keysvals = new Hashtable();
579 Hashtable headervals = new Hashtable(); 719 Hashtable headervals = new Hashtable();
@@ -613,7 +753,6 @@ namespace OpenSim.Framework.Servers.HttpServer
613 else 753 else
614 { 754 {
615 IStreamHandler streamHandler = (IStreamHandler)requestHandler; 755 IStreamHandler streamHandler = (IStreamHandler)requestHandler;
616
617 using (MemoryStream memoryStream = new MemoryStream()) 756 using (MemoryStream memoryStream = new MemoryStream())
618 { 757 {
619 streamHandler.Handle(path, request.InputStream, memoryStream, request, response); 758 streamHandler.Handle(path, request.InputStream, memoryStream, request, response);
@@ -690,7 +829,8 @@ namespace OpenSim.Framework.Servers.HttpServer
690 } 829 }
691 } 830 }
692 831
693 request.InputStream.Close(); 832 if(request.InputStream != null && request.InputStream.CanRead)
833 request.InputStream.Dispose();
694 834
695 if (buffer != null) 835 if (buffer != null)
696 { 836 {
@@ -723,10 +863,6 @@ namespace OpenSim.Framework.Servers.HttpServer
723 requestEndTick = Environment.TickCount; 863 requestEndTick = Environment.TickCount;
724 864
725 response.Send(); 865 response.Send();
726
727 //response.OutputStream.Close();
728
729 //response.FreeContext();
730 } 866 }
731 catch (SocketException e) 867 catch (SocketException e)
732 { 868 {
@@ -758,6 +894,9 @@ namespace OpenSim.Framework.Servers.HttpServer
758 } 894 }
759 finally 895 finally
760 { 896 {
897 if(request.InputStream != null && request.InputStream.CanRead)
898 request.InputStream.Close();
899
761 // Every month or so this will wrap and give bad numbers, not really a problem 900 // Every month or so this will wrap and give bad numbers, not really a problem
762 // since its just for reporting 901 // since its just for reporting
763 int tickdiff = requestEndTick - requestStartTick; 902 int tickdiff = requestEndTick - requestStartTick;
@@ -998,7 +1137,7 @@ namespace OpenSim.Framework.Servers.HttpServer
998 { 1137 {
999 String requestBody; 1138 String requestBody;
1000 1139
1001 Stream requestStream = request.InputStream; 1140 Stream requestStream = Util.Copy(request.InputStream);
1002 Stream innerStream = null; 1141 Stream innerStream = null;
1003 try 1142 try
1004 { 1143 {
@@ -1009,15 +1148,15 @@ namespace OpenSim.Framework.Servers.HttpServer
1009 } 1148 }
1010 1149
1011 using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8)) 1150 using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8))
1012 {
1013 requestBody = reader.ReadToEnd(); 1151 requestBody = reader.ReadToEnd();
1152
1014 } 1153 }
1015 }
1016 finally 1154 finally
1017 { 1155 {
1018 if (innerStream != null) 1156 if (innerStream != null && innerStream.CanRead)
1019 innerStream.Dispose(); 1157 innerStream.Dispose();
1020 requestStream.Dispose(); 1158 if (requestStream.CanRead)
1159 requestStream.Dispose();
1021 } 1160 }
1022 1161
1023 //m_log.Debug(requestBody); 1162 //m_log.Debug(requestBody);
@@ -1098,6 +1237,17 @@ namespace OpenSim.Framework.Servers.HttpServer
1098 1237
1099 if (gridproxy) 1238 if (gridproxy)
1100 xmlRprcRequest.Params.Add("gridproxy"); // Param[4] 1239 xmlRprcRequest.Params.Add("gridproxy"); // Param[4]
1240
1241 // reserve this for
1242 // ... by Fumi.Iseki for DTLNSLMoneyServer
1243 // BUT make its presence possible to detect/parse
1244 string rcn = request.IHttpClientContext.SSLCommonName;
1245 if(!string.IsNullOrWhiteSpace(rcn))
1246 {
1247 rcn = "SSLCN:" + rcn;
1248 xmlRprcRequest.Params.Add(rcn); // Param[4] or Param[5]
1249 }
1250
1101 try 1251 try
1102 { 1252 {
1103 xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint); 1253 xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
@@ -1263,15 +1413,12 @@ namespace OpenSim.Framework.Servers.HttpServer
1263 //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request"); 1413 //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
1264 Stream requestStream = request.InputStream; 1414 Stream requestStream = request.InputStream;
1265 1415
1416 string requestBody;
1266 Encoding encoding = Encoding.UTF8; 1417 Encoding encoding = Encoding.UTF8;
1267 StreamReader reader = new StreamReader(requestStream, encoding); 1418 using(StreamReader reader = new StreamReader(requestStream, encoding))
1268 1419 requestBody= reader.ReadToEnd();
1269 string requestBody = reader.ReadToEnd();
1270 reader.Close();
1271 requestStream.Close();
1272 1420
1273 //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody); 1421 //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
1274 response.KeepAlive = true;
1275 1422
1276 OSD llsdRequest = null; 1423 OSD llsdRequest = null;
1277 OSD llsdResponse = null; 1424 OSD llsdResponse = null;
@@ -1592,15 +1739,10 @@ namespace OpenSim.Framework.Servers.HttpServer
1592 byte[] buffer; 1739 byte[] buffer;
1593 1740
1594 Stream requestStream = request.InputStream; 1741 Stream requestStream = request.InputStream;
1595 1742 string requestBody;
1596 Encoding encoding = Encoding.UTF8; 1743 Encoding encoding = Encoding.UTF8;
1597 StreamReader reader = new StreamReader(requestStream, encoding); 1744 using(StreamReader reader = new StreamReader(requestStream, encoding))
1598 1745 requestBody = reader.ReadToEnd();
1599 string requestBody = reader.ReadToEnd();
1600 // avoid warning for now
1601 reader.ReadToEnd();
1602 reader.Close();
1603 requestStream.Close();
1604 1746
1605 Hashtable keysvals = new Hashtable(); 1747 Hashtable keysvals = new Hashtable();
1606 Hashtable headervals = new Hashtable(); 1748 Hashtable headervals = new Hashtable();
@@ -1792,20 +1934,13 @@ namespace OpenSim.Framework.Servers.HttpServer
1792 { 1934 {
1793 response.ProtocolVersion = (string)responsedata["http_protocol_version"]; 1935 response.ProtocolVersion = (string)responsedata["http_protocol_version"];
1794 } 1936 }
1795/* 1937
1796 if (responsedata.ContainsKey("keepalive")) 1938 if (responsedata.ContainsKey("keepalive"))
1797 { 1939 {
1798 bool keepalive = (bool)responsedata["keepalive"]; 1940 bool keepalive = (bool)responsedata["keepalive"];
1799 response.KeepAlive = keepalive; 1941 response.KeepAlive = keepalive;
1800 } 1942 }
1801 1943
1802 if (responsedata.ContainsKey("reusecontext"))
1803 response.ReuseContext = (bool) responsedata["reusecontext"];
1804*/
1805 // disable this things
1806 response.KeepAlive = false;
1807 response.ReuseContext = false;
1808
1809 // Cross-Origin Resource Sharing with simple requests 1944 // Cross-Origin Resource Sharing with simple requests
1810 if (responsedata.ContainsKey("access_control_allow_origin")) 1945 if (responsedata.ContainsKey("access_control_allow_origin"))
1811 response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]); 1946 response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
@@ -1818,11 +1953,8 @@ namespace OpenSim.Framework.Servers.HttpServer
1818 contentType = "text/html"; 1953 contentType = "text/html";
1819 } 1954 }
1820 1955
1821
1822
1823 // The client ignores anything but 200 here for web login, so ensure that this is 200 for that 1956 // The client ignores anything but 200 here for web login, so ensure that this is 200 for that
1824 1957
1825
1826 response.StatusCode = responsecode; 1958 response.StatusCode = responsecode;
1827 1959
1828 if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently) 1960 if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently)
@@ -1832,13 +1964,12 @@ namespace OpenSim.Framework.Servers.HttpServer
1832 } 1964 }
1833 1965
1834 response.AddHeader("Content-Type", contentType); 1966 response.AddHeader("Content-Type", contentType);
1835
1836 if (responsedata.ContainsKey("headers")) 1967 if (responsedata.ContainsKey("headers"))
1837 { 1968 {
1838 Hashtable headerdata = (Hashtable)responsedata["headers"]; 1969 Hashtable headerdata = (Hashtable)responsedata["headers"];
1839 1970
1840 foreach (string header in headerdata.Keys) 1971 foreach (string header in headerdata.Keys)
1841 response.AddHeader(header, (string)headerdata[header]); 1972 response.AddHeader(header, headerdata[header].ToString());
1842 } 1973 }
1843 1974
1844 byte[] buffer; 1975 byte[] buffer;
@@ -1906,7 +2037,7 @@ namespace OpenSim.Framework.Servers.HttpServer
1906 2037
1907 public void Start() 2038 public void Start()
1908 { 2039 {
1909 Start(true); 2040 Start(true,true);
1910 } 2041 }
1911 2042
1912 /// <summary> 2043 /// <summary>
@@ -1916,7 +2047,7 @@ namespace OpenSim.Framework.Servers.HttpServer
1916 /// If true then poll responses are performed asynchronsly. 2047 /// If true then poll responses are performed asynchronsly.
1917 /// Option exists to allow regression tests to perform processing synchronously. 2048 /// Option exists to allow regression tests to perform processing synchronously.
1918 /// </param> 2049 /// </param>
1919 public void Start(bool performPollResponsesAsync) 2050 public void Start(bool performPollResponsesAsync, bool runPool)
1920 { 2051 {
1921 m_log.InfoFormat( 2052 m_log.InfoFormat(
1922 "[BASE HTTP SERVER]: Starting {0} server on port {1}", UseSSL ? "HTTPS" : "HTTP", Port); 2053 "[BASE HTTP SERVER]: Starting {0} server on port {1}", UseSSL ? "HTTPS" : "HTTP", Port);
@@ -1945,6 +2076,8 @@ namespace OpenSim.Framework.Servers.HttpServer
1945 //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/"); 2076 //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
1946 //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); 2077 //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
1947 m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert); 2078 m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert);
2079 if(m_certificateValidationCallback != null)
2080 m_httpListener2.CertificateValidationCallback = m_certificateValidationCallback;
1948 m_httpListener2.ExceptionThrown += httpServerException; 2081 m_httpListener2.ExceptionThrown += httpServerException;
1949 m_httpListener2.LogWriter = httpserverlog; 2082 m_httpListener2.LogWriter = httpserverlog;
1950 } 2083 }
@@ -1954,9 +2087,11 @@ namespace OpenSim.Framework.Servers.HttpServer
1954 m_httpListener2.Start(64); 2087 m_httpListener2.Start(64);
1955 2088
1956 // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events 2089 // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events
1957 2090 if(runPool)
1958 PollServiceRequestManager = new PollServiceRequestManager(this, performPollResponsesAsync, 2, 25000); 2091 {
1959 PollServiceRequestManager.Start(); 2092 PollServiceRequestManager = new PollServiceRequestManager(this, performPollResponsesAsync, 2, 25000);
2093 PollServiceRequestManager.Start();
2094 }
1960 2095
1961 HTTPDRunning = true; 2096 HTTPDRunning = true;
1962 2097
@@ -1970,7 +2105,7 @@ namespace OpenSim.Framework.Servers.HttpServer
1970 catch (Exception e) 2105 catch (Exception e)
1971 { 2106 {
1972 m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message); 2107 m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
1973 m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?"); 2108 m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + "?");
1974 2109
1975 // We want this exception to halt the entire server since in current configurations we aren't too 2110 // We want this exception to halt the entire server since in current configurations we aren't too
1976 // useful without inbound HTTP. 2111 // useful without inbound HTTP.
@@ -2028,7 +2163,8 @@ namespace OpenSim.Framework.Servers.HttpServer
2028 2163
2029 try 2164 try
2030 { 2165 {
2031 PollServiceRequestManager.Stop(); 2166 if(PollServiceRequestManager != null)
2167 PollServiceRequestManager.Stop();
2032 2168
2033 m_httpListener2.ExceptionThrown -= httpServerException; 2169 m_httpListener2.ExceptionThrown -= httpServerException;
2034 //m_httpListener2.DisconnectHandler = null; 2170 //m_httpListener2.DisconnectHandler = null;
@@ -2135,10 +2271,9 @@ namespace OpenSim.Framework.Servers.HttpServer
2135 string file = Path.Combine(".", "http_500.html"); 2271 string file = Path.Combine(".", "http_500.html");
2136 if (!File.Exists(file)) 2272 if (!File.Exists(file))
2137 return getDefaultHTTP500(); 2273 return getDefaultHTTP500();
2138 2274 string result;
2139 StreamReader sr = File.OpenText(file); 2275 using(StreamReader sr = File.OpenText(file))
2140 string result = sr.ReadToEnd(); 2276 result = sr.ReadToEnd();
2141 sr.Close();
2142 return result; 2277 return result;
2143 } 2278 }
2144 2279
diff --git a/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs b/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs
index f61b090..d26b68a 100644
--- a/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs
+++ b/OpenSim/Framework/Servers/HttpServer/Interfaces/IOSHttpResponse.cs
@@ -118,7 +118,7 @@ namespace OpenSim.Framework.Servers.HttpServer
118 /// </summary> 118 /// </summary>
119 string StatusDescription { get; set; } 119 string StatusDescription { get; set; }
120 120
121 bool ReuseContext { get; set; } 121// bool ReuseContext { get; set; }
122 122
123 /// <summary> 123 /// <summary>
124 /// Add a header field and content to the response. 124 /// Add a header field and content to the response.
diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpResponse.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpResponse.cs
index d7744fc..a107ced 100644
--- a/OpenSim/Framework/Servers/HttpServer/OSHttpResponse.cs
+++ b/OpenSim/Framework/Servers/HttpServer/OSHttpResponse.cs
@@ -257,25 +257,6 @@ namespace OpenSim.Framework.Servers.HttpServer
257 } 257 }
258 } 258 }
259 259
260 public bool ReuseContext
261 {
262 get
263 {
264 if (_httpClientContext != null)
265 {
266 return !_httpClientContext.EndWhenDone;
267 }
268 return true;
269 }
270 set
271 {
272 if (_httpClientContext != null)
273 {
274 _httpClientContext.EndWhenDone = !value;
275 }
276 }
277 }
278
279 protected IHttpResponse _httpResponse; 260 protected IHttpResponse _httpResponse;
280 private IHttpClientContext _httpClientContext; 261 private IHttpClientContext _httpClientContext;
281 262
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
index 8ace7a9..7c7d08d 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
@@ -37,6 +37,7 @@ namespace OpenSim.Framework.Servers.HttpServer
37 public delegate Hashtable GetEventsMethod(UUID requestID, UUID pId); 37 public delegate Hashtable GetEventsMethod(UUID requestID, UUID pId);
38 38
39 public delegate Hashtable NoEventsMethod(UUID requestID, UUID pId); 39 public delegate Hashtable NoEventsMethod(UUID requestID, UUID pId);
40 public delegate void DropMethod(UUID requestID, UUID pId);
40 41
41 public class PollServiceEventArgs : EventArgs 42 public class PollServiceEventArgs : EventArgs
42 { 43 {
@@ -44,13 +45,14 @@ namespace OpenSim.Framework.Servers.HttpServer
44 public GetEventsMethod GetEvents; 45 public GetEventsMethod GetEvents;
45 public NoEventsMethod NoEvents; 46 public NoEventsMethod NoEvents;
46 public RequestMethod Request; 47 public RequestMethod Request;
48 public DropMethod Drop;
47 public UUID Id; 49 public UUID Id;
48 public int TimeOutms; 50 public int TimeOutms;
49 public EventType Type; 51 public EventType Type;
50 52
51 public enum EventType : int 53 public enum EventType : int
52 { 54 {
53 LongPoll = 0, 55 Poll = 0,
54 LslHttp = 1, 56 LslHttp = 1,
55 Inventory = 2, 57 Inventory = 2,
56 Texture = 3, 58 Texture = 3,
@@ -73,16 +75,17 @@ namespace OpenSim.Framework.Servers.HttpServer
73 RequestMethod pRequest, 75 RequestMethod pRequest,
74 string pUrl, 76 string pUrl,
75 HasEventsMethod pHasEvents, GetEventsMethod pGetEvents, NoEventsMethod pNoEvents, 77 HasEventsMethod pHasEvents, GetEventsMethod pGetEvents, NoEventsMethod pNoEvents,
76 UUID pId, int pTimeOutms) 78 DropMethod pDrop, UUID pId, int pTimeOutms)
77 { 79 {
78 Request = pRequest; 80 Request = pRequest;
79 Url = pUrl; 81 Url = pUrl;
80 HasEvents = pHasEvents; 82 HasEvents = pHasEvents;
81 GetEvents = pGetEvents; 83 GetEvents = pGetEvents;
82 NoEvents = pNoEvents; 84 NoEvents = pNoEvents;
85 Drop = pDrop;
83 Id = pId; 86 Id = pId;
84 TimeOutms = pTimeOutms; 87 TimeOutms = pTimeOutms;
85 Type = EventType.LongPoll; 88 Type = EventType.Poll;
86 } 89 }
87 } 90 }
88} 91}
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
index 3eb330a..4fd69f3 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
@@ -47,8 +47,10 @@ namespace OpenSim.Framework.Servers.HttpServer
47 public readonly UUID RequestID; 47 public readonly UUID RequestID;
48 public int contextHash; 48 public int contextHash;
49 49
50/*
50 private void GenContextHash() 51 private void GenContextHash()
51 { 52 {
53
52 Random rnd = new Random(); 54 Random rnd = new Random();
53 contextHash = 0; 55 contextHash = 0;
54 if (Request.Headers["remote_addr"] != null) 56 if (Request.Headers["remote_addr"] != null)
@@ -62,8 +64,9 @@ namespace OpenSim.Framework.Servers.HttpServer
62 } 64 }
63 else 65 else
64 contextHash += rnd.Next() & 0xffff; 66 contextHash += rnd.Next() & 0xffff;
65 }
66 67
68 }
69*/
67 public PollServiceHttpRequest( 70 public PollServiceHttpRequest(
68 PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext, IHttpRequest pRequest) 71 PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext, IHttpRequest pRequest)
69 { 72 {
@@ -72,7 +75,8 @@ namespace OpenSim.Framework.Servers.HttpServer
72 Request = pRequest; 75 Request = pRequest;
73 RequestTime = System.Environment.TickCount; 76 RequestTime = System.Environment.TickCount;
74 RequestID = UUID.Random(); 77 RequestID = UUID.Random();
75 GenContextHash(); 78// GenContextHash();
79 contextHash = HttpContext.contextID;
76 } 80 }
77 81
78 internal void DoHTTPGruntWork(BaseHttpServer server, Hashtable responsedata) 82 internal void DoHTTPGruntWork(BaseHttpServer server, Hashtable responsedata)
@@ -82,10 +86,12 @@ namespace OpenSim.Framework.Servers.HttpServer
82 86
83 byte[] buffer = server.DoHTTPGruntWork(responsedata, response); 87 byte[] buffer = server.DoHTTPGruntWork(responsedata, response);
84 88
89 if(Request.Body.CanRead)
90 Request.Body.Dispose();
91
85 response.SendChunked = false; 92 response.SendChunked = false;
86 response.ContentLength64 = buffer.Length; 93 response.ContentLength64 = buffer.Length;
87 response.ContentEncoding = Encoding.UTF8; 94 response.ContentEncoding = Encoding.UTF8;
88 response.ReuseContext = false;
89 95
90 try 96 try
91 { 97 {
@@ -114,10 +120,12 @@ namespace OpenSim.Framework.Servers.HttpServer
114 OSHttpResponse response 120 OSHttpResponse response
115 = new OSHttpResponse(new HttpResponse(HttpContext, Request), HttpContext); 121 = new OSHttpResponse(new HttpResponse(HttpContext, Request), HttpContext);
116 122
123 if(Request.Body.CanRead)
124 Request.Body.Dispose();
125
117 response.SendChunked = false; 126 response.SendChunked = false;
118 response.ContentLength64 = 0; 127 response.ContentLength64 = 0;
119 response.ContentEncoding = Encoding.UTF8; 128 response.ContentEncoding = Encoding.UTF8;
120 response.ReuseContext = false;
121 response.KeepAlive = false; 129 response.KeepAlive = false;
122 response.SendChunked = false; 130 response.SendChunked = false;
123 response.StatusCode = 503; 131 response.StatusCode = 503;
@@ -127,7 +135,7 @@ namespace OpenSim.Framework.Servers.HttpServer
127 response.OutputStream.Flush(); 135 response.OutputStream.Flush();
128 response.Send(); 136 response.Send();
129 } 137 }
130 catch (Exception e) 138 catch
131 { 139 {
132 } 140 }
133 } 141 }
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
index 936146d..a2f6a11 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
@@ -30,13 +30,10 @@ using System.Collections;
30using System.Threading; 30using System.Threading;
31using System.Reflection; 31using System.Reflection;
32using log4net; 32using log4net;
33using HttpServer;
34using OpenSim.Framework;
35using OpenSim.Framework.Monitoring; 33using OpenSim.Framework.Monitoring;
36using Amib.Threading; 34using Amib.Threading;
37using System.IO;
38using System.Text;
39using System.Collections.Generic; 35using System.Collections.Generic;
36using System.Collections.Concurrent;
40 37
41namespace OpenSim.Framework.Servers.HttpServer 38namespace OpenSim.Framework.Servers.HttpServer
42{ 39{
@@ -46,21 +43,18 @@ namespace OpenSim.Framework.Servers.HttpServer
46 43
47 private readonly BaseHttpServer m_server; 44 private readonly BaseHttpServer m_server;
48 45
49 private Dictionary<PollServiceHttpRequest, Queue<PollServiceHttpRequest>> m_bycontext; 46 private Dictionary<int, Queue<PollServiceHttpRequest>> m_bycontext;
50 private BlockingQueue<PollServiceHttpRequest> m_requests = new BlockingQueue<PollServiceHttpRequest>(); 47 private BlockingCollection<PollServiceHttpRequest> m_requests = new BlockingCollection<PollServiceHttpRequest>();
51 private static Queue<PollServiceHttpRequest> m_slowRequests = new Queue<PollServiceHttpRequest>(); 48 private static ConcurrentQueue<PollServiceHttpRequest> m_retryRequests = new ConcurrentQueue<PollServiceHttpRequest>();
52 private static Queue<PollServiceHttpRequest> m_retryRequests = new Queue<PollServiceHttpRequest>();
53 49
54 private uint m_WorkerThreadCount = 0; 50 private uint m_WorkerThreadCount = 0;
55 private Thread[] m_workerThreads; 51 private Thread[] m_workerThreads;
56 private Thread m_retrysThread; 52 private Thread m_retrysThread;
57 53
58 private bool m_running = false; 54 private bool m_running = false;
59 private int slowCount = 0;
60 55
61 private SmartThreadPool m_threadPool; 56 private SmartThreadPool m_threadPool;
62 57
63
64 public PollServiceRequestManager( 58 public PollServiceRequestManager(
65 BaseHttpServer pSrv, bool performResponsesAsync, uint pWorkerThreadCount, int pTimeout) 59 BaseHttpServer pSrv, bool performResponsesAsync, uint pWorkerThreadCount, int pTimeout)
66 { 60 {
@@ -68,8 +62,7 @@ namespace OpenSim.Framework.Servers.HttpServer
68 m_WorkerThreadCount = pWorkerThreadCount; 62 m_WorkerThreadCount = pWorkerThreadCount;
69 m_workerThreads = new Thread[m_WorkerThreadCount]; 63 m_workerThreads = new Thread[m_WorkerThreadCount];
70 64
71 PollServiceHttpRequestComparer preqCp = new PollServiceHttpRequestComparer(); 65 m_bycontext = new Dictionary<int, Queue<PollServiceHttpRequest>>(256);
72 m_bycontext = new Dictionary<PollServiceHttpRequest, Queue<PollServiceHttpRequest>>(preqCp);
73 66
74 STPStartInfo startInfo = new STPStartInfo(); 67 STPStartInfo startInfo = new STPStartInfo();
75 startInfo.IdleTimeout = 30000; 68 startInfo.IdleTimeout = 30000;
@@ -80,7 +73,6 @@ namespace OpenSim.Framework.Servers.HttpServer
80 startInfo.ThreadPoolName = "PoolService"; 73 startInfo.ThreadPoolName = "PoolService";
81 74
82 m_threadPool = new SmartThreadPool(startInfo); 75 m_threadPool = new SmartThreadPool(startInfo);
83
84 } 76 }
85 77
86 public void Start() 78 public void Start()
@@ -95,7 +87,7 @@ namespace OpenSim.Framework.Servers.HttpServer
95 PoolWorkerJob, 87 PoolWorkerJob,
96 string.Format("PollServiceWorkerThread {0}:{1}", i, m_server.Port), 88 string.Format("PollServiceWorkerThread {0}:{1}", i, m_server.Port),
97 ThreadPriority.Normal, 89 ThreadPriority.Normal,
98 false, 90 true,
99 false, 91 false,
100 null, 92 null,
101 int.MaxValue); 93 int.MaxValue);
@@ -105,36 +97,32 @@ namespace OpenSim.Framework.Servers.HttpServer
105 this.CheckRetries, 97 this.CheckRetries,
106 string.Format("PollServiceWatcherThread:{0}", m_server.Port), 98 string.Format("PollServiceWatcherThread:{0}", m_server.Port),
107 ThreadPriority.Normal, 99 ThreadPriority.Normal,
108 false, 100 true,
109 true, 101 true,
110 null, 102 null,
111 1000 * 60 * 10); 103 1000 * 60 * 10);
112
113
114 } 104 }
115 105
116 private void ReQueueEvent(PollServiceHttpRequest req) 106 private void ReQueueEvent(PollServiceHttpRequest req)
117 { 107 {
118 if (m_running) 108 if (m_running)
119 { 109 m_retryRequests.Enqueue(req);
120 lock (m_retryRequests)
121 m_retryRequests.Enqueue(req);
122 }
123 } 110 }
124 111
125 public void Enqueue(PollServiceHttpRequest req) 112 public void Enqueue(PollServiceHttpRequest req)
126 { 113 {
114 Queue<PollServiceHttpRequest> ctxQeueue;
115 int rhash = req.contextHash;
127 lock (m_bycontext) 116 lock (m_bycontext)
128 { 117 {
129 Queue<PollServiceHttpRequest> ctxQeueue; 118 if (m_bycontext.TryGetValue(rhash, out ctxQeueue))
130 if (m_bycontext.TryGetValue(req, out ctxQeueue))
131 { 119 {
132 ctxQeueue.Enqueue(req); 120 ctxQeueue.Enqueue(req);
133 } 121 }
134 else 122 else
135 { 123 {
136 ctxQeueue = new Queue<PollServiceHttpRequest>(); 124 ctxQeueue = new Queue<PollServiceHttpRequest>();
137 m_bycontext[req] = ctxQeueue; 125 m_bycontext[rhash] = ctxQeueue;
138 EnqueueInt(req); 126 EnqueueInt(req);
139 } 127 }
140 } 128 }
@@ -143,9 +131,10 @@ namespace OpenSim.Framework.Servers.HttpServer
143 public void byContextDequeue(PollServiceHttpRequest req) 131 public void byContextDequeue(PollServiceHttpRequest req)
144 { 132 {
145 Queue<PollServiceHttpRequest> ctxQeueue; 133 Queue<PollServiceHttpRequest> ctxQeueue;
134 int rhash = req.contextHash;
146 lock (m_bycontext) 135 lock (m_bycontext)
147 { 136 {
148 if (m_bycontext.TryGetValue(req, out ctxQeueue)) 137 if (m_bycontext.TryGetValue(rhash, out ctxQeueue))
149 { 138 {
150 if (ctxQeueue.Count > 0) 139 if (ctxQeueue.Count > 0)
151 { 140 {
@@ -154,51 +143,41 @@ namespace OpenSim.Framework.Servers.HttpServer
154 } 143 }
155 else 144 else
156 { 145 {
157 m_bycontext.Remove(req); 146 m_bycontext.Remove(rhash);
158 } 147 }
159 } 148 }
160 } 149 }
161 } 150 }
162 151
163 public void EnqueueInt(PollServiceHttpRequest req) 152 public void DropByContext(PollServiceHttpRequest req)
164 { 153 {
165 if (m_running) 154 Queue<PollServiceHttpRequest> ctxQeueue;
155 int rhash = req.contextHash;
156 lock (m_bycontext)
166 { 157 {
167 if (req.PollServiceArgs.Type != PollServiceEventArgs.EventType.LongPoll) 158 if (m_bycontext.TryGetValue(rhash, out ctxQeueue))
168 { 159 {
169 m_requests.Enqueue(req); 160 ctxQeueue.Clear();
170 } 161 m_bycontext.Remove(rhash);
171 else
172 {
173 lock (m_slowRequests)
174 m_slowRequests.Enqueue(req);
175 } 162 }
176 } 163 }
177 } 164 }
178 165
166 public void EnqueueInt(PollServiceHttpRequest req)
167 {
168 if (m_running)
169 m_requests.Add(req);
170 }
171
179 private void CheckRetries() 172 private void CheckRetries()
180 { 173 {
174 PollServiceHttpRequest preq;
181 while (m_running) 175 while (m_running)
182
183 { 176 {
184 Thread.Sleep(100); // let the world move .. back to faster rate 177 Thread.Sleep(100);
185 Watchdog.UpdateThread(); 178 Watchdog.UpdateThread();
186 lock (m_retryRequests) 179 while (m_running && m_retryRequests.TryDequeue(out preq))
187 { 180 m_requests.Add(preq);
188 while (m_retryRequests.Count > 0 && m_running)
189 m_requests.Enqueue(m_retryRequests.Dequeue());
190 }
191 slowCount++;
192 if (slowCount >= 10)
193 {
194 slowCount = 0;
195
196 lock (m_slowRequests)
197 {
198 while (m_slowRequests.Count > 0 && m_running)
199 m_requests.Enqueue(m_slowRequests.Dequeue());
200 }
201 }
202 } 181 }
203 } 182 }
204 183
@@ -206,117 +185,130 @@ namespace OpenSim.Framework.Servers.HttpServer
206 { 185 {
207 m_running = false; 186 m_running = false;
208 187
209 Thread.Sleep(1000); // let the world move 188 Thread.Sleep(100); // let the world move
210 189
211 foreach (Thread t in m_workerThreads) 190 foreach (Thread t in m_workerThreads)
212 Watchdog.AbortThread(t.ManagedThreadId); 191 Watchdog.AbortThread(t.ManagedThreadId);
213 192
193 m_threadPool.Shutdown();
194
214 // any entry in m_bycontext should have a active request on the other queues 195 // any entry in m_bycontext should have a active request on the other queues
215 // so just delete contents to easy GC 196 // so just delete contents to easy GC
216 foreach (Queue<PollServiceHttpRequest> qu in m_bycontext.Values) 197 foreach (Queue<PollServiceHttpRequest> qu in m_bycontext.Values)
217 qu.Clear(); 198 qu.Clear();
218 m_bycontext.Clear(); 199 m_bycontext.Clear();
219 200
201 PollServiceHttpRequest req;
220 try 202 try
221 { 203 {
222 foreach (PollServiceHttpRequest req in m_retryRequests) 204 while(m_retryRequests.TryDequeue(out req))
223 {
224 req.DoHTTPstop(m_server); 205 req.DoHTTPstop(m_server);
225 }
226 } 206 }
227 catch 207 catch
228 { 208 {
229 } 209 }
230 210
231 PollServiceHttpRequest wreq; 211 try
232 m_retryRequests.Clear();
233
234 lock (m_slowRequests)
235 { 212 {
236 while (m_slowRequests.Count > 0) 213 while(m_requests.TryTake(out req, 0))
237 m_requests.Enqueue(m_slowRequests.Dequeue()); 214 req.DoHTTPstop(m_server);
238
239 } 215 }
240 216 catch
241 while (m_requests.Count() > 0)
242 { 217 {
243 try
244 {
245 wreq = m_requests.Dequeue(0);
246 wreq.DoHTTPstop(m_server);
247
248 }
249 catch
250 {
251 }
252 } 218 }
253 219
254 m_requests.Clear(); 220 m_requests.Dispose();
221
255 } 222 }
256 223
257 // work threads 224 // work threads
258 225
259 private void PoolWorkerJob() 226 private void PoolWorkerJob()
260 { 227 {
228 PollServiceHttpRequest req;
261 while (m_running) 229 while (m_running)
262 { 230 {
263 PollServiceHttpRequest req = m_requests.Dequeue(5000); 231 req = null;
232 if(!m_requests.TryTake(out req, 4500) || req == null)
233 {
234 Watchdog.UpdateThread();
235 continue;
236 }
264 237
265 Watchdog.UpdateThread(); 238 Watchdog.UpdateThread();
266 if (req != null) 239
240 try
267 { 241 {
268 try 242 if(!req.HttpContext.CanSend())
243 {
244 req.PollServiceArgs.Drop(req.RequestID, req.PollServiceArgs.Id);
245 byContextDequeue(req);
246 continue;
247 }
248
249 if(req.HttpContext.IsSending())
269 { 250 {
270 if (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id)) 251 if ((Environment.TickCount - req.RequestTime) > req.PollServiceArgs.TimeOutms)
271 { 252 {
272 Hashtable responsedata = req.PollServiceArgs.GetEvents(req.RequestID, req.PollServiceArgs.Id); 253 req.PollServiceArgs.Drop(req.RequestID, req.PollServiceArgs.Id);
254 byContextDequeue(req);
255 }
256 else
257 ReQueueEvent(req);
258 continue;
259 }
273 260
261 if (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id))
262 {
263 PollServiceHttpRequest nreq = req;
264 m_threadPool.QueueWorkItem(x =>
265 {
266 try
267 {
268 Hashtable responsedata = nreq.PollServiceArgs.GetEvents(nreq.RequestID, nreq.PollServiceArgs.Id);
269 nreq.DoHTTPGruntWork(m_server, responsedata);
270 }
271 catch (ObjectDisposedException) { }
272 finally
273 {
274 byContextDequeue(nreq);
275 nreq = null;
276 }
277 return null;
278 }, null);
279 }
280 else
281 {
282 if ((Environment.TickCount - req.RequestTime) > req.PollServiceArgs.TimeOutms)
283 {
284 PollServiceHttpRequest nreq = req;
274 m_threadPool.QueueWorkItem(x => 285 m_threadPool.QueueWorkItem(x =>
275 { 286 {
276 try 287 try
277 { 288 {
278 req.DoHTTPGruntWork(m_server, responsedata); 289 nreq.DoHTTPGruntWork(m_server,
279 byContextDequeue(req); 290 nreq.PollServiceArgs.NoEvents(nreq.RequestID, nreq.PollServiceArgs.Id));
280 } 291 }
281 catch (ObjectDisposedException) // Browser aborted before we could read body, server closed the stream 292 catch (ObjectDisposedException) {}
293 finally
282 { 294 {
283 // Ignore it, no need to reply 295 byContextDequeue(nreq);
296 nreq = null;
284 } 297 }
285 return null; 298 return null;
286 }, null); 299 }, null);
287 } 300 }
288 else 301 else
289 { 302 {
290 if ((Environment.TickCount - req.RequestTime) > req.PollServiceArgs.TimeOutms) 303 ReQueueEvent(req);
291 {
292 m_threadPool.QueueWorkItem(x =>
293 {
294 try
295 {
296 req.DoHTTPGruntWork(m_server,
297 req.PollServiceArgs.NoEvents(req.RequestID, req.PollServiceArgs.Id));
298 byContextDequeue(req);
299 }
300 catch (ObjectDisposedException)
301 {
302 // Ignore it, no need to reply
303 }
304 return null;
305 }, null);
306 }
307 else
308 {
309 ReQueueEvent(req);
310 }
311 } 304 }
312 } 305 }
313 catch (Exception e) 306 }
314 { 307 catch (Exception e)
315 m_log.ErrorFormat("Exception in poll service thread: " + e.ToString()); 308 {
316 } 309 m_log.ErrorFormat("Exception in poll service thread: " + e.ToString());
317 } 310 }
318 } 311 }
319 } 312 }
320
321 } 313 }
322} 314}
diff --git a/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs b/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs
index 0305dee..dfc2715 100644
--- a/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs
+++ b/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs
@@ -50,11 +50,10 @@ namespace OpenSim.Framework.Servers.HttpServer
50 50
51 protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) 51 protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
52 { 52 {
53 string requestBody;
53 Encoding encoding = Encoding.UTF8; 54 Encoding encoding = Encoding.UTF8;
54 StreamReader streamReader = new StreamReader(request, encoding); 55 using(StreamReader streamReader = new StreamReader(request,encoding))
55 56 requestBody = streamReader.ReadToEnd();
56 string requestBody = streamReader.ReadToEnd();
57 streamReader.Close();
58 57
59 string param = GetParam(path); 58 string param = GetParam(path);
60 string responseString = m_restMethod(requestBody, path, param, httpRequest, httpResponse); 59 string responseString = m_restMethod(requestBody, path, param, httpRequest, httpResponse);
diff --git a/OpenSim/Framework/Servers/MainServer.cs b/OpenSim/Framework/Servers/MainServer.cs
index ea7b2b5..523ccba 100644
--- a/OpenSim/Framework/Servers/MainServer.cs
+++ b/OpenSim/Framework/Servers/MainServer.cs
@@ -42,6 +42,7 @@ namespace OpenSim.Framework.Servers
42// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 42// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
43 43
44 private static BaseHttpServer instance = null; 44 private static BaseHttpServer instance = null;
45 private static BaseHttpServer unsecureinstance = null;
45 private static Dictionary<uint, BaseHttpServer> m_Servers = new Dictionary<uint, BaseHttpServer>(); 46 private static Dictionary<uint, BaseHttpServer> m_Servers = new Dictionary<uint, BaseHttpServer>();
46 47
47 /// <summary> 48 /// <summary>
@@ -93,6 +94,21 @@ namespace OpenSim.Framework.Servers
93 } 94 }
94 } 95 }
95 96
97
98 public static BaseHttpServer UnSecureInstance
99 {
100 get { return unsecureinstance; }
101
102 set
103 {
104 lock (m_Servers)
105 if (!m_Servers.ContainsValue(value))
106 throw new Exception("HTTP server must already have been registered to be set as the main instance");
107
108 unsecureinstance = value;
109 }
110 }
111
96 /// <summary> 112 /// <summary>
97 /// Get all the registered servers. 113 /// Get all the registered servers.
98 /// </summary> 114 /// </summary>
@@ -353,5 +369,17 @@ namespace OpenSim.Framework.Servers
353 return m_Servers[port]; 369 return m_Servers[port];
354 } 370 }
355 } 371 }
372
373 public static void Stop()
374 {
375 lock (m_Servers)
376 {
377 foreach (BaseHttpServer httpServer in m_Servers.Values)
378 {
379 httpServer.Stop();
380 }
381 }
382 }
383
356 } 384 }
357} \ No newline at end of file 385} \ No newline at end of file
diff --git a/OpenSim/Framework/Servers/ServerBase.cs b/OpenSim/Framework/Servers/ServerBase.cs
index f627ae6..3c2dce8 100644
--- a/OpenSim/Framework/Servers/ServerBase.cs
+++ b/OpenSim/Framework/Servers/ServerBase.cs
@@ -275,18 +275,6 @@ namespace OpenSim.Framework.Servers
275 (string module, string[] args) => Notice(GetThreadsReport())); 275 (string module, string[] args) => Notice(GetThreadsReport()));
276 276
277 m_console.Commands.AddCommand ( 277 m_console.Commands.AddCommand (
278 "Debug", false, "debug comms set",
279 "debug comms set serialosdreq true|false",
280 "Set comms parameters. For debug purposes.",
281 HandleDebugCommsSet);
282
283 m_console.Commands.AddCommand (
284 "Debug", false, "debug comms status",
285 "debug comms status",
286 "Show current debug comms parameters.",
287 HandleDebugCommsStatus);
288
289 m_console.Commands.AddCommand (
290 "Debug", false, "debug threadpool set", 278 "Debug", false, "debug threadpool set",
291 "debug threadpool set worker|iocp min|max <n>", 279 "debug threadpool set worker|iocp min|max <n>",
292 "Set threadpool parameters. For debug purposes.", 280 "Set threadpool parameters. For debug purposes.",
@@ -343,47 +331,13 @@ namespace OpenSim.Framework.Servers
343 331
344 public void RegisterCommonComponents(IConfigSource configSource) 332 public void RegisterCommonComponents(IConfigSource configSource)
345 { 333 {
346 IConfig networkConfig = configSource.Configs["Network"]; 334// IConfig networkConfig = configSource.Configs["Network"];
347
348 if (networkConfig != null)
349 {
350 WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false);
351 }
352 335
353 m_serverStatsCollector = new ServerStatsCollector(); 336 m_serverStatsCollector = new ServerStatsCollector();
354 m_serverStatsCollector.Initialise(configSource); 337 m_serverStatsCollector.Initialise(configSource);
355 m_serverStatsCollector.Start(); 338 m_serverStatsCollector.Start();
356 } 339 }
357 340
358 private void HandleDebugCommsStatus(string module, string[] args)
359 {
360 Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint);
361 }
362
363 private void HandleDebugCommsSet(string module, string[] args)
364 {
365 if (args.Length != 5)
366 {
367 Notice("Usage: debug comms set serialosdreq true|false");
368 return;
369 }
370
371 if (args[3] != "serialosdreq")
372 {
373 Notice("Usage: debug comms set serialosdreq true|false");
374 return;
375 }
376
377 bool setSerializeOsdRequests;
378
379 if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests))
380 return;
381
382 WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests;
383
384 Notice("serialosdreq is now {0}", setSerializeOsdRequests);
385 }
386
387 private void HandleShowThreadpoolCallsActive(string module, string[] args) 341 private void HandleShowThreadpoolCallsActive(string module, string[] args)
388 { 342 {
389 List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsInProgress().ToList(); 343 List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsInProgress().ToList();
@@ -928,16 +882,12 @@ namespace OpenSim.Framework.Servers
928 sb.Append("\n"); 882 sb.Append("\n");
929 } 883 }
930 884
931 sb.Append("\n"); 885 sb.Append(GetThreadPoolReport());
932 886
933 // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting 887 sb.Append("\n");
934 // zero active threads.
935 int totalThreads = Process.GetCurrentProcess().Threads.Count; 888 int totalThreads = Process.GetCurrentProcess().Threads.Count;
936 if (totalThreads > 0) 889 if (totalThreads > 0)
937 sb.AppendFormat("Total threads active: {0}\n\n", totalThreads); 890 sb.AppendFormat("Total process threads active: {0}\n\n", totalThreads);
938
939 sb.Append("Main threadpool (excluding script engine pools)\n");
940 sb.Append(GetThreadPoolReport());
941 891
942 return sb.ToString(); 892 return sb.ToString();
943 } 893 }
@@ -948,15 +898,46 @@ namespace OpenSim.Framework.Servers
948 /// <returns></returns> 898 /// <returns></returns>
949 public static string GetThreadPoolReport() 899 public static string GetThreadPoolReport()
950 { 900 {
901
902 StringBuilder sb = new StringBuilder();
903
904 // framework pool is alwasy active
905 int maxWorkers;
906 int minWorkers;
907 int curWorkers;
908 int maxComp;
909 int minComp;
910 int curComp;
911
912 try
913 {
914 ThreadPool.GetMaxThreads(out maxWorkers, out maxComp);
915 ThreadPool.GetMinThreads(out minWorkers, out minComp);
916 ThreadPool.GetAvailableThreads(out curWorkers, out curComp);
917 curWorkers = maxWorkers - curWorkers;
918 curComp = maxComp - curComp;
919
920 sb.Append("\nFramework main threadpool \n");
921 sb.AppendFormat("workers: {0} ({1} / {2})\n", curWorkers, maxWorkers, minWorkers);
922 sb.AppendFormat("Completion: {0} ({1} / {2})\n", curComp, maxComp, minComp);
923 }
924 catch { }
925
926 if (
927 Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
928 || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
929 {
930 sb.AppendFormat("\nThread pool used: Framework main threadpool\n");
931 return sb.ToString();
932 }
933
951 string threadPoolUsed = null; 934 string threadPoolUsed = null;
952 int maxThreads = 0; 935 int maxThreads = 0;
953 int minThreads = 0; 936 int minThreads = 0;
954 int allocatedThreads = 0; 937 int allocatedThreads = 0;
955 int inUseThreads = 0; 938 int inUseThreads = 0;
956 int waitingCallbacks = 0; 939 int waitingCallbacks = 0;
957 int completionPortThreads = 0;
958 940
959 StringBuilder sb = new StringBuilder();
960 if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) 941 if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
961 { 942 {
962 STPInfo stpi = Util.GetSmartThreadPoolInfo(); 943 STPInfo stpi = Util.GetSmartThreadPoolInfo();
@@ -972,22 +953,10 @@ namespace OpenSim.Framework.Servers
972 waitingCallbacks = stpi.WaitingCallbacks; 953 waitingCallbacks = stpi.WaitingCallbacks;
973 } 954 }
974 } 955 }
975 else if ( 956
976 Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
977 || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
978 {
979 threadPoolUsed = "BuiltInThreadPool";
980 ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
981 ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
982 int availableThreads;
983 ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
984 inUseThreads = maxThreads - availableThreads;
985 allocatedThreads = -1;
986 waitingCallbacks = -1;
987 }
988
989 if (threadPoolUsed != null) 957 if (threadPoolUsed != null)
990 { 958 {
959 sb.Append("\nThreadpool (excluding script engine pools)\n");
991 sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed); 960 sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
992 sb.AppendFormat("Max threads : {0}\n", maxThreads); 961 sb.AppendFormat("Max threads : {0}\n", maxThreads);
993 sb.AppendFormat("Min threads : {0}\n", minThreads); 962 sb.AppendFormat("Min threads : {0}\n", minThreads);
diff --git a/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs b/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs
index 480f2bb..68a1c78 100644
--- a/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs
+++ b/OpenSim/Framework/Servers/Tests/VersionInfoTests.cs
@@ -41,14 +41,5 @@ namespace OpenSim.Framework.Servers.Tests
41 { 41 {
42 Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.Version.Length," VersionInfo.Version string not " + VersionInfo.VERSIONINFO_VERSION_LENGTH + " chars."); 42 Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.Version.Length," VersionInfo.Version string not " + VersionInfo.VERSIONINFO_VERSION_LENGTH + " chars.");
43 } 43 }
44
45 [Test]
46 public void TestGetVersionStringLength()
47 {
48 foreach (VersionInfo.Flavour flavour in Enum.GetValues(typeof(VersionInfo.Flavour)))
49 {
50 Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.GetVersionString("0.0.0", flavour).Length, "0.0.0/" + flavour + " failed");
51 }
52 }
53 } 44 }
54} 45}
diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs
index 0ec24e6..c5c4ab3 100644
--- a/OpenSim/Framework/Util.cs
+++ b/OpenSim/Framework/Util.cs
@@ -30,6 +30,8 @@ using System.Collections;
30using System.Collections.Generic; 30using System.Collections.Generic;
31using System.Data; 31using System.Data;
32using System.Diagnostics; 32using System.Diagnostics;
33using System.Drawing;
34using System.Drawing.Imaging;
33using System.Globalization; 35using System.Globalization;
34using System.IO; 36using System.IO;
35using System.IO.Compression; 37using System.IO.Compression;
@@ -79,7 +81,9 @@ namespace OpenSim.Framework
79 81
80 FoldedMask = 0x0f, 82 FoldedMask = 0x0f,
81 83
82 // 84 FoldingShift = 13 , // number of bit shifts from normal perm to folded or back (same as Transfer shift below)
85 // when doing as a block
86
83 Transfer = 1 << 13, // 0x02000 87 Transfer = 1 << 13, // 0x02000
84 Modify = 1 << 14, // 0x04000 88 Modify = 1 << 14, // 0x04000
85 Copy = 1 << 15, // 0x08000 89 Copy = 1 << 15, // 0x08000
@@ -90,7 +94,9 @@ namespace OpenSim.Framework
90 // explicitly given 94 // explicitly given
91 All = 0x8e000, 95 All = 0x8e000,
92 AllAndExport = 0x9e000, 96 AllAndExport = 0x9e000,
93 AllEffective = 0x9e000 97 AllAndExportNoMod = 0x9a000,
98 AllEffective = 0x9e000,
99 UnfoldedMask = 0x1e000
94 } 100 }
95 101
96 /// <summary> 102 /// <summary>
@@ -153,12 +159,14 @@ namespace OpenSim.Framework
153 public static readonly int MAX_THREADPOOL_LEVEL = 3; 159 public static readonly int MAX_THREADPOOL_LEVEL = 3;
154 160
155 public static double TimeStampClockPeriodMS; 161 public static double TimeStampClockPeriodMS;
162 public static double TimeStampClockPeriod;
156 163
157 static Util() 164 static Util()
158 { 165 {
159 LogThreadPool = 0; 166 LogThreadPool = 0;
160 LogOverloads = true; 167 LogOverloads = true;
161 TimeStampClockPeriodMS = 1000.0D / (double)Stopwatch.Frequency; 168 TimeStampClockPeriod = 1.0D/ (double)Stopwatch.Frequency;
169 TimeStampClockPeriodMS = 1e3 * TimeStampClockPeriod;
162 m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero)); 170 m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero));
163 } 171 }
164 172
@@ -256,10 +264,7 @@ namespace OpenSim.Framework
256 /// <returns>The distance between the two vectors</returns> 264 /// <returns>The distance between the two vectors</returns>
257 public static double GetDistanceTo(Vector3 a, Vector3 b) 265 public static double GetDistanceTo(Vector3 a, Vector3 b)
258 { 266 {
259 float dx = a.X - b.X; 267 return Vector3.Distance(a,b);
260 float dy = a.Y - b.Y;
261 float dz = a.Z - b.Z;
262 return Math.Sqrt(dx * dx + dy * dy + dz * dz);
263 } 268 }
264 269
265 /// <summary> 270 /// <summary>
@@ -271,10 +276,7 @@ namespace OpenSim.Framework
271 /// <returns></returns> 276 /// <returns></returns>
272 public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount) 277 public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
273 { 278 {
274 float dx = a.X - b.X; 279 return Vector3.DistanceSquared(a,b) < (amount * amount);
275 float dy = a.Y - b.Y;
276 float dz = a.Z - b.Z;
277 return (dx*dx + dy*dy + dz*dz) < (amount*amount);
278 } 280 }
279 281
280 /// <summary> 282 /// <summary>
@@ -375,15 +377,17 @@ namespace OpenSim.Framework
375 get { return randomClass; } 377 get { return randomClass; }
376 } 378 }
377 379
380 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
378 public static ulong UIntsToLong(uint X, uint Y) 381 public static ulong UIntsToLong(uint X, uint Y)
379 { 382 {
380 return Utils.UIntsToLong(X, Y); 383 return ((ulong)X << 32) | (ulong)Y;
381 } 384 }
382 385
383 // Regions are identified with a 'handle' made up of its world coordinates packed into a ulong. 386 // Regions are identified with a 'handle' made up of its world coordinates packed into a ulong.
384 // Region handles are based on the coordinate of the region corner with lower X and Y 387 // Region handles are based on the coordinate of the region corner with lower X and Y
385 // var regions need more work than this to get that right corner from a generic world position 388 // var regions need more work than this to get that right corner from a generic world position
386 // this corner must be on a grid point 389 // this corner must be on a grid point
390 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
387 public static ulong RegionWorldLocToHandle(uint X, uint Y) 391 public static ulong RegionWorldLocToHandle(uint X, uint Y)
388 { 392 {
389 ulong handle = X & 0xffffff00; // make sure it matchs grid coord points. 393 ulong handle = X & 0xffffff00; // make sure it matchs grid coord points.
@@ -392,6 +396,7 @@ namespace OpenSim.Framework
392 return handle; 396 return handle;
393 } 397 }
394 398
399 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
395 public static ulong RegionGridLocToHandle(uint X, uint Y) 400 public static ulong RegionGridLocToHandle(uint X, uint Y)
396 { 401 {
397 ulong handle = X; 402 ulong handle = X;
@@ -400,12 +405,14 @@ namespace OpenSim.Framework
400 return handle; 405 return handle;
401 } 406 }
402 407
408 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
403 public static void RegionHandleToWorldLoc(ulong handle, out uint X, out uint Y) 409 public static void RegionHandleToWorldLoc(ulong handle, out uint X, out uint Y)
404 { 410 {
405 X = (uint)(handle >> 32); 411 X = (uint)(handle >> 32);
406 Y = (uint)(handle & 0xfffffffful); 412 Y = (uint)(handle & 0xfffffffful);
407 } 413 }
408 414
415 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
409 public static void RegionHandleToRegionLoc(ulong handle, out uint X, out uint Y) 416 public static void RegionHandleToRegionLoc(ulong handle, out uint X, out uint Y)
410 { 417 {
411 X = (uint)(handle >> 40) & 0x00ffffffu; // bring from higher half, divide by 256 and clean 418 X = (uint)(handle >> 40) & 0x00ffffffu; // bring from higher half, divide by 256 and clean
@@ -415,17 +422,20 @@ namespace OpenSim.Framework
415 422
416 // A region location can be 'world coordinates' (meters) or 'region grid coordinates' 423 // A region location can be 'world coordinates' (meters) or 'region grid coordinates'
417 // grid coordinates have a fixed step of 256m as defined by viewers 424 // grid coordinates have a fixed step of 256m as defined by viewers
425 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
418 public static uint WorldToRegionLoc(uint worldCoord) 426 public static uint WorldToRegionLoc(uint worldCoord)
419 { 427 {
420 return worldCoord >> 8; 428 return worldCoord >> 8;
421 } 429 }
422 430
423 // Convert a region's 'region grid coordinate' to its 'world coordinate'. 431 // Convert a region's 'region grid coordinate' to its 'world coordinate'.
432 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
424 public static uint RegionToWorldLoc(uint regionCoord) 433 public static uint RegionToWorldLoc(uint regionCoord)
425 { 434 {
426 return regionCoord << 8; 435 return regionCoord << 8;
427 } 436 }
428 437
438
429 public static bool checkServiceURI(string uristr, out string serviceURI) 439 public static bool checkServiceURI(string uristr, out string serviceURI)
430 { 440 {
431 serviceURI = string.Empty; 441 serviceURI = string.Empty;
@@ -569,14 +579,15 @@ namespace OpenSim.Framework
569 } 579 }
570 580
571 // Clamp the maximum magnitude of a vector 581 // Clamp the maximum magnitude of a vector
582 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
572 public static Vector3 ClampV(Vector3 x, float max) 583 public static Vector3 ClampV(Vector3 x, float max)
573 { 584 {
574 float lenSq = x.LengthSquared(); 585 float lenSq = x.LengthSquared();
575 if (lenSq > (max * max)) 586 if (lenSq > (max * max))
576 { 587 {
577 x = x / x.Length() * max; 588 lenSq = max / (float)Math.Sqrt(lenSq);
589 x = x * lenSq;
578 } 590 }
579
580 return x; 591 return x;
581 } 592 }
582 593
@@ -665,6 +676,7 @@ namespace OpenSim.Framework
665 public static string GetFormattedXml(string rawXml) 676 public static string GetFormattedXml(string rawXml)
666 { 677 {
667 XmlDocument xd = new XmlDocument(); 678 XmlDocument xd = new XmlDocument();
679
668 xd.LoadXml(rawXml); 680 xd.LoadXml(rawXml);
669 681
670 StringBuilder sb = new StringBuilder(); 682 StringBuilder sb = new StringBuilder();
@@ -818,8 +830,8 @@ namespace OpenSim.Framework
818 830
819 private static byte[] ComputeMD5Hash(string data, Encoding encoding) 831 private static byte[] ComputeMD5Hash(string data, Encoding encoding)
820 { 832 {
821 MD5 md5 = MD5.Create(); 833 using(MD5 md5 = MD5.Create())
822 return md5.ComputeHash(encoding.GetBytes(data)); 834 return md5.ComputeHash(encoding.GetBytes(data));
823 } 835 }
824 836
825 /// <summary> 837 /// <summary>
@@ -987,6 +999,8 @@ namespace OpenSim.Framework
987 return output.ToString(); 999 return output.ToString();
988 } 1000 }
989 1001
1002 private static ExpiringCache<string,IPAddress> dnscache = new ExpiringCache<string, IPAddress>();
1003
990 /// <summary> 1004 /// <summary>
991 /// Converts a URL to a IPAddress 1005 /// Converts a URL to a IPAddress
992 /// </summary> 1006 /// </summary>
@@ -1004,38 +1018,128 @@ namespace OpenSim.Framework
1004 /// <returns>An IP address, or null</returns> 1018 /// <returns>An IP address, or null</returns>
1005 public static IPAddress GetHostFromDNS(string dnsAddress) 1019 public static IPAddress GetHostFromDNS(string dnsAddress)
1006 { 1020 {
1007 // Is it already a valid IP? No need to look it up. 1021 if(String.IsNullOrWhiteSpace(dnsAddress))
1008 IPAddress ipa; 1022 return null;
1009 if (IPAddress.TryParse(dnsAddress, out ipa))
1010 return ipa;
1011 1023
1012 IPAddress[] hosts = null; 1024 IPAddress ia = null;
1025 if(dnscache.TryGetValue(dnsAddress, out ia) && ia != null)
1026 {
1027 dnscache.AddOrUpdate(dnsAddress, ia, 300);
1028 return ia;
1029 }
1030
1031 ia = null;
1032 // If it is already an IP, don't let GetHostEntry see it
1033 if (IPAddress.TryParse(dnsAddress, out ia) && ia != null)
1034 {
1035 if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
1036 return null;
1037 dnscache.AddOrUpdate(dnsAddress, ia, 300);
1038 return ia;
1039 }
1013 1040
1014 // Not an IP, lookup required 1041 IPHostEntry IPH;
1015 try 1042 try
1016 { 1043 {
1017 hosts = Dns.GetHostEntry(dnsAddress).AddressList; 1044 IPH = Dns.GetHostEntry(dnsAddress);
1018 } 1045 }
1019 catch (Exception e) 1046 catch // (SocketException e)
1047 {
1048 return null;
1049 }
1050
1051 if(IPH == null || IPH.AddressList.Length == 0)
1052 return null;
1053
1054 ia = null;
1055 foreach (IPAddress Adr in IPH.AddressList)
1020 { 1056 {
1021 m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e); 1057 if (ia == null)
1058 ia = Adr;
1059
1060 if (Adr.AddressFamily == AddressFamily.InterNetwork)
1061 {
1062 ia = Adr;
1063 break;
1064 }
1065 }
1066 if(ia != null)
1067 dnscache.AddOrUpdate(dnsAddress, ia, 300);
1068 return ia;
1069 }
1022 1070
1023 // Still going to throw the exception on for now, since this was what was happening in the first place 1071 public static IPEndPoint getEndPoint(IPAddress ia, int port)
1024 throw e; 1072 {
1073 if(ia == null)
1074 return null;
1075
1076 IPEndPoint newEP = null;
1077 try
1078 {
1079 newEP = new IPEndPoint(ia, port);
1080 }
1081 catch
1082 {
1083 newEP = null;
1084 }
1085 return newEP;
1086 }
1087
1088 public static IPEndPoint getEndPoint(string hostname, int port)
1089 {
1090 if(String.IsNullOrWhiteSpace(hostname))
1091 return null;
1092
1093 IPAddress ia = null;
1094 if(dnscache.TryGetValue(hostname, out ia) && ia != null)
1095 {
1096 dnscache.AddOrUpdate(hostname, ia, 300);
1097 return getEndPoint(ia, port);
1098 }
1099
1100 ia = null;
1101
1102 // If it is already an IP, don't let GetHostEntry see it
1103 if (IPAddress.TryParse(hostname, out ia) && ia != null)
1104 {
1105 if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
1106 return null;
1107
1108 dnscache.AddOrUpdate(hostname, ia, 300);
1109 return getEndPoint(ia, port);
1110 }
1111
1112
1113 IPHostEntry IPH;
1114 try
1115 {
1116 IPH = Dns.GetHostEntry(hostname);
1117 }
1118 catch // (SocketException e)
1119 {
1120 return null;
1025 } 1121 }
1026 1122
1027 foreach (IPAddress host in hosts) 1123 if(IPH == null || IPH.AddressList.Length == 0)
1124 return null;
1125
1126 ia = null;
1127 foreach (IPAddress Adr in IPH.AddressList)
1028 { 1128 {
1029 if (host.AddressFamily == AddressFamily.InterNetwork) 1129 if (ia == null)
1130 ia = Adr;
1131
1132 if (Adr.AddressFamily == AddressFamily.InterNetwork)
1030 { 1133 {
1031 return host; 1134 ia = Adr;
1135 break;
1032 } 1136 }
1033 } 1137 }
1034 1138
1035 if (hosts.Length > 0) 1139 if(ia != null)
1036 return hosts[0]; 1140 dnscache.AddOrUpdate(hostname, ia, 300);
1037 1141
1038 return null; 1142 return getEndPoint(ia,port);
1039 } 1143 }
1040 1144
1041 public static Uri GetURI(string protocol, string hostname, int port, string path) 1145 public static Uri GetURI(string protocol, string hostname, int port, string path)
@@ -1815,7 +1919,9 @@ namespace OpenSim.Framework
1815 string ru = String.Empty; 1919 string ru = String.Empty;
1816 1920
1817 if (Environment.OSVersion.Platform == PlatformID.Unix) 1921 if (Environment.OSVersion.Platform == PlatformID.Unix)
1818 ru = "Unix/Mono"; 1922 {
1923 ru = "Unix/Mono";
1924 }
1819 else 1925 else
1820 if (Environment.OSVersion.Platform == PlatformID.MacOSX) 1926 if (Environment.OSVersion.Platform == PlatformID.MacOSX)
1821 ru = "OSX/Mono"; 1927 ru = "OSX/Mono";
@@ -2125,9 +2231,9 @@ namespace OpenSim.Framework
2125 // might have gotten an oversized array even after the string trim 2231 // might have gotten an oversized array even after the string trim
2126 byte[] data = UTF8.GetBytes(str); 2232 byte[] data = UTF8.GetBytes(str);
2127 2233
2128 if (data.Length > 256) 2234 if (data.Length > 255) //play safe
2129 { 2235 {
2130 int cut = 255; 2236 int cut = 254;
2131 if((data[cut] & 0x80 ) != 0 ) 2237 if((data[cut] & 0x80 ) != 0 )
2132 { 2238 {
2133 while(cut > 0 && (data[cut] & 0xc0) != 0xc0) 2239 while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
@@ -2229,7 +2335,7 @@ namespace OpenSim.Framework
2229 2335
2230 if (data.Length > MaxLength) 2336 if (data.Length > MaxLength)
2231 { 2337 {
2232 int cut = MaxLength -1 ; 2338 int cut = MaxLength - 1 ;
2233 if((data[cut] & 0x80 ) != 0 ) 2339 if((data[cut] & 0x80 ) != 0 )
2234 { 2340 {
2235 while(cut > 0 && (data[cut] & 0xc0) != 0xc0) 2341 while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
@@ -2396,8 +2502,9 @@ namespace OpenSim.Framework
2396 public bool Running { get; set; } 2502 public bool Running { get; set; }
2397 public bool Aborted { get; set; } 2503 public bool Aborted { get; set; }
2398 private int started; 2504 private int started;
2505 public bool DoTimeout;
2399 2506
2400 public ThreadInfo(long threadFuncNum, string context) 2507 public ThreadInfo(long threadFuncNum, string context, bool dotimeout = true)
2401 { 2508 {
2402 ThreadFuncNum = threadFuncNum; 2509 ThreadFuncNum = threadFuncNum;
2403 this.context = context; 2510 this.context = context;
@@ -2405,6 +2512,7 @@ namespace OpenSim.Framework
2405 Thread = null; 2512 Thread = null;
2406 Running = false; 2513 Running = false;
2407 Aborted = false; 2514 Aborted = false;
2515 DoTimeout = dotimeout;
2408 } 2516 }
2409 2517
2410 public void Started() 2518 public void Started()
@@ -2475,7 +2583,7 @@ namespace OpenSim.Framework
2475 foreach (KeyValuePair<long, ThreadInfo> entry in activeThreads) 2583 foreach (KeyValuePair<long, ThreadInfo> entry in activeThreads)
2476 { 2584 {
2477 ThreadInfo t = entry.Value; 2585 ThreadInfo t = entry.Value;
2478 if (t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT)) 2586 if (t.DoTimeout && t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
2479 { 2587 {
2480 m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace()); 2588 m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace());
2481 t.Abort(); 2589 t.Abort();
@@ -2516,10 +2624,10 @@ namespace OpenSim.Framework
2516 FireAndForget(callback, obj, null); 2624 FireAndForget(callback, obj, null);
2517 } 2625 }
2518 2626
2519 public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context) 2627 public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context, bool dotimeout = true)
2520 { 2628 {
2521 Interlocked.Increment(ref numTotalThreadFuncsCalled); 2629 Interlocked.Increment(ref numTotalThreadFuncsCalled);
2522 2630/*
2523 if (context != null) 2631 if (context != null)
2524 { 2632 {
2525 if (!m_fireAndForgetCallsMade.ContainsKey(context)) 2633 if (!m_fireAndForgetCallsMade.ContainsKey(context))
@@ -2532,13 +2640,13 @@ namespace OpenSim.Framework
2532 else 2640 else
2533 m_fireAndForgetCallsInProgress[context]++; 2641 m_fireAndForgetCallsInProgress[context]++;
2534 } 2642 }
2535 2643*/
2536 WaitCallback realCallback; 2644 WaitCallback realCallback;
2537 2645
2538 bool loggingEnabled = LogThreadPool > 0; 2646 bool loggingEnabled = LogThreadPool > 0;
2539 2647
2540 long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum); 2648 long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
2541 ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context); 2649 ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context, dotimeout);
2542 2650
2543 if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest) 2651 if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
2544 { 2652 {
@@ -2549,8 +2657,8 @@ namespace OpenSim.Framework
2549 Culture.SetCurrentCulture(); 2657 Culture.SetCurrentCulture();
2550 callback(o); 2658 callback(o);
2551 2659
2552 if (context != null) 2660// if (context != null)
2553 m_fireAndForgetCallsInProgress[context]--; 2661// m_fireAndForgetCallsInProgress[context]--;
2554 }; 2662 };
2555 } 2663 }
2556 else 2664 else
@@ -2574,9 +2682,8 @@ namespace OpenSim.Framework
2574 2682
2575 callback(o); 2683 callback(o);
2576 } 2684 }
2577 catch (ThreadAbortException e) 2685 catch (ThreadAbortException)
2578 { 2686 {
2579 m_log.Error(string.Format("Aborted threadfunc {0} ", threadFuncNum), e);
2580 } 2687 }
2581 catch (Exception e) 2688 catch (Exception e)
2582 { 2689 {
@@ -2591,8 +2698,8 @@ namespace OpenSim.Framework
2591 if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread) 2698 if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
2592 m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed())); 2699 m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed()));
2593 2700
2594 if (context != null) 2701// if (context != null)
2595 m_fireAndForgetCallsInProgress[context]--; 2702// m_fireAndForgetCallsInProgress[context]--;
2596 } 2703 }
2597 }; 2704 };
2598 } 2705 }
@@ -2758,6 +2865,12 @@ namespace OpenSim.Framework
2758 /// <returns>The stack trace, or null if failed to get it</returns> 2865 /// <returns>The stack trace, or null if failed to get it</returns>
2759 private static StackTrace GetStackTrace(Thread targetThread) 2866 private static StackTrace GetStackTrace(Thread targetThread)
2760 { 2867 {
2868
2869 return null;
2870/*
2871 not only this does not work on mono but it is not longer recomended on windows.
2872 can cause deadlocks etc.
2873
2761 if (IsPlatformMono) 2874 if (IsPlatformMono)
2762 { 2875 {
2763 // This doesn't work in Mono 2876 // This doesn't work in Mono
@@ -2820,6 +2933,7 @@ namespace OpenSim.Framework
2820 // Signal the fallack-thread to stop 2933 // Signal the fallack-thread to stop
2821 exitedSafely.Set(); 2934 exitedSafely.Set();
2822 } 2935 }
2936*/
2823 } 2937 }
2824#pragma warning restore 0618 2938#pragma warning restore 0618
2825 2939
@@ -2849,6 +2963,16 @@ namespace OpenSim.Framework
2849 return stpi; 2963 return stpi;
2850 } 2964 }
2851 2965
2966 public static void StopThreadPool()
2967 {
2968 if (m_ThreadPool == null)
2969 return;
2970 SmartThreadPool pool = m_ThreadPool;
2971 m_ThreadPool = null;
2972
2973 try { pool.Shutdown(); } catch {}
2974 }
2975
2852 #endregion FireAndForget Threading Pattern 2976 #endregion FireAndForget Threading Pattern
2853 2977
2854 /// <summary> 2978 /// <summary>
@@ -2862,6 +2986,7 @@ namespace OpenSim.Framework
2862 { 2986 {
2863 return Environment.TickCount & EnvironmentTickCountMask; 2987 return Environment.TickCount & EnvironmentTickCountMask;
2864 } 2988 }
2989
2865 const Int32 EnvironmentTickCountMask = 0x3fffffff; 2990 const Int32 EnvironmentTickCountMask = 0x3fffffff;
2866 2991
2867 /// <summary> 2992 /// <summary>
@@ -2906,11 +3031,36 @@ namespace OpenSim.Framework
2906 return tcA - tcB; 3031 return tcA - tcB;
2907 } 3032 }
2908 3033
3034 public static long GetPhysicalMemUse()
3035 {
3036 return System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
3037 }
3038
2909 // returns a timestamp in ms as double 3039 // returns a timestamp in ms as double
2910 // using the time resolution avaiable to StopWatch 3040 // using the time resolution avaiable to StopWatch
3041 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
3042 public static double GetTimeStamp()
3043 {
3044 return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
3045 }
3046
3047 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
2911 public static double GetTimeStampMS() 3048 public static double GetTimeStampMS()
2912 { 3049 {
2913 return (double)Stopwatch.GetTimestamp() * TimeStampClockPeriodMS; 3050 return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
3051 }
3052
3053 // doing math in ticks is usefull to avoid loss of resolution
3054 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
3055 public static long GetTimeStampTicks()
3056 {
3057 return Stopwatch.GetTimestamp();
3058 }
3059
3060 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
3061 public static double TimeStampTicksToMS(long ticks)
3062 {
3063 return ticks * TimeStampClockPeriodMS;
2914 } 3064 }
2915 3065
2916 /// <summary> 3066 /// <summary>
@@ -3294,6 +3444,34 @@ namespace OpenSim.Framework
3294 m_log.ErrorFormat("{0} Failed XML ({1} bytes) = {2}", message, length, xml); 3444 m_log.ErrorFormat("{0} Failed XML ({1} bytes) = {2}", message, length, xml);
3295 } 3445 }
3296 3446
3447 /// <summary>
3448 /// Performs a high quality image resize
3449 /// </summary>
3450 /// <param name="image">Image to resize</param>
3451 /// <param name="width">New width</param>
3452 /// <param name="height">New height</param>
3453 /// <returns>Resized image</returns>
3454 public static Bitmap ResizeImageSolid(Image image, int width, int height)
3455 {
3456 Bitmap result = new Bitmap(width, height, PixelFormat.Format24bppRgb);
3457
3458 using (ImageAttributes atrib = new ImageAttributes())
3459 using (Graphics graphics = Graphics.FromImage(result))
3460 {
3461 atrib.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
3462 atrib.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
3463 graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
3464 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
3465 graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
3466 graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
3467
3468 graphics.DrawImage(image,new Rectangle(0,0, result.Width, result.Height),
3469 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, atrib);
3470 }
3471
3472 return result;
3473 }
3474
3297 } 3475 }
3298 3476
3299/* don't like this code 3477/* don't like this code
@@ -3458,5 +3636,6 @@ namespace OpenSim.Framework
3458 { 3636 {
3459 rng.GetBytes(buff); 3637 rng.GetBytes(buff);
3460 } 3638 }
3639
3461 } 3640 }
3462} 3641}
diff --git a/OpenSim/Framework/VersionInfo.cs b/OpenSim/Framework/VersionInfo.cs
index 1e6efe5..eac5aae 100644
--- a/OpenSim/Framework/VersionInfo.cs
+++ b/OpenSim/Framework/VersionInfo.cs
@@ -30,9 +30,9 @@ namespace OpenSim
30 public class VersionInfo 30 public class VersionInfo
31 { 31 {
32 public const string VersionNumber = "0.9.1.0"; 32 public const string VersionNumber = "0.9.1.0";
33 public const string AssemblyVersionNumber = "0.9.1.*"; 33 public const string AssemblyVersionNumber = "0.9.1.0";
34 34
35 private const Flavour VERSION_FLAVOUR = Flavour.Dev; 35 public const Flavour VERSION_FLAVOUR = Flavour.Dev;
36 36
37 public enum Flavour 37 public enum Flavour
38 { 38 {
@@ -53,7 +53,7 @@ namespace OpenSim
53 53
54 public static string GetVersionString(string versionNumber, Flavour flavour) 54 public static string GetVersionString(string versionNumber, Flavour flavour)
55 { 55 {
56 string versionString = "OpenSim " + versionNumber + " " + flavour; 56 string versionString = "OpenSim " + versionNumber + " Snail " + flavour;
57 return versionString.PadRight(VERSIONINFO_VERSION_LENGTH); 57 return versionString.PadRight(VERSIONINFO_VERSION_LENGTH);
58 } 58 }
59 59
diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs
index 12f58fe..417e1cf 100644
--- a/OpenSim/Framework/WebUtil.cs
+++ b/OpenSim/Framework/WebUtil.cs
@@ -33,7 +33,6 @@ using System.Globalization;
33using System.IO; 33using System.IO;
34using System.IO.Compression; 34using System.IO.Compression;
35using System.Net; 35using System.Net;
36using System.Net.Security;
37using System.Reflection; 36using System.Reflection;
38using System.Text; 37using System.Text;
39using System.Web; 38using System.Web;
@@ -43,9 +42,9 @@ using System.Xml.Linq;
43using log4net; 42using log4net;
44using Nwc.XmlRpc; 43using Nwc.XmlRpc;
45using OpenMetaverse.StructuredData; 44using OpenMetaverse.StructuredData;
45using OpenSim.Framework.ServiceAuth;
46using XMLResponseHelper = OpenSim.Framework.SynchronousRestObjectRequester.XMLResponseHelper; 46using XMLResponseHelper = OpenSim.Framework.SynchronousRestObjectRequester.XMLResponseHelper;
47 47
48using OpenSim.Framework.ServiceAuth;
49 48
50namespace OpenSim.Framework 49namespace OpenSim.Framework
51{ 50{
@@ -72,11 +71,6 @@ namespace OpenSim.Framework
72 public static int RequestNumber { get; set; } 71 public static int RequestNumber { get; set; }
73 72
74 /// <summary> 73 /// <summary>
75 /// Control where OSD requests should be serialized per endpoint.
76 /// </summary>
77 public static bool SerializeOSDRequestsPerEndpoint { get; set; }
78
79 /// <summary>
80 /// this is the header field used to communicate the local request id 74 /// this is the header field used to communicate the local request id
81 /// used for performance and debugging 75 /// used for performance and debugging
82 /// </summary> 76 /// </summary>
@@ -98,31 +92,6 @@ namespace OpenSim.Framework
98 /// </remarks> 92 /// </remarks>
99 public const int MaxRequestDiagLength = 200; 93 public const int MaxRequestDiagLength = 200;
100 94
101 /// <summary>
102 /// Dictionary of end points
103 /// </summary>
104 private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>();
105
106 private static object EndPointLock(string url)
107 {
108 System.Uri uri = new System.Uri(url);
109 string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port);
110
111 lock (m_endpointSerializer)
112 {
113 object eplock = null;
114
115 if (! m_endpointSerializer.TryGetValue(endpoint,out eplock))
116 {
117 eplock = new object();
118 m_endpointSerializer.Add(endpoint,eplock);
119 // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint);
120 }
121
122 return eplock;
123 }
124 }
125
126 #region JSONRequest 95 #region JSONRequest
127 96
128 /// <summary> 97 /// <summary>
@@ -154,21 +123,6 @@ namespace OpenSim.Framework
154 return ServiceOSDRequest(url, null, "GET", timeout, false, false); 123 return ServiceOSDRequest(url, null, "GET", timeout, false, false);
155 } 124 }
156 125
157 public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc)
158 {
159 if (SerializeOSDRequestsPerEndpoint)
160 {
161 lock (EndPointLock(url))
162 {
163 return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc);
164 }
165 }
166 else
167 {
168 return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc);
169 }
170 }
171
172 public static void LogOutgoingDetail(Stream outputStream) 126 public static void LogOutgoingDetail(Stream outputStream)
173 { 127 {
174 LogOutgoingDetail("", outputStream); 128 LogOutgoingDetail("", outputStream);
@@ -222,7 +176,7 @@ namespace OpenSim.Framework
222 LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input); 176 LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input);
223 } 177 }
224 178
225 private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) 179 public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc)
226 { 180 {
227 int reqnum = RequestNumber++; 181 int reqnum = RequestNumber++;
228 182
@@ -245,7 +199,7 @@ namespace OpenSim.Framework
245 request.Timeout = timeout; 199 request.Timeout = timeout;
246 request.KeepAlive = false; 200 request.KeepAlive = false;
247 request.MaximumAutomaticRedirections = 10; 201 request.MaximumAutomaticRedirections = 10;
248 request.ReadWriteTimeout = timeout / 4; 202 request.ReadWriteTimeout = timeout / 2;
249 request.Headers[OSHeaderRequestID] = reqnum.ToString(); 203 request.Headers[OSHeaderRequestID] = reqnum.ToString();
250 204
251 // If there is some input, write it into the request 205 // If there is some input, write it into the request
@@ -422,14 +376,6 @@ namespace OpenSim.Framework
422 376
423 public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout) 377 public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
424 { 378 {
425 lock (EndPointLock(url))
426 {
427 return ServiceFormRequestWorker(url,data,timeout);
428 }
429 }
430
431 private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout)
432 {
433 int reqnum = RequestNumber++; 379 int reqnum = RequestNumber++;
434 string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown"; 380 string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
435 381
@@ -449,7 +395,7 @@ namespace OpenSim.Framework
449 request.Timeout = timeout; 395 request.Timeout = timeout;
450 request.KeepAlive = false; 396 request.KeepAlive = false;
451 request.MaximumAutomaticRedirections = 10; 397 request.MaximumAutomaticRedirections = 10;
452 request.ReadWriteTimeout = timeout / 4; 398 request.ReadWriteTimeout = timeout / 2;
453 request.Headers[OSHeaderRequestID] = reqnum.ToString(); 399 request.Headers[OSHeaderRequestID] = reqnum.ToString();
454 400
455 if (data != null) 401 if (data != null)
@@ -1315,18 +1261,24 @@ namespace OpenSim.Framework
1315 { 1261 {
1316 if (hwr.StatusCode == HttpStatusCode.NotFound) 1262 if (hwr.StatusCode == HttpStatusCode.NotFound)
1317 return deserial; 1263 return deserial;
1264
1318 if (hwr.StatusCode == HttpStatusCode.Unauthorized) 1265 if (hwr.StatusCode == HttpStatusCode.Unauthorized)
1319 { 1266 {
1320 m_log.Error(string.Format( 1267 m_log.ErrorFormat("[SynchronousRestObjectRequester]: Web request {0} requires authentication",
1321 "[SynchronousRestObjectRequester]: Web request {0} requires authentication ", 1268 requestUrl);
1322 requestUrl)); 1269 }
1323 return deserial; 1270 else
1271 {
1272 m_log.WarnFormat("[SynchronousRestObjectRequester]: Web request {0} returned error: {1}",
1273 requestUrl, hwr.StatusCode);
1324 } 1274 }
1325 } 1275 }
1326 else 1276 else
1327 m_log.Error(string.Format( 1277 m_log.ErrorFormat(
1328 "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} ", 1278 "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} {3}",
1329 verb, requestUrl, typeof(TResponse).ToString()), e); 1279 verb, requestUrl, typeof(TResponse).ToString(), e.Message);
1280
1281 return deserial;
1330 } 1282 }
1331 } 1283 }
1332 catch (System.InvalidOperationException) 1284 catch (System.InvalidOperationException)
@@ -1381,16 +1333,42 @@ namespace OpenSim.Framework
1381 public static TResponse LogAndDeserialize<TRequest, TResponse>(int reqnum, Stream respStream, long contentLength) 1333 public static TResponse LogAndDeserialize<TRequest, TResponse>(int reqnum, Stream respStream, long contentLength)
1382 { 1334 {
1383 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); 1335 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
1384
1385 if (WebUtil.DebugLevel >= 5) 1336 if (WebUtil.DebugLevel >= 5)
1386 { 1337 {
1387 byte[] data = new byte[contentLength]; 1338 const int blockLength = 4096;
1388 Util.ReadStream(respStream, data); 1339 byte[] dataBuffer = new byte[blockLength];
1340 int curcount;
1341 using (MemoryStream ms = new MemoryStream(4 * blockLength))
1342 {
1343 if(contentLength == -1)
1344 {
1345 while (true)
1346 {
1347 curcount = respStream.Read(dataBuffer, 0, blockLength);
1348 if (curcount <= 0)
1349 break;
1350 ms.Write(dataBuffer, 0, curcount);
1351 }
1352 }
1353 else
1354 {
1355 int remaining = (int)contentLength;
1356 while (remaining > 0)
1357 {
1358 curcount = respStream.Read(dataBuffer, 0, remaining);
1359 if (curcount <= 0)
1360 throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
1361 ms.Write(dataBuffer, 0, curcount);
1362 remaining -= curcount;
1363 }
1364 }
1389 1365
1390 WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(data)); 1366 dataBuffer = ms.ToArray();
1367 WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(dataBuffer));
1391 1368
1392 using (MemoryStream temp = new MemoryStream(data)) 1369 ms.Position = 0;
1393 return (TResponse)deserializer.Deserialize(temp); 1370 return (TResponse)deserializer.Deserialize(ms);
1371 }
1394 } 1372 }
1395 else 1373 else
1396 { 1374 {
@@ -1474,6 +1452,5 @@ namespace OpenSim.Framework
1474 } 1452 }
1475 } 1453 }
1476 } 1454 }
1477
1478 } 1455 }
1479} 1456}