aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/CoreModules/Communications
diff options
context:
space:
mode:
authorDr Scofield2009-02-10 13:10:57 +0000
committerDr Scofield2009-02-10 13:10:57 +0000
commit180be7de07014aa33bc6066f12a0819b731c1c9d (patch)
tree3aa13af3cda4b808fa9453655875327699b61311 /OpenSim/Region/CoreModules/Communications
parentStopgap measure: To use gridlaunch, or GUI, start opensim with (diff)
downloadopensim-SC_OLD-180be7de07014aa33bc6066f12a0819b731c1c9d.zip
opensim-SC_OLD-180be7de07014aa33bc6066f12a0819b731c1c9d.tar.gz
opensim-SC_OLD-180be7de07014aa33bc6066f12a0819b731c1c9d.tar.bz2
opensim-SC_OLD-180be7de07014aa33bc6066f12a0819b731c1c9d.tar.xz
this is step 2 of 2 of the OpenSim.Region.Environment refactor.
NOTHING has been deleted or moved off to forge at this point. what has happened is that OpenSim.Region.Environment.Modules has been split in two: - OpenSim.Region.CoreModules: all those modules that are either directly or indirectly referenced from other OpenSim packages, or that provide functionality that the OpenSim developer community considers core functionality: CoreModules/Agent/AssetTransaction CoreModules/Agent/Capabilities CoreModules/Agent/TextureDownload CoreModules/Agent/TextureSender CoreModules/Agent/TextureSender/Tests CoreModules/Agent/Xfer CoreModules/Avatar/AvatarFactory CoreModules/Avatar/Chat/ChatModule CoreModules/Avatar/Combat CoreModules/Avatar/Currency/SampleMoney CoreModules/Avatar/Dialog CoreModules/Avatar/Friends CoreModules/Avatar/Gestures CoreModules/Avatar/Groups CoreModules/Avatar/InstantMessage CoreModules/Avatar/Inventory CoreModules/Avatar/Inventory/Archiver CoreModules/Avatar/Inventory/Transfer CoreModules/Avatar/Lure CoreModules/Avatar/ObjectCaps CoreModules/Avatar/Profiles CoreModules/Communications/Local CoreModules/Communications/REST CoreModules/Framework/EventQueue CoreModules/Framework/InterfaceCommander CoreModules/Hypergrid CoreModules/InterGrid CoreModules/Scripting/DynamicTexture CoreModules/Scripting/EMailModules CoreModules/Scripting/HttpRequest CoreModules/Scripting/LoadImageURL CoreModules/Scripting/VectorRender CoreModules/Scripting/WorldComm CoreModules/Scripting/XMLRPC CoreModules/World/Archiver CoreModules/World/Archiver/Tests CoreModules/World/Estate CoreModules/World/Land CoreModules/World/Permissions CoreModules/World/Serialiser CoreModules/World/Sound CoreModules/World/Sun CoreModules/World/Terrain CoreModules/World/Terrain/DefaultEffects CoreModules/World/Terrain/DefaultEffects/bin CoreModules/World/Terrain/DefaultEffects/bin/Debug CoreModules/World/Terrain/Effects CoreModules/World/Terrain/FileLoaders CoreModules/World/Terrain/FloodBrushes CoreModules/World/Terrain/PaintBrushes CoreModules/World/Terrain/Tests CoreModules/World/Vegetation CoreModules/World/Wind CoreModules/World/WorldMap - OpenSim.Region.OptionalModules: all those modules that are not core modules: OptionalModules/Avatar/Chat/IRC-stuff OptionalModules/Avatar/Concierge OptionalModules/Avatar/Voice/AsterixVoice OptionalModules/Avatar/Voice/SIPVoice OptionalModules/ContentManagementSystem OptionalModules/Grid/Interregion OptionalModules/Python OptionalModules/SvnSerialiser OptionalModules/World/NPC OptionalModules/World/TreePopulator
Diffstat (limited to 'OpenSim/Region/CoreModules/Communications')
-rw-r--r--OpenSim/Region/CoreModules/Communications/Local/LocalInterregionComms.cs244
-rw-r--r--OpenSim/Region/CoreModules/Communications/REST/RESTInterregionComms.cs960
2 files changed, 1204 insertions, 0 deletions
diff --git a/OpenSim/Region/CoreModules/Communications/Local/LocalInterregionComms.cs b/OpenSim/Region/CoreModules/Communications/Local/LocalInterregionComms.cs
new file mode 100644
index 0000000..3a9df4a
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Communications/Local/LocalInterregionComms.cs
@@ -0,0 +1,244 @@
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 OpenSim 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 */
27using System;
28using System.Collections;
29using System.Collections.Generic;
30using System.Net;
31using System.Net.Sockets;
32using System.Reflection;
33using System.Threading;
34using System.Xml;
35using OpenMetaverse;
36using log4net;
37using Nini.Config;
38using Nwc.XmlRpc;
39using OpenSim.Framework;
40using OpenSim.Framework.Communications.Cache;
41using OpenSim.Region.Framework.Interfaces;
42using OpenSim.Region.Framework.Scenes;
43
44namespace OpenSim.Region.CoreModules.Communications.Local
45{
46 public class LocalInterregionComms : IRegionModule, IInterregionCommsOut, IInterregionCommsIn
47 {
48 private bool m_enabled = false;
49
50 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51 private List<Scene> m_sceneList = new List<Scene>();
52
53 #region Events
54 public event ChildAgentUpdateReceived OnChildAgentUpdate;
55
56 #endregion /* Events */
57
58 #region IRegionModule
59
60 public void Initialise(Scene scene, IConfigSource config)
61 {
62 if (m_sceneList.Count == 0)
63 {
64 IConfig startupConfig = config.Configs["Communications"];
65
66 if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTCommms") == "LocalComms"))
67 {
68 m_log.Debug("[LOCAL COMMS]: Enabling InterregionComms LocalComms module");
69 m_enabled = true;
70 }
71 }
72
73 if (!m_enabled)
74 return;
75
76 Init(scene);
77 }
78
79 public void PostInitialise()
80 {
81 }
82
83 public void Close()
84 {
85 }
86
87 public string Name
88 {
89 get { return "LocalInterregionCommsModule"; }
90 }
91
92 public bool IsSharedModule
93 {
94 get { return true; }
95 }
96 /// <summary>
97 /// Can be called from other modules.
98 /// </summary>
99 /// <param name="scene"></param>
100 public void Init(Scene scene)
101 {
102 if (!m_sceneList.Contains(scene))
103 {
104 lock (m_sceneList)
105 {
106 m_sceneList.Add(scene);
107 if (m_enabled)
108 scene.RegisterModuleInterface<IInterregionCommsOut>(this);
109 scene.RegisterModuleInterface<IInterregionCommsIn>(this);
110 }
111
112 }
113 }
114
115 #endregion /* IRegionModule */
116
117 #region IInterregionComms
118
119 /**
120 * Agent-related communications
121 */
122
123 public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit)
124 {
125 foreach (Scene s in m_sceneList)
126 {
127 if (s.RegionInfo.RegionHandle == regionHandle)
128 {
129// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendCreateChildAgent", regionHandle);
130 s.NewUserConnection(aCircuit);
131 return true;
132 }
133 }
134
135// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for SendCreateChildAgent", regionHandle);
136 return false;
137 }
138
139 public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
140 {
141 foreach (Scene s in m_sceneList)
142 {
143 if (s.RegionInfo.RegionHandle == regionHandle)
144 {
145 //m_log.DebugFormat(
146 // "[LOCAL COMMS]: Found region {0} {1} to send ChildAgentUpdate",
147 // s.RegionInfo.RegionName, regionHandle);
148
149 s.IncomingChildAgentDataUpdate(cAgentData);
150 return true;
151 }
152 }
153
154// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle);
155 return false;
156 }
157
158 public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
159 {
160 foreach (Scene s in m_sceneList)
161 {
162 if (s.RegionInfo.RegionHandle == regionHandle)
163 {
164 //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
165 s.IncomingChildAgentDataUpdate(cAgentData);
166 return true;
167 }
168 }
169 //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
170 return false;
171 }
172
173 public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
174 {
175 //uint x, y;
176 //Utils.LongToUInts(regionHandle, out x, out y);
177 //x = x / Constants.RegionSize;
178 //y = y / Constants.RegionSize;
179 //Console.WriteLine("\n >>> Local SendReleaseAgent " + x + "-" + y);
180 foreach (Scene s in m_sceneList)
181 {
182 if (s.RegionInfo.RegionHandle == regionHandle)
183 {
184 //m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent");
185 return s.IncomingReleaseAgent(id);
186 }
187 }
188 //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent");
189 return false;
190 }
191
192 public bool SendCloseAgent(ulong regionHandle, UUID id)
193 {
194 //uint x, y;
195 //Utils.LongToUInts(regionHandle, out x, out y);
196 //x = x / Constants.RegionSize;
197 //y = y / Constants.RegionSize;
198 //Console.WriteLine("\n >>> Local SendCloseAgent " + x + "-" + y);
199 foreach (Scene s in m_sceneList)
200 {
201 if (s.RegionInfo.RegionHandle == regionHandle)
202 {
203 //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent");
204 return s.IncomingCloseAgent(id);
205 }
206 }
207 //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent");
208 return false;
209 }
210
211 /**
212 * Object-related communications
213 */
214
215 public bool SendCreateObject(ulong regionHandle, ISceneObject sog)
216 {
217 foreach (Scene s in m_sceneList)
218 {
219 if (s.RegionInfo.RegionHandle == regionHandle)
220 {
221 //m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
222 return s.IncomingCreateObject(sog);
223 }
224 }
225 return false;
226 }
227
228 #endregion /* IInterregionComms */
229
230 #region Misc
231
232 public UUID GetRegionID(ulong regionhandle)
233 {
234 foreach (Scene s in m_sceneList)
235 {
236 if (s.RegionInfo.RegionHandle == regionhandle)
237 return s.RegionInfo.RegionID;
238 }
239 // ? weird. should not happen
240 return m_sceneList[0].RegionInfo.RegionID;
241 }
242 #endregion
243 }
244}
diff --git a/OpenSim/Region/CoreModules/Communications/REST/RESTInterregionComms.cs b/OpenSim/Region/CoreModules/Communications/REST/RESTInterregionComms.cs
new file mode 100644
index 0000000..b4f4814
--- /dev/null
+++ b/OpenSim/Region/CoreModules/Communications/REST/RESTInterregionComms.cs
@@ -0,0 +1,960 @@
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 OpenSim 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 */
27using System;
28using System.Collections;
29using System.Collections.Generic;
30using System.IO;
31using System.Net;
32using System.Net.Sockets;
33using System.Reflection;
34using System.Threading;
35using System.Xml;
36using OpenMetaverse;
37using OpenMetaverse.StructuredData;
38using log4net;
39using Nini.Config;
40using Nwc.XmlRpc;
41using OpenSim.Framework;
42using OpenSim.Framework.Communications;
43using OpenSim.Framework.Communications.Cache;
44using OpenSim.Framework.Servers;
45using OpenSim.Region.Framework.Interfaces;
46using OpenSim.Region.Framework.Scenes;
47using OpenSim.Region.Framework.Scenes.Hypergrid;
48using OpenSim.Region.CoreModules.Communications.Local;
49
50namespace OpenSim.Region.CoreModules.Communications.REST
51{
52 public class RESTInterregionComms : IRegionModule, IInterregionCommsOut
53 {
54 private static bool initialized = false;
55 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
56
57 protected bool m_enabled = false;
58 protected Scene m_aScene;
59 // RESTInterregionComms does not care about local regions; it delegates that to the Local module
60 protected LocalInterregionComms m_localBackend;
61
62 protected CommunicationsManager m_commsManager;
63
64 #region IRegionModule
65
66 public virtual void Initialise(Scene scene, IConfigSource config)
67 {
68 if (!initialized)
69 {
70 initialized = true;
71 IConfig startupConfig = config.Configs["Communications"];
72
73 if ((startupConfig == null)
74 || (startupConfig != null)
75 && (startupConfig.GetString("InterregionComms", "RESTComms") == "RESTComms"))
76 {
77 m_log.Info("[REST COMMS]: Enabling InterregionComms RESTComms module");
78 m_enabled = true;
79 InitOnce(scene);
80 }
81 }
82
83 if (!m_enabled)
84 return;
85
86 InitEach(scene);
87
88 }
89
90 public virtual void PostInitialise()
91 {
92 if (m_enabled)
93 AddHTTPHandlers();
94 }
95
96 public virtual void Close()
97 {
98 }
99
100 public virtual string Name
101 {
102 get { return "RESTInterregionCommsModule"; }
103 }
104
105 public virtual bool IsSharedModule
106 {
107 get { return true; }
108 }
109
110 protected virtual void InitEach(Scene scene)
111 {
112 m_localBackend.Init(scene);
113 scene.RegisterModuleInterface<IInterregionCommsOut>(this);
114 }
115
116 protected virtual void InitOnce(Scene scene)
117 {
118 m_localBackend = new LocalInterregionComms();
119 m_commsManager = scene.CommsManager;
120 m_aScene = scene;
121 }
122
123 protected virtual void AddHTTPHandlers()
124 {
125 m_aScene.CommsManager.HttpServer.AddHTTPHandler("/agent/", AgentHandler);
126 m_aScene.CommsManager.HttpServer.AddHTTPHandler("/object/", ObjectHandler);
127 }
128
129 #endregion /* IRegionModule */
130
131 #region IInterregionComms
132
133 /**
134 * Agent-related communications
135 */
136
137 public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit)
138 {
139 // Try local first
140 if (m_localBackend.SendCreateChildAgent(regionHandle, aCircuit))
141 return true;
142
143 // else do the remote thing
144 RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
145 if (regInfo != null)
146 {
147 SendUserInformation(regInfo, aCircuit);
148
149 return DoCreateChildAgentCall(regInfo, aCircuit);
150 }
151 //else
152 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
153 return false;
154 }
155
156 public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
157 {
158 // Try local first
159 if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
160 return true;
161
162 // else do the remote thing
163 RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
164 if (regInfo != null)
165 {
166 return DoChildAgentUpdateCall(regInfo, cAgentData);
167 }
168 //else
169 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
170 return false;
171
172 }
173
174 public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
175 {
176 // Try local first
177 if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
178 return true;
179
180 // else do the remote thing
181 RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
182 if (regInfo != null)
183 {
184 return DoChildAgentUpdateCall(regInfo, cAgentData);
185 }
186 //else
187 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
188 return false;
189
190 }
191
192 public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
193 {
194 // Try local first
195 if (m_localBackend.SendReleaseAgent(regionHandle, id, uri))
196 return true;
197
198 // else do the remote thing
199 return DoReleaseAgentCall(regionHandle, id, uri);
200 }
201
202 public bool SendCloseAgent(ulong regionHandle, UUID id)
203 {
204 // Try local first
205 if (m_localBackend.SendCloseAgent(regionHandle, id))
206 return true;
207
208 // else do the remote thing
209 RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
210 if (regInfo != null)
211 {
212 return DoCloseAgentCall(regInfo, id);
213 }
214 //else
215 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
216 return false;
217 }
218
219 /**
220 * Object-related communications
221 */
222
223 public bool SendCreateObject(ulong regionHandle, ISceneObject sog)
224 {
225 // Try local first
226 ISceneObject sogClone = sog.CloneForNewScene();
227 if (m_localBackend.SendCreateObject(regionHandle, sogClone))
228 {
229 //m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded");
230 return true;
231 }
232
233 // else do the remote thing
234 RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
235 if (regInfo != null)
236 {
237 return DoCreateObjectCall(regInfo, sog);
238 }
239 //else
240 // m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
241 return false;
242 }
243
244 #endregion /* IInterregionComms */
245
246 #region DoWork functions for the above public interface
247
248 //-------------------------------------------------------------------
249 // Internal functions for the above public interface
250 //-------------------------------------------------------------------
251
252 protected bool DoCreateChildAgentCall(RegionInfo region, AgentCircuitData aCircuit)
253 {
254 // Eventually, we want to use a caps url instead of the agentID
255 string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + aCircuit.AgentID + "/";
256 //Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri);
257
258 WebRequest AgentCreateRequest = WebRequest.Create(uri);
259 AgentCreateRequest.Method = "POST";
260 AgentCreateRequest.ContentType = "application/json";
261 AgentCreateRequest.Timeout = 10000;
262
263 // Fill it in
264 OSDMap args = null;
265 try
266 {
267 args = aCircuit.PackAgentCircuitData();
268 }
269 catch (Exception e)
270 {
271 m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
272 }
273 // Add the regionhandle of the destination region
274 ulong regionHandle = GetRegionHandle(region.RegionHandle);
275 args["destination_handle"] = OSD.FromString(regionHandle.ToString());
276
277 string strBuffer = "";
278 byte[] buffer = new byte[1];
279 try
280 {
281 strBuffer = OSDParser.SerializeJsonString(args);
282 System.Text.UTF8Encoding str = new System.Text.UTF8Encoding();
283 buffer = str.GetBytes(strBuffer);
284
285 }
286 catch (Exception e)
287 {
288 m_log.WarnFormat("[OSG2]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
289 // ignore. buffer will be empty, caller should check.
290 }
291
292 Stream os = null;
293 try
294 { // send the Post
295 AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
296 os = AgentCreateRequest.GetRequestStream();
297 os.Write(buffer, 0, strBuffer.Length); //Send it
298 os.Close();
299 //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
300 }
301 //catch (WebException ex)
302 catch
303 {
304 //m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
305
306 return false;
307 }
308
309 // Let's wait for the response
310 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
311
312 try
313 {
314 WebResponse webResponse = AgentCreateRequest.GetResponse();
315 if (webResponse == null)
316 {
317 m_log.Info("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
318 }
319
320 StreamReader sr = new StreamReader(webResponse.GetResponseStream());
321 //reply = sr.ReadToEnd().Trim();
322 sr.ReadToEnd().Trim();
323 sr.Close();
324 //m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply);
325
326 }
327 catch (WebException ex)
328 {
329 m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
330 // ignore, really
331 }
332
333 return true;
334
335 }
336
337 protected bool DoChildAgentUpdateCall(RegionInfo region, IAgentData cAgentData)
338 {
339 // Eventually, we want to use a caps url instead of the agentID
340 string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/";
341 //Console.WriteLine(" >>> DoChildAgentUpdateCall <<< " + uri);
342
343 WebRequest ChildUpdateRequest = WebRequest.Create(uri);
344 ChildUpdateRequest.Method = "PUT";
345 ChildUpdateRequest.ContentType = "application/json";
346 ChildUpdateRequest.Timeout = 10000;
347
348 // Fill it in
349 OSDMap args = null;
350 try
351 {
352 args = cAgentData.PackUpdateMessage();
353 }
354 catch (Exception e)
355 {
356 m_log.Debug("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
357 }
358 // Add the regionhandle of the destination region
359 ulong regionHandle = GetRegionHandle(region.RegionHandle);
360 args["destination_handle"] = OSD.FromString(regionHandle.ToString());
361
362 string strBuffer = "";
363 byte[] buffer = new byte[1];
364 try
365 {
366 strBuffer = OSDParser.SerializeJsonString(args);
367 System.Text.UTF8Encoding str = new System.Text.UTF8Encoding();
368 buffer = str.GetBytes(strBuffer);
369
370 }
371 catch (Exception e)
372 {
373 m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
374 // ignore. buffer will be empty, caller should check.
375 }
376
377 Stream os = null;
378 try
379 { // send the Post
380 ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
381 os = ChildUpdateRequest.GetRequestStream();
382 os.Write(buffer, 0, strBuffer.Length); //Send it
383 os.Close();
384 //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
385 }
386 //catch (WebException ex)
387 catch
388 {
389 //m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
390
391 return false;
392 }
393
394 // Let's wait for the response
395 //m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
396
397 try
398 {
399 WebResponse webResponse = ChildUpdateRequest.GetResponse();
400 if (webResponse == null)
401 {
402 m_log.Info("[REST COMMS]: Null reply on ChilAgentUpdate post");
403 }
404
405 StreamReader sr = new StreamReader(webResponse.GetResponseStream());
406 //reply = sr.ReadToEnd().Trim();
407 sr.ReadToEnd().Trim();
408 sr.Close();
409 //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
410
411 }
412 catch (WebException ex)
413 {
414 m_log.InfoFormat("[REST COMMS]: exception on reply of ChilAgentUpdate {0}", ex.Message);
415 // ignore, really
416 }
417
418 return true;
419 }
420
421 protected bool DoReleaseAgentCall(ulong regionHandle, UUID id, string uri)
422 {
423 //Console.WriteLine(" >>> DoReleaseAgentCall <<< " + uri);
424
425 WebRequest request = WebRequest.Create(uri);
426 request.Method = "DELETE";
427 request.Timeout = 10000;
428
429 try
430 {
431 WebResponse webResponse = request.GetResponse();
432 if (webResponse == null)
433 {
434 m_log.Info("[REST COMMS]: Null reply on agent get ");
435 }
436
437 StreamReader sr = new StreamReader(webResponse.GetResponseStream());
438 //reply = sr.ReadToEnd().Trim();
439 sr.ReadToEnd().Trim();
440 sr.Close();
441 //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
442
443 }
444 catch (WebException ex)
445 {
446 m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
447 // ignore, really
448 }
449
450 return true;
451 }
452
453 protected bool DoCloseAgentCall(RegionInfo region, UUID id)
454 {
455 string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() +"/";
456
457 //Console.WriteLine(" >>> DoCloseAgentCall <<< " + uri);
458
459 WebRequest request = WebRequest.Create(uri);
460 request.Method = "DELETE";
461 request.Timeout = 10000;
462
463 try
464 {
465 WebResponse webResponse = request.GetResponse();
466 if (webResponse == null)
467 {
468 m_log.Info("[REST COMMS]: Null reply on agent get ");
469 }
470
471 StreamReader sr = new StreamReader(webResponse.GetResponseStream());
472 //reply = sr.ReadToEnd().Trim();
473 sr.ReadToEnd().Trim();
474 sr.Close();
475 //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
476
477 }
478 catch (WebException ex)
479 {
480 m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
481 // ignore, really
482 }
483
484 return true;
485 }
486
487 protected bool DoCreateObjectCall(RegionInfo region, ISceneObject sog)
488 {
489 ulong regionHandle = GetRegionHandle(region.RegionHandle);
490 string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/object/" + sog.UUID + "/" + regionHandle.ToString() + "/";
491 //Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri);
492
493 WebRequest ObjectCreateRequest = WebRequest.Create(uri);
494 ObjectCreateRequest.Method = "POST";
495 ObjectCreateRequest.ContentType = "text/xml";
496 ObjectCreateRequest.Timeout = 10000;
497
498 OSDMap args = new OSDMap(2);
499 args["sog"] = OSD.FromString(sog.ToXmlString2());
500 args["extra"] = OSD.FromString(sog.ExtraToXmlString());
501 if (m_aScene.m_allowScriptCrossings)
502 {
503 string state = sog.GetStateSnapshot();
504 if (state.Length > 0)
505 args["state"] = OSD.FromString(state);
506 }
507
508 string strBuffer = "";
509 byte[] buffer = new byte[1];
510 try
511 {
512 strBuffer = OSDParser.SerializeJsonString(args);
513 System.Text.UTF8Encoding str = new System.Text.UTF8Encoding();
514 buffer = str.GetBytes(strBuffer);
515
516 }
517 catch (Exception e)
518 {
519 m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
520 // ignore. buffer will be empty, caller should check.
521 }
522
523 Stream os = null;
524 try
525 { // send the Post
526 ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
527 os = ObjectCreateRequest.GetRequestStream();
528 os.Write(buffer, 0, strBuffer.Length); //Send it
529 os.Close();
530 m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
531 }
532 //catch (WebException ex)
533 catch
534 {
535 // m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message);
536
537 return false;
538 }
539
540 // Let's wait for the response
541 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
542
543 try
544 {
545 WebResponse webResponse = ObjectCreateRequest.GetResponse();
546 if (webResponse == null)
547 {
548 m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post");
549 }
550
551 StreamReader sr = new StreamReader(webResponse.GetResponseStream());
552 //reply = sr.ReadToEnd().Trim();
553 sr.ReadToEnd().Trim();
554 sr.Close();
555 //m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply);
556
557 }
558 catch (WebException ex)
559 {
560 m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message);
561 // ignore, really
562 }
563
564 return true;
565
566 }
567
568 #endregion /* Do Work */
569
570 #region Incoming calls from remote instances
571
572 /**
573 * Agent-related incoming calls
574 */
575
576 public Hashtable AgentHandler(Hashtable request)
577 {
578 //m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
579
580 //Console.WriteLine("---------------------------");
581 //Console.WriteLine(" >> uri=" + request["uri"]);
582 //Console.WriteLine(" >> content-type=" + request["content-type"]);
583 //Console.WriteLine(" >> http-method=" + request["http-method"]);
584 //Console.WriteLine("---------------------------\n");
585
586 Hashtable responsedata = new Hashtable();
587 responsedata["content_type"] = "text/html";
588
589 UUID agentID;
590 string action;
591 ulong regionHandle;
592 if (!GetParams((string)request["uri"], out agentID, out regionHandle, out action))
593 {
594 m_log.InfoFormat("[REST COMMS]: Invalid parameters for agent message {0}", request["uri"]);
595 responsedata["int_response_code"] = 404;
596 responsedata["str_response_string"] = "false";
597
598 return responsedata;
599 }
600
601 // Next, let's parse the verb
602 string method = (string)request["http-method"];
603 if (method.Equals("PUT"))
604 {
605 DoAgentPut(request, responsedata);
606 return responsedata;
607 }
608 else if (method.Equals("POST"))
609 {
610 DoAgentPost(request, responsedata, agentID);
611 return responsedata;
612 }
613 else if (method.Equals("DELETE"))
614 {
615 DoAgentDelete(request, responsedata, agentID, action, regionHandle);
616
617 return responsedata;
618 }
619 else
620 {
621 m_log.InfoFormat("[REST COMMS]: method {0} not supported in agent message", method);
622 responsedata["int_response_code"] = 404;
623 responsedata["str_response_string"] = "false";
624
625 return responsedata;
626 }
627
628 }
629
630 protected OSDMap GetOSDMap(Hashtable request)
631 {
632 OSDMap args = null;
633 try
634 {
635 OSD buffer;
636 // We should pay attention to the content-type, but let's assume we know it's Json
637 buffer = OSDParser.DeserializeJson((string)request["body"]);
638 if (buffer.Type == OSDType.Map)
639 {
640 args = (OSDMap)buffer;
641 return args;
642 }
643 else
644 {
645 // uh?
646 m_log.Debug("[REST COMMS]: Got OSD of type " + buffer.Type.ToString());
647 return null;
648 }
649 }
650 catch (Exception ex)
651 {
652 m_log.InfoFormat("[REST COMMS]: exception on parse of REST message {0}", ex.Message);
653 return null;
654 }
655 }
656
657 protected virtual void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
658 {
659 OSDMap args = GetOSDMap(request);
660 if (args == null)
661 {
662 responsedata["int_response_code"] = 400;
663 responsedata["str_response_string"] = "false";
664 return;
665 }
666
667 // retrieve the regionhandle
668 ulong regionhandle = 0;
669 if (args["destination_handle"] != null)
670 UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
671
672 AgentCircuitData aCircuit = new AgentCircuitData();
673 try
674 {
675 aCircuit.UnpackAgentCircuitData(args);
676 }
677 catch (Exception ex)
678 {
679 m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildCreate message {0}", ex.Message);
680 return;
681 }
682
683 // This is the meaning of POST agent
684 AdjustUserInformation(aCircuit);
685 bool result = m_localBackend.SendCreateChildAgent(regionhandle, aCircuit);
686
687 responsedata["int_response_code"] = 200;
688 responsedata["str_response_string"] = result.ToString();
689 }
690
691 protected virtual void DoAgentPut(Hashtable request, Hashtable responsedata)
692 {
693 OSDMap args = GetOSDMap(request);
694 if (args == null)
695 {
696 responsedata["int_response_code"] = 400;
697 responsedata["str_response_string"] = "false";
698 return;
699 }
700
701 // retrieve the regionhandle
702 ulong regionhandle = 0;
703 if (args["destination_handle"] != null)
704 UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
705
706 string messageType;
707 if (args["message_type"] != null)
708 messageType = args["message_type"].AsString();
709 else
710 {
711 m_log.Warn("[REST COMMS]: Agent Put Message Type not found. ");
712 messageType = "AgentData";
713 }
714
715 bool result = true;
716 if ("AgentData".Equals(messageType))
717 {
718 AgentData agent = new AgentData();
719 try
720 {
721 agent.UnpackUpdateMessage(args);
722 }
723 catch (Exception ex)
724 {
725 m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
726 return;
727 }
728 //agent.Dump();
729 // This is one of the meanings of PUT agent
730 result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
731
732 }
733 else if ("AgentPosition".Equals(messageType))
734 {
735 AgentPosition agent = new AgentPosition();
736 try
737 {
738 agent.UnpackUpdateMessage(args);
739 }
740 catch (Exception ex)
741 {
742 m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
743 return;
744 }
745 //agent.Dump();
746 // This is one of the meanings of PUT agent
747 result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
748
749 }
750
751
752
753 responsedata["int_response_code"] = 200;
754 responsedata["str_response_string"] = result.ToString();
755 }
756
757 protected virtual void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, ulong regionHandle)
758 {
759 //Console.WriteLine(" >>> DoDelete action:" + action + "; regionHandle:" + regionHandle);
760
761 if (action.Equals("release"))
762 m_localBackend.SendReleaseAgent(regionHandle, id, "");
763 else
764 m_localBackend.SendCloseAgent(regionHandle, id);
765
766 responsedata["int_response_code"] = 200;
767 responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
768 }
769
770 /**
771 * Object-related incoming calls
772 */
773
774 public Hashtable ObjectHandler(Hashtable request)
775 {
776 //m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called");
777
778 //Console.WriteLine("---------------------------");
779 //Console.WriteLine(" >> uri=" + request["uri"]);
780 //Console.WriteLine(" >> content-type=" + request["content-type"]);
781 //Console.WriteLine(" >> http-method=" + request["http-method"]);
782 //Console.WriteLine("---------------------------\n");
783
784 Hashtable responsedata = new Hashtable();
785 responsedata["content_type"] = "text/html";
786
787 UUID objectID;
788 string action;
789 ulong regionHandle;
790 if (!GetParams((string)request["uri"], out objectID, out regionHandle, out action))
791 {
792 m_log.InfoFormat("[REST COMMS]: Invalid parameters for object message {0}", request["uri"]);
793 responsedata["int_response_code"] = 404;
794 responsedata["str_response_string"] = "false";
795
796 return responsedata;
797 }
798
799 // Next, let's parse the verb
800 string method = (string)request["http-method"];
801 if (method.Equals("POST"))
802 {
803 DoObjectPost(request, responsedata, regionHandle);
804 return responsedata;
805 }
806 //else if (method.Equals("PUT"))
807 //{
808 // DoObjectPut(request, responsedata, agentID);
809 // return responsedata;
810 //}
811 //else if (method.Equals("DELETE"))
812 //{
813 // DoObjectDelete(request, responsedata, agentID, action, regionHandle);
814 // return responsedata;
815 //}
816 else
817 {
818 m_log.InfoFormat("[REST COMMS]: method {0} not supported in object message", method);
819 responsedata["int_response_code"] = 404;
820 responsedata["str_response_string"] = "false";
821
822 return responsedata;
823 }
824
825 }
826
827 protected virtual void DoObjectPost(Hashtable request, Hashtable responsedata, ulong regionhandle)
828 {
829 OSDMap args = GetOSDMap(request);
830 if (args == null)
831 {
832 responsedata["int_response_code"] = 400;
833 responsedata["str_response_string"] = "false";
834 return;
835 }
836
837 string sogXmlStr = "", extraStr = "", stateXmlStr = "";
838 if (args["sog"] != null)
839 sogXmlStr = args["sog"].AsString();
840 if (args["extra"] != null)
841 extraStr = args["extra"].AsString();
842
843 UUID regionID = m_localBackend.GetRegionID(regionhandle);
844 SceneObjectGroup sog = null;
845 try
846 {
847 sog = new SceneObjectGroup(sogXmlStr);
848 sog.ExtraFromXmlString(extraStr);
849 }
850 catch (Exception ex)
851 {
852 m_log.InfoFormat("[REST COMMS]: exception on deserializing scene object {0}", ex.Message);
853 responsedata["int_response_code"] = 400;
854 responsedata["str_response_string"] = "false";
855 return;
856 }
857
858 if ((args["state"] != null) && m_aScene.m_allowScriptCrossings)
859 {
860 stateXmlStr = args["state"].AsString();
861 if (stateXmlStr != "")
862 {
863 try
864 {
865 sog.SetState(stateXmlStr, regionID);
866 }
867 catch (Exception ex)
868 {
869 m_log.InfoFormat("[REST COMMS]: exception on setting state for scene object {0}", ex.Message);
870
871 }
872 }
873 }
874 // This is the meaning of POST object
875 bool result = m_localBackend.SendCreateObject(regionhandle, sog);
876
877 responsedata["int_response_code"] = 200;
878 responsedata["str_response_string"] = result.ToString();
879 }
880
881 #endregion
882
883 #region Misc
884
885 /// <summary>
886 /// Extract the param from an uri.
887 /// </summary>
888 /// <param name="uri">Something like this: /agent/uuid/ or /agent/uuid/handle/release</param>
889 /// <param name="uri">uuid on uuid field</param>
890 /// <param name="action">optional action</param>
891 protected bool GetParams(string uri, out UUID uuid, out ulong regionHandle, out string action)
892 {
893 uuid = UUID.Zero;
894 action = "";
895 regionHandle = 0;
896
897 uri = uri.Trim(new char[] { '/' });
898 string[] parts = uri.Split('/');
899 if (parts.Length <= 1)
900 {
901 return false;
902 }
903 else
904 {
905 if (!UUID.TryParse(parts[1], out uuid))
906 return false;
907
908 if (parts.Length >= 3)
909 UInt64.TryParse(parts[2], out regionHandle);
910 if (parts.Length >= 4)
911 action = parts[3];
912
913 return true;
914 }
915 }
916
917 #endregion Misc
918
919 #region Hyperlinks
920
921 protected virtual ulong GetRegionHandle(ulong handle)
922 {
923 if (m_aScene.SceneGridService is HGSceneCommunicationService)
924 return ((HGSceneCommunicationService)(m_aScene.SceneGridService)).m_hg.FindRegionHandle(handle);
925
926 return handle;
927 }
928
929 protected virtual bool IsHyperlink(ulong handle)
930 {
931 if (m_aScene.SceneGridService is HGSceneCommunicationService)
932 return ((HGSceneCommunicationService)(m_aScene.SceneGridService)).m_hg.IsHyperlinkRegion(handle);
933
934 return false;
935 }
936
937 protected virtual void SendUserInformation(RegionInfo regInfo, AgentCircuitData aCircuit)
938 {
939 try
940 {
941 //if (IsHyperlink(regInfo.RegionHandle))
942 if (m_aScene.SceneGridService is HGSceneCommunicationService)
943 {
944 ((HGSceneCommunicationService)(m_aScene.SceneGridService)).m_hg.SendUserInformation(regInfo, aCircuit);
945 }
946 }
947 catch // Bad cast
948 { }
949
950 }
951
952 protected virtual void AdjustUserInformation(AgentCircuitData aCircuit)
953 {
954 if (m_aScene.SceneGridService is HGSceneCommunicationService)
955 ((HGSceneCommunicationService)(m_aScene.SceneGridService)).m_hg.AdjustUserInformation(aCircuit);
956 }
957 #endregion /* Hyperlinks */
958
959 }
960}