aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Server
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Server')
-rw-r--r--OpenSim/Server/Base/ServerUtils.cs3
-rw-r--r--OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs2
-rw-r--r--OpenSim/Server/Handlers/Authentication/OpenIdServerConnector.cs77
-rw-r--r--OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs345
-rw-r--r--OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs61
-rw-r--r--OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs269
-rw-r--r--OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs154
-rw-r--r--OpenSim/Server/Handlers/Grid/GridInfoServerInConnector.cs55
-rw-r--r--OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs77
-rw-r--r--OpenSim/Server/Handlers/Login/LLLoginHandlers.cs149
-rw-r--r--OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs95
-rw-r--r--OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs205
-rw-r--r--OpenSim/Server/Handlers/Simulation/AgentHandlers.cs338
-rw-r--r--OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs238
-rw-r--r--OpenSim/Server/Handlers/Simulation/SimulationServiceInConnector.cs33
-rw-r--r--OpenSim/Server/Handlers/Simulation/Utils.cs103
-rw-r--r--OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs61
-rw-r--r--OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs258
18 files changed, 2370 insertions, 153 deletions
diff --git a/OpenSim/Server/Base/ServerUtils.cs b/OpenSim/Server/Base/ServerUtils.cs
index a5d28a4..e00eb2a 100644
--- a/OpenSim/Server/Base/ServerUtils.cs
+++ b/OpenSim/Server/Base/ServerUtils.cs
@@ -278,6 +278,9 @@ namespace OpenSim.Server.Base
278 { 278 {
279 foreach (KeyValuePair<string, object> kvp in data) 279 foreach (KeyValuePair<string, object> kvp in data)
280 { 280 {
281 if (kvp.Value == null)
282 continue;
283
281 XmlElement elem = parent.OwnerDocument.CreateElement("", 284 XmlElement elem = parent.OwnerDocument.CreateElement("",
282 kvp.Key, ""); 285 kvp.Key, "");
283 286
diff --git a/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs b/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs
index 2abef0a..adb1e5b 100644
--- a/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs
+++ b/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs
@@ -49,7 +49,7 @@ namespace OpenSim.Server.Handlers.Authentication
49 if (serverConfig == null) 49 if (serverConfig == null)
50 throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); 50 throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
51 51
52 string authenticationService = serverConfig.GetString("AuthenticationServiceModule", 52 string authenticationService = serverConfig.GetString("LocalServiceModule",
53 String.Empty); 53 String.Empty);
54 54
55 if (authenticationService == String.Empty) 55 if (authenticationService == String.Empty)
diff --git a/OpenSim/Server/Handlers/Authentication/OpenIdServerConnector.cs b/OpenSim/Server/Handlers/Authentication/OpenIdServerConnector.cs
new file mode 100644
index 0000000..a0a92ed
--- /dev/null
+++ b/OpenSim/Server/Handlers/Authentication/OpenIdServerConnector.cs
@@ -0,0 +1,77 @@
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.Reflection;
30using Nini.Config;
31using log4net;
32using OpenSim.Server.Base;
33using OpenSim.Services.Interfaces;
34using OpenSim.Framework.Servers.HttpServer;
35using OpenSim.Server.Handlers.Base;
36
37namespace OpenSim.Server.Handlers.Authentication
38{
39 public class OpenIdServerConnector : ServiceConnector
40 {
41 private static readonly ILog m_log =
42 LogManager.GetLogger(
43 MethodBase.GetCurrentMethod().DeclaringType);
44
45 private IAuthenticationService m_AuthenticationService;
46 private IUserAccountService m_UserAccountService;
47 private string m_ConfigName = "OpenIdService";
48
49 public OpenIdServerConnector(IConfigSource config, IHttpServer server, string configName) :
50 base(config, server, configName)
51 {
52 IConfig serverConfig = config.Configs[m_ConfigName];
53 if (serverConfig == null)
54 throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
55
56 string authService = serverConfig.GetString("AuthenticationServiceModule",
57 String.Empty);
58 string userService = serverConfig.GetString("UserAccountServiceModule",
59 String.Empty);
60
61 if (authService == String.Empty || userService == String.Empty)
62 throw new Exception("No AuthenticationServiceModule or no UserAccountServiceModule in config file for OpenId authentication");
63
64 Object[] args = new Object[] { config };
65 m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
66 m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(authService, args);
67
68 // Handler for OpenID user identity pages
69 server.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", m_UserAccountService, m_AuthenticationService));
70 // Handlers for the OpenID endpoint server
71 server.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", m_UserAccountService, m_AuthenticationService));
72 server.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", m_UserAccountService, m_AuthenticationService));
73
74 m_log.Info("[OPENID]: OpenId service enabled");
75 }
76 }
77}
diff --git a/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs b/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs
new file mode 100644
index 0000000..e73961b
--- /dev/null
+++ b/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs
@@ -0,0 +1,345 @@
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 System.Collections.Specialized;
31using System.IO;
32using System.Net;
33using System.Web;
34using DotNetOpenId;
35using DotNetOpenId.Provider;
36using OpenSim.Framework;
37using OpenSim.Framework.Servers;
38using OpenSim.Framework.Servers.HttpServer;
39using OpenSim.Server.Handlers.Base;
40using OpenSim.Services.Interfaces;
41using Nini.Config;
42using OpenMetaverse;
43
44namespace OpenSim.Server.Handlers.Authentication
45{
46 /// <summary>
47 /// Temporary, in-memory store for OpenID associations
48 /// </summary>
49 public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
50 {
51 private class AssociationItem
52 {
53 public AssociationRelyingPartyType DistinguishingFactor;
54 public string Handle;
55 public DateTime Expires;
56 public byte[] PrivateData;
57 }
58
59 Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
60 SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
61 object m_syncRoot = new object();
62
63 #region IAssociationStore<AssociationRelyingPartyType> Members
64
65 public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
66 {
67 AssociationItem item = new AssociationItem();
68 item.DistinguishingFactor = distinguishingFactor;
69 item.Handle = assoc.Handle;
70 item.Expires = assoc.Expires.ToLocalTime();
71 item.PrivateData = assoc.SerializePrivateData();
72
73 lock (m_syncRoot)
74 {
75 m_store[item.Handle] = item;
76 m_sortedStore[item.Expires] = item;
77 }
78 }
79
80 public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
81 {
82 lock (m_syncRoot)
83 {
84 if (m_sortedStore.Count > 0)
85 {
86 AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
87 return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
88 }
89 else
90 {
91 return null;
92 }
93 }
94 }
95
96 public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
97 {
98 AssociationItem item;
99 bool success = false;
100 lock (m_syncRoot)
101 success = m_store.TryGetValue(handle, out item);
102
103 if (success)
104 return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
105 else
106 return null;
107 }
108
109 public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
110 {
111 lock (m_syncRoot)
112 {
113 for (int i = 0; i < m_sortedStore.Values.Count; i++)
114 {
115 AssociationItem item = m_sortedStore.Values[i];
116 if (item.Handle == handle)
117 {
118 m_sortedStore.RemoveAt(i);
119 break;
120 }
121 }
122
123 return m_store.Remove(handle);
124 }
125 }
126
127 public void ClearExpiredAssociations()
128 {
129 lock (m_syncRoot)
130 {
131 List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
132 DateTime now = DateTime.Now;
133
134 for (int i = 0; i < itemsCopy.Count; i++)
135 {
136 AssociationItem item = itemsCopy[i];
137
138 if (item.Expires <= now)
139 {
140 m_sortedStore.RemoveAt(i);
141 m_store.Remove(item.Handle);
142 }
143 }
144 }
145 }
146
147 #endregion
148 }
149
150 public class OpenIdStreamHandler : IStreamHandler
151 {
152 #region HTML
153
154 /// <summary>Login form used to authenticate OpenID requests</summary>
155 const string LOGIN_PAGE =
156@"<html>
157<head><title>OpenSim OpenID Login</title></head>
158<body>
159<h3>OpenSim Login</h3>
160<form method=""post"">
161<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
162<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
163<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
164<input type=""submit"" value=""Login"">
165</form>
166</body>
167</html>";
168
169 /// <summary>Page shown for a valid OpenID identity</summary>
170 const string OPENID_PAGE =
171@"<html>
172<head>
173<title>{2} {3}</title>
174<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
175</head>
176<body>OpenID identifier for {2} {3}</body>
177</html>
178";
179
180 /// <summary>Page shown for an invalid OpenID identity</summary>
181 const string INVALID_OPENID_PAGE =
182@"<html><head><title>Identity not found</title></head>
183<body>Invalid OpenID identity</body></html>";
184
185 /// <summary>Page shown if the OpenID endpoint is requested directly</summary>
186 const string ENDPOINT_PAGE =
187@"<html><head><title>OpenID Endpoint</title></head><body>
188This is an OpenID server endpoint, not a human-readable resource.
189For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
190</body></html>";
191
192 #endregion HTML
193
194 public string ContentType { get { return m_contentType; } }
195 public string HttpMethod { get { return m_httpMethod; } }
196 public string Path { get { return m_path; } }
197
198 string m_contentType;
199 string m_httpMethod;
200 string m_path;
201 IAuthenticationService m_authenticationService;
202 IUserAccountService m_userAccountService;
203 ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
204
205 /// <summary>
206 /// Constructor
207 /// </summary>
208 public OpenIdStreamHandler(string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
209 {
210 m_authenticationService = authService;
211 m_userAccountService = userService;
212 m_httpMethod = httpMethod;
213 m_path = path;
214
215 m_contentType = "text/html";
216 }
217
218 /// <summary>
219 /// Handles all GET and POST requests for OpenID identifier pages and endpoint
220 /// server communication
221 /// </summary>
222 public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
223 {
224 Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
225
226 // Defult to returning HTML content
227 m_contentType = "text/html";
228
229 try
230 {
231 NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
232 NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
233 NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
234
235 OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
236
237 if (provider.Request != null)
238 {
239 if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
240 {
241 IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
242 string[] passwordValues = postQuery.GetValues("pass");
243
244 UserAccount account;
245 if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
246 {
247 // Check for form POST data
248 if (passwordValues != null && passwordValues.Length == 1)
249 {
250 if (account != null &&
251 (m_authenticationService.Authenticate(account.PrincipalID, passwordValues[0], 30) != string.Empty))
252 authRequest.IsAuthenticated = true;
253 else
254 authRequest.IsAuthenticated = false;
255 }
256 else
257 {
258 // Authentication was requested, send the client a login form
259 using (StreamWriter writer = new StreamWriter(response))
260 writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
261 return;
262 }
263 }
264 else
265 {
266 // Cannot find an avatar matching the claimed identifier
267 authRequest.IsAuthenticated = false;
268 }
269 }
270
271 // Add OpenID headers to the response
272 foreach (string key in provider.Request.Response.Headers.Keys)
273 httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
274
275 string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
276 if (contentTypeValues != null && contentTypeValues.Length == 1)
277 m_contentType = contentTypeValues[0];
278
279 // Set the response code and document body based on the OpenID result
280 httpResponse.StatusCode = (int)provider.Request.Response.Code;
281 response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
282 response.Close();
283 }
284 else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
285 {
286 // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
287 using (StreamWriter writer = new StreamWriter(response))
288 writer.Write(ENDPOINT_PAGE);
289 }
290 else
291 {
292 // Try and lookup this avatar
293 UserAccount account;
294 if (TryGetAccount(httpRequest.Url, out account))
295 {
296 using (StreamWriter writer = new StreamWriter(response))
297 {
298 // TODO: Print out a full profile page for this avatar
299 writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
300 httpRequest.Url.Authority, account.FirstName, account.LastName));
301 }
302 }
303 else
304 {
305 // Couldn't parse an avatar name, or couldn't find the avatar in the user server
306 using (StreamWriter writer = new StreamWriter(response))
307 writer.Write(INVALID_OPENID_PAGE);
308 }
309 }
310 }
311 catch (Exception ex)
312 {
313 httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
314 using (StreamWriter writer = new StreamWriter(response))
315 writer.Write(ex.Message);
316 }
317 }
318
319 /// <summary>
320 /// Parse a URL with a relative path of the form /users/First_Last and try to
321 /// retrieve the profile matching that avatar name
322 /// </summary>
323 /// <param name="requestUrl">URL to parse for an avatar name</param>
324 /// <param name="profile">Profile data for the avatar</param>
325 /// <returns>True if the parse and lookup were successful, otherwise false</returns>
326 bool TryGetAccount(Uri requestUrl, out UserAccount account)
327 {
328 if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
329 {
330 // Parse the avatar name from the path
331 string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
332 string[] name = username.Split('_');
333
334 if (name.Length == 2)
335 {
336 account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
337 return (account != null);
338 }
339 }
340
341 account = null;
342 return false;
343 }
344 }
345}
diff --git a/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs b/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs
new file mode 100644
index 0000000..9a57cd9
--- /dev/null
+++ b/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs
@@ -0,0 +1,61 @@
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 Nini.Config;
30using OpenSim.Server.Base;
31using OpenSim.Services.Interfaces;
32using OpenSim.Framework.Servers.HttpServer;
33using OpenSim.Server.Handlers.Base;
34
35namespace OpenSim.Server.Handlers.Avatar
36{
37 public class AvatarServiceConnector : ServiceConnector
38 {
39 private IAvatarService m_AvatarService;
40 private string m_ConfigName = "AvatarService";
41
42 public AvatarServiceConnector(IConfigSource config, IHttpServer server, string configName) :
43 base(config, server, configName)
44 {
45 IConfig serverConfig = config.Configs[m_ConfigName];
46 if (serverConfig == null)
47 throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
48
49 string avatarService = serverConfig.GetString("LocalServiceModule",
50 String.Empty);
51
52 if (avatarService == String.Empty)
53 throw new Exception("No LocalServiceModule in config file");
54
55 Object[] args = new Object[] { config };
56 m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarService, args);
57
58 server.AddStreamHandler(new AvatarServerPostHandler(m_AvatarService));
59 }
60 }
61}
diff --git a/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs b/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs
new file mode 100644
index 0000000..49c2e43
--- /dev/null
+++ b/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs
@@ -0,0 +1,269 @@
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 Nini.Config;
29using log4net;
30using System;
31using System.Reflection;
32using System.IO;
33using System.Net;
34using System.Text;
35using System.Text.RegularExpressions;
36using System.Xml;
37using System.Xml.Serialization;
38using System.Collections.Generic;
39using OpenSim.Server.Base;
40using OpenSim.Services.Interfaces;
41using OpenSim.Framework;
42using OpenSim.Framework.Servers.HttpServer;
43using OpenMetaverse;
44
45namespace OpenSim.Server.Handlers.Avatar
46{
47 public class AvatarServerPostHandler : BaseStreamHandler
48 {
49 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
50
51 private IAvatarService m_AvatarService;
52
53 public AvatarServerPostHandler(IAvatarService service) :
54 base("POST", "/avatar")
55 {
56 m_AvatarService = service;
57 }
58
59 public override byte[] Handle(string path, Stream requestData,
60 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
61 {
62 StreamReader sr = new StreamReader(requestData);
63 string body = sr.ReadToEnd();
64 sr.Close();
65 body = body.Trim();
66
67 //m_log.DebugFormat("[XXX]: query String: {0}", body);
68
69 try
70 {
71 Dictionary<string, object> request =
72 ServerUtils.ParseQueryString(body);
73
74 if (!request.ContainsKey("METHOD"))
75 return FailureResult();
76
77 string method = request["METHOD"].ToString();
78
79 switch (method)
80 {
81 case "getavatar":
82 return GetAvatar(request);
83 case "setavatar":
84 return SetAvatar(request);
85 case "resetavatar":
86 return ResetAvatar(request);
87 case "setitems":
88 return SetItems(request);
89 case "removeitems":
90 return RemoveItems(request);
91 }
92 m_log.DebugFormat("[AVATAR HANDLER]: unknown method request: {0}", method);
93 }
94 catch (Exception e)
95 {
96 m_log.Debug("[AVATAR HANDLER]: Exception {0}" + e);
97 }
98
99 return FailureResult();
100
101 }
102
103 byte[] GetAvatar(Dictionary<string, object> request)
104 {
105 UUID user = UUID.Zero;
106
107 if (!request.ContainsKey("UserID"))
108 return FailureResult();
109
110 if (UUID.TryParse(request["UserID"].ToString(), out user))
111 {
112 AvatarData avatar = m_AvatarService.GetAvatar(user);
113 if (avatar == null)
114 return FailureResult();
115
116 Dictionary<string, object> result = new Dictionary<string, object>();
117 if (avatar == null)
118 result["result"] = "null";
119 else
120 result["result"] = avatar.ToKeyValuePairs();
121
122 string xmlString = ServerUtils.BuildXmlResponse(result);
123
124 UTF8Encoding encoding = new UTF8Encoding();
125 return encoding.GetBytes(xmlString);
126 }
127
128 return FailureResult();
129 }
130
131 byte[] SetAvatar(Dictionary<string, object> request)
132 {
133 UUID user = UUID.Zero;
134
135 if (!request.ContainsKey("UserID"))
136 return FailureResult();
137
138 if (!UUID.TryParse(request["UserID"].ToString(), out user))
139 return FailureResult();
140
141 AvatarData avatar = new AvatarData(request);
142 if (m_AvatarService.SetAvatar(user, avatar))
143 return SuccessResult();
144
145 return FailureResult();
146 }
147
148 byte[] ResetAvatar(Dictionary<string, object> request)
149 {
150 UUID user = UUID.Zero;
151 if (!request.ContainsKey("UserID"))
152 return FailureResult();
153
154 if (!UUID.TryParse(request["UserID"].ToString(), out user))
155 return FailureResult();
156
157 if (m_AvatarService.ResetAvatar(user))
158 return SuccessResult();
159
160 return FailureResult();
161 }
162
163 byte[] SetItems(Dictionary<string, object> request)
164 {
165 UUID user = UUID.Zero;
166 string[] names, values;
167
168 if (!request.ContainsKey("UserID") || !request.ContainsKey("Names") || !request.ContainsKey("Values"))
169 return FailureResult();
170
171 if (!UUID.TryParse(request["UserID"].ToString(), out user))
172 return FailureResult();
173
174 if (!(request["Names"] is List<string> || request["Values"] is List<string>))
175 return FailureResult();
176
177 List<string> _names = (List<string>)request["Names"];
178 names = _names.ToArray();
179 List<string> _values = (List<string>)request["Values"];
180 values = _values.ToArray();
181
182 if (m_AvatarService.SetItems(user, names, values))
183 return SuccessResult();
184
185 return FailureResult();
186 }
187
188 byte[] RemoveItems(Dictionary<string, object> request)
189 {
190 UUID user = UUID.Zero;
191 string[] names;
192
193 if (!request.ContainsKey("UserID") || !request.ContainsKey("Names"))
194 return FailureResult();
195
196 if (!UUID.TryParse(request["UserID"].ToString(), out user))
197 return FailureResult();
198
199 if (!(request["Names"] is List<string>))
200 return FailureResult();
201
202 List<string> _names = (List<string>)request["Names"];
203 names = _names.ToArray();
204
205 if (m_AvatarService.RemoveItems(user, names))
206 return SuccessResult();
207
208 return FailureResult();
209 }
210
211
212
213 private byte[] SuccessResult()
214 {
215 XmlDocument doc = new XmlDocument();
216
217 XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
218 "", "");
219
220 doc.AppendChild(xmlnode);
221
222 XmlElement rootElement = doc.CreateElement("", "ServerResponse",
223 "");
224
225 doc.AppendChild(rootElement);
226
227 XmlElement result = doc.CreateElement("", "result", "");
228 result.AppendChild(doc.CreateTextNode("Success"));
229
230 rootElement.AppendChild(result);
231
232 return DocToBytes(doc);
233 }
234
235 private byte[] FailureResult()
236 {
237 XmlDocument doc = new XmlDocument();
238
239 XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
240 "", "");
241
242 doc.AppendChild(xmlnode);
243
244 XmlElement rootElement = doc.CreateElement("", "ServerResponse",
245 "");
246
247 doc.AppendChild(rootElement);
248
249 XmlElement result = doc.CreateElement("", "result", "");
250 result.AppendChild(doc.CreateTextNode("Failure"));
251
252 rootElement.AppendChild(result);
253
254 return DocToBytes(doc);
255 }
256
257 private byte[] DocToBytes(XmlDocument doc)
258 {
259 MemoryStream ms = new MemoryStream();
260 XmlTextWriter xw = new XmlTextWriter(ms, null);
261 xw.Formatting = Formatting.Indented;
262 doc.WriteTo(xw);
263 xw.Flush();
264
265 return ms.ToArray();
266 }
267
268 }
269}
diff --git a/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs b/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs
new file mode 100644
index 0000000..d1233dc
--- /dev/null
+++ b/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs
@@ -0,0 +1,154 @@
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;
30using System.IO;
31using System.Net;
32using System.Reflection;
33using System.Text;
34using log4net;
35using Nini.Config;
36using Nwc.XmlRpc;
37using OpenSim.Framework;
38using OpenSim.Framework.Servers.HttpServer;
39
40namespace OpenSim.Server.Handlers.Grid
41{
42 public class GridInfoHandlers
43 {
44 private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
45
46 private Hashtable _info = new Hashtable();
47
48 /// <summary>
49 /// Instantiate a GridInfoService object.
50 /// </summary>
51 /// <param name="configPath">path to config path containing
52 /// grid information</param>
53 /// <remarks>
54 /// GridInfoService uses the [GridInfo] section of the
55 /// standard OpenSim.ini file --- which is not optimal, but
56 /// anything else requires a general redesign of the config
57 /// system.
58 /// </remarks>
59 public GridInfoHandlers(IConfigSource configSource)
60 {
61 loadGridInfo(configSource);
62 }
63
64 private void loadGridInfo(IConfigSource configSource)
65 {
66 _info["platform"] = "OpenSim";
67 try
68 {
69 IConfig startupCfg = configSource.Configs["Startup"];
70 IConfig gridCfg = configSource.Configs["GridInfoService"];
71 IConfig netCfg = configSource.Configs["Network"];
72
73 bool grid = startupCfg.GetBoolean("gridmode", false);
74
75 if (null != gridCfg)
76 {
77 foreach (string k in gridCfg.GetKeys())
78 {
79 _info[k] = gridCfg.GetString(k);
80 }
81 }
82 else if (null != netCfg)
83 {
84 if (grid)
85 _info["login"]
86 = netCfg.GetString(
87 "user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString());
88 else
89 _info["login"]
90 = String.Format(
91 "http://127.0.0.1:{0}/",
92 netCfg.GetString(
93 "http_listener_port", ConfigSettings.DefaultRegionHttpPort.ToString()));
94
95 IssueWarning();
96 }
97 else
98 {
99 _info["login"] = "http://127.0.0.1:9000/";
100 IssueWarning();
101 }
102 }
103 catch (Exception)
104 {
105 _log.Debug("[GRID INFO SERVICE]: Cannot get grid info from config source, using minimal defaults");
106 }
107
108 _log.DebugFormat("[GRID INFO SERVICE]: Grid info service initialized with {0} keys", _info.Count);
109
110 }
111
112 private void IssueWarning()
113 {
114 _log.Warn("[GRID INFO SERVICE]: found no [GridInfo] section in your OpenSim.ini");
115 _log.Warn("[GRID INFO SERVICE]: trying to guess sensible defaults, you might want to provide better ones:");
116
117 foreach (string k in _info.Keys)
118 {
119 _log.WarnFormat("[GRID INFO SERVICE]: {0}: {1}", k, _info[k]);
120 }
121 }
122
123 public XmlRpcResponse XmlRpcGridInfoMethod(XmlRpcRequest request, IPEndPoint remoteClient)
124 {
125 XmlRpcResponse response = new XmlRpcResponse();
126 Hashtable responseData = new Hashtable();
127
128 _log.Info("[GRID INFO SERVICE]: Request for grid info");
129
130 foreach (string k in _info.Keys)
131 {
132 responseData[k] = _info[k];
133 }
134 response.Value = responseData;
135
136 return response;
137 }
138
139 public string RestGetGridInfoMethod(string request, string path, string param,
140 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
141 {
142 StringBuilder sb = new StringBuilder();
143
144 sb.Append("<gridinfo>\n");
145 foreach (string k in _info.Keys)
146 {
147 sb.AppendFormat("<{0}>{1}</{0}>\n", k, _info[k]);
148 }
149 sb.Append("</gridinfo>\n");
150
151 return sb.ToString();
152 }
153 }
154}
diff --git a/OpenSim/Server/Handlers/Grid/GridInfoServerInConnector.cs b/OpenSim/Server/Handlers/Grid/GridInfoServerInConnector.cs
new file mode 100644
index 0000000..c9e80d9
--- /dev/null
+++ b/OpenSim/Server/Handlers/Grid/GridInfoServerInConnector.cs
@@ -0,0 +1,55 @@
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 System.Reflection;
31using log4net;
32using OpenMetaverse;
33using Nini.Config;
34using OpenSim.Framework;
35using OpenSim.Framework.Servers.HttpServer;
36using OpenSim.Server.Handlers.Base;
37
38namespace OpenSim.Server.Handlers.Grid
39{
40 public class GridInfoServerInConnector : ServiceConnector
41 {
42 private string m_ConfigName = "GridInfoService";
43
44 public GridInfoServerInConnector(IConfigSource config, IHttpServer server, string configName) :
45 base(config, server, configName)
46 {
47 GridInfoHandlers handlers = new GridInfoHandlers(config);
48
49 server.AddStreamHandler(new RestStreamHandler("GET", "/get_grid_info",
50 handlers.RestGetGridInfoMethod));
51 server.AddXmlRPCHandler("get_grid_info", handlers.XmlRpcGridInfoMethod);
52 }
53
54 }
55}
diff --git a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs
index 85a8738..318ce85 100644
--- a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs
+++ b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs
@@ -103,6 +103,12 @@ namespace OpenSim.Server.Handlers.Grid
103 case "get_region_range": 103 case "get_region_range":
104 return GetRegionRange(request); 104 return GetRegionRange(request);
105 105
106 case "get_default_regions":
107 return GetDefaultRegions(request);
108
109 case "get_fallback_regions":
110 return GetFallbackRegions(request);
111
106 } 112 }
107 m_log.DebugFormat("[GRID HANDLER]: unknown method {0} request {1}", method.Length, method); 113 m_log.DebugFormat("[GRID HANDLER]: unknown method {0} request {1}", method.Length, method);
108 } 114 }
@@ -404,6 +410,77 @@ namespace OpenSim.Server.Handlers.Grid
404 return encoding.GetBytes(xmlString); 410 return encoding.GetBytes(xmlString);
405 } 411 }
406 412
413 byte[] GetDefaultRegions(Dictionary<string, object> request)
414 {
415 //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions");
416 UUID scopeID = UUID.Zero;
417 if (request.ContainsKey("SCOPEID"))
418 UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
419 else
420 m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range");
421
422 List<GridRegion> rinfos = m_GridService.GetDefaultRegions(scopeID);
423
424 Dictionary<string, object> result = new Dictionary<string, object>();
425 if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
426 result["result"] = "null";
427 else
428 {
429 int i = 0;
430 foreach (GridRegion rinfo in rinfos)
431 {
432 Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
433 result["region" + i] = rinfoDict;
434 i++;
435 }
436 }
437 string xmlString = ServerUtils.BuildXmlResponse(result);
438 //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
439 UTF8Encoding encoding = new UTF8Encoding();
440 return encoding.GetBytes(xmlString);
441 }
442
443 byte[] GetFallbackRegions(Dictionary<string, object> request)
444 {
445 //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange");
446 UUID scopeID = UUID.Zero;
447 if (request.ContainsKey("SCOPEID"))
448 UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
449 else
450 m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get fallback regions");
451
452 int x = 0, y = 0;
453 if (request.ContainsKey("X"))
454 Int32.TryParse(request["X"].ToString(), out x);
455 else
456 m_log.WarnFormat("[GRID HANDLER]: no X in request to get fallback regions");
457 if (request.ContainsKey("Y"))
458 Int32.TryParse(request["Y"].ToString(), out y);
459 else
460 m_log.WarnFormat("[GRID HANDLER]: no Y in request to get fallback regions");
461
462
463 List<GridRegion> rinfos = m_GridService.GetFallbackRegions(scopeID, x, y);
464
465 Dictionary<string, object> result = new Dictionary<string, object>();
466 if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
467 result["result"] = "null";
468 else
469 {
470 int i = 0;
471 foreach (GridRegion rinfo in rinfos)
472 {
473 Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
474 result["region" + i] = rinfoDict;
475 i++;
476 }
477 }
478 string xmlString = ServerUtils.BuildXmlResponse(result);
479 //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
480 UTF8Encoding encoding = new UTF8Encoding();
481 return encoding.GetBytes(xmlString);
482 }
483
407 #endregion 484 #endregion
408 485
409 #region Misc 486 #region Misc
diff --git a/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs b/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs
new file mode 100644
index 0000000..aaa958b
--- /dev/null
+++ b/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs
@@ -0,0 +1,149 @@
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;
30using System.IO;
31using System.Reflection;
32using System.Net;
33using System.Text;
34
35using OpenSim.Server.Base;
36using OpenSim.Server.Handlers.Base;
37using OpenSim.Services.Interfaces;
38using OpenSim.Framework;
39using OpenSim.Framework.Servers.HttpServer;
40
41using OpenMetaverse;
42using OpenMetaverse.StructuredData;
43using Nwc.XmlRpc;
44using Nini.Config;
45using log4net;
46
47
48namespace OpenSim.Server.Handlers.Login
49{
50 public class LLLoginHandlers
51 {
52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
53
54 private ILoginService m_LocalService;
55
56 public LLLoginHandlers(ILoginService service)
57 {
58 m_LocalService = service;
59 }
60
61 public XmlRpcResponse HandleXMLRPCLogin(XmlRpcRequest request, IPEndPoint remoteClient)
62 {
63 Hashtable requestData = (Hashtable)request.Params[0];
64
65 if (requestData != null)
66 {
67 if (requestData.ContainsKey("first") && requestData["first"] != null &&
68 requestData.ContainsKey("last") && requestData["last"] != null &&
69 requestData.ContainsKey("passwd") && requestData["passwd"] != null)
70 {
71 string first = requestData["first"].ToString();
72 string last = requestData["last"].ToString();
73 string passwd = requestData["passwd"].ToString();
74 string startLocation = string.Empty;
75 if (requestData.ContainsKey("start"))
76 startLocation = requestData["start"].ToString();
77
78 string clientVersion = "Unknown";
79 if (requestData.Contains("version"))
80 clientVersion = requestData["version"].ToString();
81 // We should do something interesting with the client version...
82
83 m_log.InfoFormat("[LOGIN]: XMLRPC Login Requested for {0} {1}, starting in {2}, using {3}", first, last, startLocation, clientVersion);
84
85 LoginResponse reply = null;
86 reply = m_LocalService.Login(first, last, passwd, startLocation, remoteClient);
87
88 XmlRpcResponse response = new XmlRpcResponse();
89 response.Value = reply.ToHashtable();
90 return response;
91
92 }
93 }
94
95 return FailedXMLRPCResponse();
96
97 }
98
99 public OSD HandleLLSDLogin(OSD request, IPEndPoint remoteClient)
100 {
101 if (request.Type == OSDType.Map)
102 {
103 OSDMap map = (OSDMap)request;
104
105 if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
106 {
107 string startLocation = string.Empty;
108
109 if (map.ContainsKey("start"))
110 startLocation = map["start"].AsString();
111
112 m_log.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" + map["last"].AsString() + "' / " + startLocation);
113
114 LoginResponse reply = null;
115 reply = m_LocalService.Login(map["first"].AsString(), map["last"].AsString(), map["passwd"].AsString(), startLocation, remoteClient);
116 return reply.ToOSDMap();
117
118 }
119 }
120
121 return FailedOSDResponse();
122 }
123
124 private XmlRpcResponse FailedXMLRPCResponse()
125 {
126 Hashtable hash = new Hashtable();
127 hash["reason"] = "key";
128 hash["message"] = "Incomplete login credentials. Check your username and password.";
129 hash["login"] = "false";
130
131 XmlRpcResponse response = new XmlRpcResponse();
132 response.Value = hash;
133
134 return response;
135 }
136
137 private OSD FailedOSDResponse()
138 {
139 OSDMap map = new OSDMap();
140
141 map["reason"] = OSD.FromString("key");
142 map["message"] = OSD.FromString("Invalid login credentials. Check your username and passwd.");
143 map["login"] = OSD.FromString("false");
144
145 return map;
146 }
147 }
148
149}
diff --git a/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs b/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs
new file mode 100644
index 0000000..e24055b
--- /dev/null
+++ b/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs
@@ -0,0 +1,95 @@
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 System.Reflection;
31using log4net;
32using Nini.Config;
33using OpenSim.Server.Base;
34using OpenSim.Services.Interfaces;
35using OpenSim.Framework;
36using OpenSim.Framework.Servers.HttpServer;
37using OpenSim.Server.Handlers.Base;
38
39namespace OpenSim.Server.Handlers.Login
40{
41 public class LLLoginServiceInConnector : ServiceConnector
42 {
43 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
44
45 private ILoginService m_LoginService;
46
47 public LLLoginServiceInConnector(IConfigSource config, IHttpServer server, IScene scene) :
48 base(config, server, String.Empty)
49 {
50 m_log.Debug("[LLLOGIN IN CONNECTOR]: Starting...");
51 string loginService = ReadLocalServiceFromConfig(config);
52
53 ISimulationService simService = scene.RequestModuleInterface<ISimulationService>();
54 ILibraryService libService = scene.RequestModuleInterface<ILibraryService>();
55
56 Object[] args = new Object[] { config, simService, libService };
57 m_LoginService = ServerUtils.LoadPlugin<ILoginService>(loginService, args);
58
59 InitializeHandlers(server);
60 }
61
62 public LLLoginServiceInConnector(IConfigSource config, IHttpServer server) :
63 base(config, server, String.Empty)
64 {
65 string loginService = ReadLocalServiceFromConfig(config);
66
67 Object[] args = new Object[] { config };
68
69 m_LoginService = ServerUtils.LoadPlugin<ILoginService>(loginService, args);
70
71 InitializeHandlers(server);
72 }
73
74 private string ReadLocalServiceFromConfig(IConfigSource config)
75 {
76 IConfig serverConfig = config.Configs["LoginService"];
77 if (serverConfig == null)
78 throw new Exception(String.Format("No section LoginService in config file"));
79
80 string loginService = serverConfig.GetString("LocalServiceModule", String.Empty);
81 if (loginService == string.Empty)
82 throw new Exception(String.Format("No LocalServiceModule for LoginService in config file"));
83
84 return loginService;
85 }
86
87 private void InitializeHandlers(IHttpServer server)
88 {
89 LLLoginHandlers loginHandlers = new LLLoginHandlers(m_LoginService);
90 server.AddXmlRPCHandler("login_to_simulator", loginHandlers.HandleXMLRPCLogin, false);
91 server.SetDefaultLLSDHandler(loginHandlers.HandleLLSDLogin);
92 }
93
94 }
95}
diff --git a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs
index b5ae54a..d180bbb 100644
--- a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs
+++ b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs
@@ -65,7 +65,7 @@ namespace OpenSim.Server.Handlers.Presence
65 body = body.Trim(); 65 body = body.Trim();
66 66
67 //m_log.DebugFormat("[XXX]: query String: {0}", body); 67 //m_log.DebugFormat("[XXX]: query String: {0}", body);
68 68 string method = string.Empty;
69 try 69 try
70 { 70 {
71 Dictionary<string, object> request = 71 Dictionary<string, object> request =
@@ -74,56 +74,192 @@ namespace OpenSim.Server.Handlers.Presence
74 if (!request.ContainsKey("METHOD")) 74 if (!request.ContainsKey("METHOD"))
75 return FailureResult(); 75 return FailureResult();
76 76
77 string method = request["METHOD"].ToString(); 77 method = request["METHOD"].ToString();
78 78
79 switch (method) 79 switch (method)
80 { 80 {
81 case "login":
82 return LoginAgent(request);
83 case "logout":
84 return LogoutAgent(request);
85 case "logoutregion":
86 return LogoutRegionAgents(request);
81 case "report": 87 case "report":
82 return Report(request); 88 return Report(request);
89 case "getagent":
90 return GetAgent(request);
91 case "getagents":
92 return GetAgents(request);
93 case "sethome":
94 return SetHome(request);
83 } 95 }
84 m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method); 96 m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method);
85 } 97 }
86 catch (Exception e) 98 catch (Exception e)
87 { 99 {
88 m_log.Debug("[PRESENCE HANDLER]: Exception {0}" + e); 100 m_log.DebugFormat("[PRESENCE HANDLER]: Exception in method {0}: {1}", method, e);
89 } 101 }
90 102
91 return FailureResult(); 103 return FailureResult();
92 104
93 } 105 }
94 106
107 byte[] LoginAgent(Dictionary<string, object> request)
108 {
109 string user = String.Empty;
110 UUID session = UUID.Zero;
111 UUID ssession = UUID.Zero;
112
113 if (!request.ContainsKey("UserID") || !request.ContainsKey("SessionID"))
114 return FailureResult();
115
116 user = request["UserID"].ToString();
117
118 if (!UUID.TryParse(request["SessionID"].ToString(), out session))
119 return FailureResult();
120
121 if (request.ContainsKey("SecureSessionID"))
122 // If it's malformed, we go on with a Zero on it
123 UUID.TryParse(request["SecureSessionID"].ToString(), out ssession);
124
125 if (m_PresenceService.LoginAgent(user, session, ssession))
126 return SuccessResult();
127
128 return FailureResult();
129 }
130
131 byte[] LogoutAgent(Dictionary<string, object> request)
132 {
133 UUID session = UUID.Zero;
134 Vector3 position = Vector3.Zero;
135 Vector3 lookat = Vector3.Zero;
136
137 if (!request.ContainsKey("SessionID"))
138 return FailureResult();
139
140 if (!UUID.TryParse(request["SessionID"].ToString(), out session))
141 return FailureResult();
142
143 if (request.ContainsKey("Position") && request["Position"] != null)
144 Vector3.TryParse(request["Position"].ToString(), out position);
145 if (request.ContainsKey("LookAt") && request["Position"] != null)
146 Vector3.TryParse(request["LookAt"].ToString(), out lookat);
147
148 if (m_PresenceService.LogoutAgent(session, position, lookat))
149 return SuccessResult();
150
151 return FailureResult();
152 }
153
154 byte[] LogoutRegionAgents(Dictionary<string, object> request)
155 {
156 UUID region = UUID.Zero;
157
158 if (!request.ContainsKey("RegionID"))
159 return FailureResult();
160
161 if (!UUID.TryParse(request["RegionID"].ToString(), out region))
162 return FailureResult();
163
164 if (m_PresenceService.LogoutRegionAgents(region))
165 return SuccessResult();
166
167 return FailureResult();
168 }
169
95 byte[] Report(Dictionary<string, object> request) 170 byte[] Report(Dictionary<string, object> request)
96 { 171 {
97 PresenceInfo info = new PresenceInfo(); 172 UUID session = UUID.Zero;
98 info.Data = new Dictionary<string, string>(); 173 UUID region = UUID.Zero;
174 Vector3 position = new Vector3(128, 128, 70);
175 Vector3 look = Vector3.Zero;
99 176
100 if (!request.ContainsKey("PrincipalID") || !request.ContainsKey("RegionID")) 177 if (!request.ContainsKey("SessionID") || !request.ContainsKey("RegionID"))
101 return FailureResult(); 178 return FailureResult();
102 179
103 if (!UUID.TryParse(request["PrincipalID"].ToString(), 180 if (!UUID.TryParse(request["SessionID"].ToString(), out session))
104 out info.PrincipalID))
105 return FailureResult(); 181 return FailureResult();
106 182
107 if (!UUID.TryParse(request["RegionID"].ToString(), 183 if (!UUID.TryParse(request["RegionID"].ToString(), out region))
108 out info.RegionID))
109 return FailureResult(); 184 return FailureResult();
110 185
111 foreach (KeyValuePair<string, object> kvp in request) 186 if (request.ContainsKey("position"))
112 { 187 Vector3.TryParse(request["position"].ToString(), out position);
113 if (kvp.Key == "METHOD" ||
114 kvp.Key == "PrincipalID" ||
115 kvp.Key == "RegionID")
116 continue;
117 188
118 info.Data[kvp.Key] = kvp.Value.ToString(); 189 if (request.ContainsKey("lookAt"))
119 } 190 Vector3.TryParse(request["lookAt"].ToString(), out look);
120 191
121 if (m_PresenceService.Report(info)) 192 if (m_PresenceService.ReportAgent(session, region, position, look))
193 {
122 return SuccessResult(); 194 return SuccessResult();
195 }
123 196
124 return FailureResult(); 197 return FailureResult();
125 } 198 }
126 199
200 byte[] GetAgent(Dictionary<string, object> request)
201 {
202 UUID session = UUID.Zero;
203
204 if (!request.ContainsKey("SessionID"))
205 return FailureResult();
206
207 if (!UUID.TryParse(request["SessionID"].ToString(), out session))
208 return FailureResult();
209
210 PresenceInfo pinfo = m_PresenceService.GetAgent(session);
211
212 Dictionary<string, object> result = new Dictionary<string, object>();
213 if (pinfo == null)
214 result["result"] = "null";
215 else
216 result["result"] = pinfo.ToKeyValuePairs();
217
218 string xmlString = ServerUtils.BuildXmlResponse(result);
219 //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
220 UTF8Encoding encoding = new UTF8Encoding();
221 return encoding.GetBytes(xmlString);
222 }
223
224 byte[] GetAgents(Dictionary<string, object> request)
225 {
226
227 string[] userIDs;
228
229 if (!request.ContainsKey("uuids"))
230 return FailureResult();
231
232 if (!(request["uuids"] is List<string>))
233 {
234 m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents input argument was of unexpected type {0}", request["uuids"].GetType().ToString());
235 return FailureResult();
236 }
237
238 userIDs = ((List<string>)request["uuids"]).ToArray();
239
240 PresenceInfo[] pinfos = m_PresenceService.GetAgents(userIDs);
241
242 Dictionary<string, object> result = new Dictionary<string, object>();
243 if ((pinfos == null) || ((pinfos != null) && (pinfos.Length == 0)))
244 result["result"] = "null";
245 else
246 {
247 int i = 0;
248 foreach (PresenceInfo pinfo in pinfos)
249 {
250 Dictionary<string, object> rinfoDict = pinfo.ToKeyValuePairs();
251 result["presence" + i] = rinfoDict;
252 i++;
253 }
254 }
255
256 string xmlString = ServerUtils.BuildXmlResponse(result);
257 //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
258 UTF8Encoding encoding = new UTF8Encoding();
259 return encoding.GetBytes(xmlString);
260 }
261
262
127 private byte[] SuccessResult() 263 private byte[] SuccessResult()
128 { 264 {
129 XmlDocument doc = new XmlDocument(); 265 XmlDocument doc = new XmlDocument();
@@ -138,7 +274,7 @@ namespace OpenSim.Server.Handlers.Presence
138 274
139 doc.AppendChild(rootElement); 275 doc.AppendChild(rootElement);
140 276
141 XmlElement result = doc.CreateElement("", "Result", ""); 277 XmlElement result = doc.CreateElement("", "result", "");
142 result.AppendChild(doc.CreateTextNode("Success")); 278 result.AppendChild(doc.CreateTextNode("Success"));
143 279
144 rootElement.AppendChild(result); 280 rootElement.AppendChild(result);
@@ -160,7 +296,7 @@ namespace OpenSim.Server.Handlers.Presence
160 296
161 doc.AppendChild(rootElement); 297 doc.AppendChild(rootElement);
162 298
163 XmlElement result = doc.CreateElement("", "Result", ""); 299 XmlElement result = doc.CreateElement("", "result", "");
164 result.AppendChild(doc.CreateTextNode("Failure")); 300 result.AppendChild(doc.CreateTextNode("Failure"));
165 301
166 rootElement.AppendChild(result); 302 rootElement.AppendChild(result);
@@ -178,5 +314,32 @@ namespace OpenSim.Server.Handlers.Presence
178 314
179 return ms.ToArray(); 315 return ms.ToArray();
180 } 316 }
317
318 byte[] SetHome(Dictionary<string, object> request)
319 {
320 UUID region = UUID.Zero;
321 Vector3 position = new Vector3(128, 128, 70);
322 Vector3 look = Vector3.Zero;
323
324 if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID"))
325 return FailureResult();
326
327 string user = request["UserID"].ToString();
328
329 if (!UUID.TryParse(request["RegionID"].ToString(), out region))
330 return FailureResult();
331
332 if (request.ContainsKey("position"))
333 Vector3.TryParse(request["position"].ToString(), out position);
334
335 if (request.ContainsKey("lookAt"))
336 Vector3.TryParse(request["lookAt"].ToString(), out look);
337
338 if (m_PresenceService.SetHomeLocation(user, region, position, look))
339 return SuccessResult();
340
341 return FailureResult();
342 }
343
181 } 344 }
182} 345}
diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs
index 3da72c7..45e88ce 100644
--- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs
+++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs
@@ -26,6 +26,7 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Collections;
29using System.IO; 30using System.IO;
30using System.Reflection; 31using System.Reflection;
31using System.Net; 32using System.Net;
@@ -34,6 +35,7 @@ using System.Text;
34using OpenSim.Server.Base; 35using OpenSim.Server.Base;
35using OpenSim.Server.Handlers.Base; 36using OpenSim.Server.Handlers.Base;
36using OpenSim.Services.Interfaces; 37using OpenSim.Services.Interfaces;
38using GridRegion = OpenSim.Services.Interfaces.GridRegion;
37using OpenSim.Framework; 39using OpenSim.Framework;
38using OpenSim.Framework.Servers.HttpServer; 40using OpenSim.Framework.Servers.HttpServer;
39 41
@@ -45,93 +47,111 @@ using log4net;
45 47
46namespace OpenSim.Server.Handlers.Simulation 48namespace OpenSim.Server.Handlers.Simulation
47{ 49{
48 public class AgentGetHandler : BaseStreamHandler 50 public class AgentHandler
49 { 51 {
50 // TODO: unused: private ISimulationService m_SimulationService; 52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51 // TODO: unused: private IAuthenticationService m_AuthenticationService; 53 private ISimulationService m_SimulationService;
52 54
53 public AgentGetHandler(ISimulationService service, IAuthenticationService authentication) : 55 public AgentHandler(ISimulationService sim)
54 base("GET", "/agent")
55 { 56 {
56 // TODO: unused: m_SimulationService = service; 57 m_SimulationService = sim;
57 // TODO: unused: m_AuthenticationService = authentication;
58 } 58 }
59 59
60 public override byte[] Handle(string path, Stream request, 60 public Hashtable Handler(Hashtable request)
61 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
62 { 61 {
63 // Not implemented yet 62 //m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
64 httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
65 return new byte[] { };
66 }
67 }
68 63
69 public class AgentPostHandler : BaseStreamHandler 64 //m_log.Debug("---------------------------");
70 { 65 //m_log.Debug(" >> uri=" + request["uri"]);
71 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 66 //m_log.Debug(" >> content-type=" + request["content-type"]);
72 private ISimulationService m_SimulationService; 67 //m_log.Debug(" >> http-method=" + request["http-method"]);
73 private IAuthenticationService m_AuthenticationService; 68 //m_log.Debug("---------------------------\n");
74 // TODO: unused: private bool m_AllowForeignGuests;
75 69
76 public AgentPostHandler(ISimulationService service, IAuthenticationService authentication, bool foreignGuests) : 70 Hashtable responsedata = new Hashtable();
77 base("POST", "/agent") 71 responsedata["content_type"] = "text/html";
78 { 72 responsedata["keepalive"] = false;
79 m_SimulationService = service;
80 m_AuthenticationService = authentication;
81 // TODO: unused: m_AllowForeignGuests = foreignGuests;
82 }
83 73
84 public override byte[] Handle(string path, Stream request,
85 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
86 {
87 byte[] result = new byte[0];
88 74
89 UUID agentID; 75 UUID agentID;
76 UUID regionID;
90 string action; 77 string action;
91 ulong regionHandle; 78 if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action))
92 if (!RestHandlerUtils.GetParams(path, out agentID, out regionHandle, out action))
93 { 79 {
94 m_log.InfoFormat("[AgentPostHandler]: Invalid parameters for agent message {0}", path); 80 m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
95 httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; 81 responsedata["int_response_code"] = 404;
96 httpResponse.StatusDescription = "Invalid parameters for agent message " + path; 82 responsedata["str_response_string"] = "false";
97 83
98 return result; 84 return responsedata;
99 } 85 }
100 86
101 if (m_AuthenticationService != null) 87 // Next, let's parse the verb
88 string method = (string)request["http-method"];
89 if (method.Equals("PUT"))
102 { 90 {
103 // Authentication 91 DoAgentPut(request, responsedata);
104 string authority = string.Empty; 92 return responsedata;
105 string authToken = string.Empty; 93 }
106 if (!RestHandlerUtils.GetAuthentication(httpRequest, out authority, out authToken)) 94 else if (method.Equals("POST"))
107 { 95 {
108 m_log.InfoFormat("[AgentPostHandler]: Authentication failed for agent message {0}", path); 96 DoAgentPost(request, responsedata, agentID);
109 httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; 97 return responsedata;
110 return result; 98 }
111 } 99 else if (method.Equals("GET"))
112 // TODO: Rethink this 100 {
113 //if (!m_AuthenticationService.VerifyKey(agentID, authToken)) 101 DoAgentGet(request, responsedata, agentID, regionID);
114 //{ 102 return responsedata;
115 // m_log.InfoFormat("[AgentPostHandler]: Authentication failed for agent message {0}", path); 103 }
116 // httpResponse.StatusCode = (int)HttpStatusCode.Forbidden; 104 else if (method.Equals("DELETE"))
117 // return result; 105 {
118 //} 106 DoAgentDelete(request, responsedata, agentID, action, regionID);
119 m_log.DebugFormat("[AgentPostHandler]: Authentication succeeded for {0}", agentID); 107 return responsedata;
120 } 108 }
109 else
110 {
111 m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method);
112 responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
113 responsedata["str_response_string"] = "Method not allowed";
114
115 return responsedata;
116 }
117
118 }
121 119
122 OSDMap args = Util.GetOSDMap(request, (int)httpRequest.ContentLength); 120 protected virtual void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
121 {
122 OSDMap args = Utils.GetOSDMap((string)request["body"]);
123 if (args == null) 123 if (args == null)
124 { 124 {
125 httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; 125 responsedata["int_response_code"] = HttpStatusCode.BadRequest;
126 httpResponse.StatusDescription = "Unable to retrieve data"; 126 responsedata["str_response_string"] = "Bad request";
127 m_log.DebugFormat("[AgentPostHandler]: Unable to retrieve data for post {0}", path); 127 return;
128 return result;
129 } 128 }
130 129
131 // retrieve the regionhandle 130 // retrieve the input arguments
132 ulong regionhandle = 0; 131 int x = 0, y = 0;
133 if (args["destination_handle"] != null) 132 UUID uuid = UUID.Zero;
134 UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle); 133 string regionname = string.Empty;
134 uint teleportFlags = 0;
135 if (args.ContainsKey("destination_x") && args["destination_x"] != null)
136 Int32.TryParse(args["destination_x"].AsString(), out x);
137 else
138 m_log.WarnFormat(" -- request didn't have destination_x");
139 if (args.ContainsKey("destination_y") && args["destination_y"] != null)
140 Int32.TryParse(args["destination_y"].AsString(), out y);
141 else
142 m_log.WarnFormat(" -- request didn't have destination_y");
143 if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
144 UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
145 if (args.ContainsKey("destination_name") && args["destination_name"] != null)
146 regionname = args["destination_name"].ToString();
147 if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
148 teleportFlags = args["teleport_flags"].AsUInteger();
149
150 GridRegion destination = new GridRegion();
151 destination.RegionID = uuid;
152 destination.RegionLocX = x;
153 destination.RegionLocY = y;
154 destination.RegionName = regionname;
135 155
136 AgentCircuitData aCircuit = new AgentCircuitData(); 156 AgentCircuitData aCircuit = new AgentCircuitData();
137 try 157 try
@@ -140,70 +160,168 @@ namespace OpenSim.Server.Handlers.Simulation
140 } 160 }
141 catch (Exception ex) 161 catch (Exception ex)
142 { 162 {
143 m_log.InfoFormat("[AgentPostHandler]: exception on unpacking CreateAgent message {0}", ex.Message); 163 m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
144 httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; 164 responsedata["int_response_code"] = HttpStatusCode.BadRequest;
145 httpResponse.StatusDescription = "Problems with data deserialization"; 165 responsedata["str_response_string"] = "Bad request";
146 return result; 166 return;
147 } 167 }
148 168
149 string reason = string.Empty; 169 OSDMap resp = new OSDMap(2);
170 string reason = String.Empty;
150 171
151 // We need to clean up a few things in the user service before I can do this 172 // This is the meaning of POST agent
152 //if (m_AllowForeignGuests) 173 //m_regionClient.AdjustUserInformation(aCircuit);
153 // m_regionClient.AdjustUserInformation(aCircuit); 174 bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
154 175
155 // Finally! 176 resp["reason"] = OSD.FromString(reason);
156 bool success = m_SimulationService.CreateAgent(regionhandle, aCircuit, out reason); 177 resp["success"] = OSD.FromBoolean(result);
157 178
158 OSDMap resp = new OSDMap(1); 179 // TODO: add reason if not String.Empty?
180 responsedata["int_response_code"] = HttpStatusCode.OK;
181 responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
182 }
159 183
160 resp["success"] = OSD.FromBoolean(success); 184 protected virtual void DoAgentPut(Hashtable request, Hashtable responsedata)
185 {
186 OSDMap args = Utils.GetOSDMap((string)request["body"]);
187 if (args == null)
188 {
189 responsedata["int_response_code"] = HttpStatusCode.BadRequest;
190 responsedata["str_response_string"] = "Bad request";
191 return;
192 }
161 193
162 httpResponse.StatusCode = (int)HttpStatusCode.OK; 194 // retrieve the input arguments
195 int x = 0, y = 0;
196 UUID uuid = UUID.Zero;
197 string regionname = string.Empty;
198 if (args.ContainsKey("destination_x") && args["destination_x"] != null)
199 Int32.TryParse(args["destination_x"].AsString(), out x);
200 if (args.ContainsKey("destination_y") && args["destination_y"] != null)
201 Int32.TryParse(args["destination_y"].AsString(), out y);
202 if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
203 UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
204 if (args.ContainsKey("destination_name") && args["destination_name"] != null)
205 regionname = args["destination_name"].ToString();
163 206
164 return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)); 207 GridRegion destination = new GridRegion();
165 } 208 destination.RegionID = uuid;
166 } 209 destination.RegionLocX = x;
210 destination.RegionLocY = y;
211 destination.RegionName = regionname;
167 212
168 public class AgentPutHandler : BaseStreamHandler 213 string messageType;
169 { 214 if (args["message_type"] != null)
170 // TODO: unused: private ISimulationService m_SimulationService; 215 messageType = args["message_type"].AsString();
171 // TODO: unused: private IAuthenticationService m_AuthenticationService; 216 else
217 {
218 m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
219 messageType = "AgentData";
220 }
172 221
173 public AgentPutHandler(ISimulationService service, IAuthenticationService authentication) : 222 bool result = true;
174 base("PUT", "/agent") 223 if ("AgentData".Equals(messageType))
175 { 224 {
176 // TODO: unused: m_SimulationService = service; 225 AgentData agent = new AgentData();
177 // TODO: unused: m_AuthenticationService = authentication; 226 try
227 {
228 agent.Unpack(args);
229 }
230 catch (Exception ex)
231 {
232 m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
233 responsedata["int_response_code"] = HttpStatusCode.BadRequest;
234 responsedata["str_response_string"] = "Bad request";
235 return;
236 }
237
238 //agent.Dump();
239 // This is one of the meanings of PUT agent
240 result = m_SimulationService.UpdateAgent(destination, agent);
241
242 }
243 else if ("AgentPosition".Equals(messageType))
244 {
245 AgentPosition agent = new AgentPosition();
246 try
247 {
248 agent.Unpack(args);
249 }
250 catch (Exception ex)
251 {
252 m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
253 return;
254 }
255 //agent.Dump();
256 // This is one of the meanings of PUT agent
257 result = m_SimulationService.UpdateAgent(destination, agent);
258
259 }
260
261 responsedata["int_response_code"] = HttpStatusCode.OK;
262 responsedata["str_response_string"] = result.ToString();
263 //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
178 } 264 }
179 265
180 public override byte[] Handle(string path, Stream request, 266 protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
181 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
182 { 267 {
183 // Not implemented yet 268 GridRegion destination = new GridRegion();
184 httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented; 269 destination.RegionID = regionID;
185 return new byte[] { };
186 }
187 }
188 270
189 public class AgentDeleteHandler : BaseStreamHandler 271 IAgentData agent = null;
190 { 272 bool result = m_SimulationService.RetrieveAgent(destination, id, out agent);
191 // TODO: unused: private ISimulationService m_SimulationService; 273 OSDMap map = null;
192 // TODO: unused: private IAuthenticationService m_AuthenticationService; 274 if (result)
275 {
276 if (agent != null) // just to make sure
277 {
278 map = agent.Pack();
279 string strBuffer = "";
280 try
281 {
282 strBuffer = OSDParser.SerializeJsonString(map);
283 }
284 catch (Exception e)
285 {
286 m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message);
287 responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
288 // ignore. buffer will be empty, caller should check.
289 }
193 290
194 public AgentDeleteHandler(ISimulationService service, IAuthenticationService authentication) : 291 responsedata["content_type"] = "application/json";
195 base("DELETE", "/agent") 292 responsedata["int_response_code"] = HttpStatusCode.OK;
196 { 293 responsedata["str_response_string"] = strBuffer;
197 // TODO: unused: m_SimulationService = service; 294 }
198 // TODO: unused: m_AuthenticationService = authentication; 295 else
296 {
297 responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
298 responsedata["str_response_string"] = "Internal error";
299 }
300 }
301 else
302 {
303 responsedata["int_response_code"] = HttpStatusCode.NotFound;
304 responsedata["str_response_string"] = "Not Found";
305 }
199 } 306 }
200 307
201 public override byte[] Handle(string path, Stream request, 308 protected virtual void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID)
202 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
203 { 309 {
204 // Not implemented yet 310 m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID);
205 httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented; 311
206 return new byte[] { }; 312 GridRegion destination = new GridRegion();
313 destination.RegionID = regionID;
314
315 if (action.Equals("release"))
316 m_SimulationService.ReleaseAgent(regionID, id, "");
317 else
318 m_SimulationService.CloseAgent(destination, id);
319
320 responsedata["int_response_code"] = HttpStatusCode.OK;
321 responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
322
323 m_log.Debug("[AGENT HANDLER]: Agent Released/Deleted.");
207 } 324 }
208 } 325 }
326
209} 327}
diff --git a/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs b/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs
new file mode 100644
index 0000000..b6eabe3
--- /dev/null
+++ b/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs
@@ -0,0 +1,238 @@
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;
30using System.IO;
31using System.Reflection;
32using System.Net;
33using System.Text;
34
35using OpenSim.Server.Base;
36using OpenSim.Server.Handlers.Base;
37using OpenSim.Services.Interfaces;
38using GridRegion = OpenSim.Services.Interfaces.GridRegion;
39using OpenSim.Framework;
40using OpenSim.Framework.Servers.HttpServer;
41
42using OpenMetaverse;
43using OpenMetaverse.StructuredData;
44using Nini.Config;
45using log4net;
46
47
48namespace OpenSim.Server.Handlers.Simulation
49{
50 public class ObjectHandler
51 {
52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
53 private ISimulationService m_SimulationService;
54
55 public ObjectHandler(ISimulationService sim)
56 {
57 m_SimulationService = sim;
58 }
59
60 public Hashtable Handler(Hashtable request)
61 {
62 //m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called");
63
64 //m_log.Debug("---------------------------");
65 //m_log.Debug(" >> uri=" + request["uri"]);
66 //m_log.Debug(" >> content-type=" + request["content-type"]);
67 //m_log.Debug(" >> http-method=" + request["http-method"]);
68 //m_log.Debug("---------------------------\n");
69
70 Hashtable responsedata = new Hashtable();
71 responsedata["content_type"] = "text/html";
72
73 UUID objectID;
74 UUID regionID;
75 string action;
76 if (!Utils.GetParams((string)request["uri"], out objectID, out regionID, out action))
77 {
78 m_log.InfoFormat("[OBJECT HANDLER]: Invalid parameters for object message {0}", request["uri"]);
79 responsedata["int_response_code"] = 404;
80 responsedata["str_response_string"] = "false";
81
82 return responsedata;
83 }
84
85 // Next, let's parse the verb
86 string method = (string)request["http-method"];
87 if (method.Equals("POST"))
88 {
89 DoObjectPost(request, responsedata, regionID);
90 return responsedata;
91 }
92 else if (method.Equals("PUT"))
93 {
94 DoObjectPut(request, responsedata, regionID);
95 return responsedata;
96 }
97 //else if (method.Equals("DELETE"))
98 //{
99 // DoObjectDelete(request, responsedata, agentID, action, regionHandle);
100 // return responsedata;
101 //}
102 else
103 {
104 m_log.InfoFormat("[OBJECT HANDLER]: method {0} not supported in object message", method);
105 responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
106 responsedata["str_response_string"] = "Mthod not allowed";
107
108 return responsedata;
109 }
110
111 }
112
113 protected virtual void DoObjectPost(Hashtable request, Hashtable responsedata, UUID regionID)
114 {
115 OSDMap args = Utils.GetOSDMap((string)request["body"]);
116 if (args == null)
117 {
118 responsedata["int_response_code"] = 400;
119 responsedata["str_response_string"] = "false";
120 return;
121 }
122 // retrieve the input arguments
123 int x = 0, y = 0;
124 UUID uuid = UUID.Zero;
125 string regionname = string.Empty;
126 if (args.ContainsKey("destination_x") && args["destination_x"] != null)
127 Int32.TryParse(args["destination_x"].AsString(), out x);
128 if (args.ContainsKey("destination_y") && args["destination_y"] != null)
129 Int32.TryParse(args["destination_y"].AsString(), out y);
130 if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
131 UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
132 if (args.ContainsKey("destination_name") && args["destination_name"] != null)
133 regionname = args["destination_name"].ToString();
134
135 GridRegion destination = new GridRegion();
136 destination.RegionID = uuid;
137 destination.RegionLocX = x;
138 destination.RegionLocY = y;
139 destination.RegionName = regionname;
140
141 string sogXmlStr = "", extraStr = "", stateXmlStr = "";
142 if (args.ContainsKey("sog") && args["sog"] != null)
143 sogXmlStr = args["sog"].AsString();
144 if (args.ContainsKey("extra") && args["extra"] != null)
145 extraStr = args["extra"].AsString();
146
147 IScene s = m_SimulationService.GetScene(destination.RegionHandle);
148 ISceneObject sog = null;
149 try
150 {
151 //m_log.DebugFormat("[OBJECT HANDLER]: received {0}", sogXmlStr);
152 sog = s.DeserializeObject(sogXmlStr);
153 sog.ExtraFromXmlString(extraStr);
154 }
155 catch (Exception ex)
156 {
157 m_log.InfoFormat("[OBJECT HANDLER]: exception on deserializing scene object {0}", ex.Message);
158 responsedata["int_response_code"] = HttpStatusCode.BadRequest;
159 responsedata["str_response_string"] = "Bad request";
160 return;
161 }
162
163 if ((args["state"] != null) && s.AllowScriptCrossings)
164 {
165 stateXmlStr = args["state"].AsString();
166 if (stateXmlStr != "")
167 {
168 try
169 {
170 sog.SetState(stateXmlStr, s);
171 }
172 catch (Exception ex)
173 {
174 m_log.InfoFormat("[OBJECT HANDLER]: exception on setting state for scene object {0}", ex.Message);
175 // ignore and continue
176 }
177 }
178 }
179
180 bool result = false;
181 try
182 {
183 // This is the meaning of POST object
184 result = m_SimulationService.CreateObject(destination, sog, false);
185 }
186 catch (Exception e)
187 {
188 m_log.DebugFormat("[OBJECT HANDLER]: Exception in CreateObject: {0}", e.StackTrace);
189 }
190
191 responsedata["int_response_code"] = HttpStatusCode.OK;
192 responsedata["str_response_string"] = result.ToString();
193 }
194
195 protected virtual void DoObjectPut(Hashtable request, Hashtable responsedata, UUID regionID)
196 {
197 OSDMap args = Utils.GetOSDMap((string)request["body"]);
198 if (args == null)
199 {
200 responsedata["int_response_code"] = 400;
201 responsedata["str_response_string"] = "false";
202 return;
203 }
204
205 // retrieve the input arguments
206 int x = 0, y = 0;
207 UUID uuid = UUID.Zero;
208 string regionname = string.Empty;
209 if (args.ContainsKey("destination_x") && args["destination_x"] != null)
210 Int32.TryParse(args["destination_x"].AsString(), out x);
211 if (args.ContainsKey("destination_y") && args["destination_y"] != null)
212 Int32.TryParse(args["destination_y"].AsString(), out y);
213 if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
214 UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
215 if (args.ContainsKey("destination_name") && args["destination_name"] != null)
216 regionname = args["destination_name"].ToString();
217
218 GridRegion destination = new GridRegion();
219 destination.RegionID = uuid;
220 destination.RegionLocX = x;
221 destination.RegionLocY = y;
222 destination.RegionName = regionname;
223
224 UUID userID = UUID.Zero, itemID = UUID.Zero;
225 if (args.ContainsKey("userid") && args["userid"] != null)
226 userID = args["userid"].AsUUID();
227 if (args.ContainsKey("itemid") && args["itemid"] != null)
228 itemID = args["itemid"].AsUUID();
229
230 // This is the meaning of PUT object
231 bool result = m_SimulationService.CreateObject(destination, userID, itemID);
232
233 responsedata["int_response_code"] = 200;
234 responsedata["str_response_string"] = result.ToString();
235 }
236
237 }
238} \ No newline at end of file
diff --git a/OpenSim/Server/Handlers/Simulation/SimulationServiceInConnector.cs b/OpenSim/Server/Handlers/Simulation/SimulationServiceInConnector.cs
index fe93fa5..55a575c 100644
--- a/OpenSim/Server/Handlers/Simulation/SimulationServiceInConnector.cs
+++ b/OpenSim/Server/Handlers/Simulation/SimulationServiceInConnector.cs
@@ -37,22 +37,15 @@ namespace OpenSim.Server.Handlers.Simulation
37{ 37{
38 public class SimulationServiceInConnector : ServiceConnector 38 public class SimulationServiceInConnector : ServiceConnector
39 { 39 {
40 private ISimulationService m_SimulationService; 40 private ISimulationService m_LocalSimulationService;
41 private IAuthenticationService m_AuthenticationService; 41 private IAuthenticationService m_AuthenticationService;
42 42
43 public SimulationServiceInConnector(IConfigSource config, IHttpServer server, IScene scene) : 43 public SimulationServiceInConnector(IConfigSource config, IHttpServer server, IScene scene) :
44 base(config, server, String.Empty) 44 base(config, server, String.Empty)
45 { 45 {
46 IConfig serverConfig = config.Configs["SimulationService"]; 46 //IConfig serverConfig = config.Configs["SimulationService"];
47 if (serverConfig == null) 47 //if (serverConfig == null)
48 throw new Exception("No section 'SimulationService' in config file"); 48 // throw new Exception("No section 'SimulationService' in config file");
49
50 bool authentication = serverConfig.GetBoolean("RequireAuthentication", false);
51
52 if (authentication)
53 m_AuthenticationService = scene.RequestModuleInterface<IAuthenticationService>();
54
55 bool foreignGuests = serverConfig.GetBoolean("AllowForeignGuests", false);
56 49
57 //string simService = serverConfig.GetString("LocalServiceModule", 50 //string simService = serverConfig.GetString("LocalServiceModule",
58 // String.Empty); 51 // String.Empty);
@@ -61,20 +54,18 @@ namespace OpenSim.Server.Handlers.Simulation
61 // throw new Exception("No SimulationService in config file"); 54 // throw new Exception("No SimulationService in config file");
62 55
63 //Object[] args = new Object[] { config }; 56 //Object[] args = new Object[] { config };
64 m_SimulationService = scene.RequestModuleInterface<ISimulationService>(); 57 m_LocalSimulationService = scene.RequestModuleInterface<ISimulationService>();
65 //ServerUtils.LoadPlugin<ISimulationService>(simService, args); 58 //ServerUtils.LoadPlugin<ISimulationService>(simService, args);
66 if (m_SimulationService == null)
67 throw new Exception("No Local ISimulationService Module");
68
69
70 59
71 //System.Console.WriteLine("XXXXXXXXXXXXXXXXXXX m_AssetSetvice == null? " + ((m_AssetService == null) ? "yes" : "no")); 60 //System.Console.WriteLine("XXXXXXXXXXXXXXXXXXX m_AssetSetvice == null? " + ((m_AssetService == null) ? "yes" : "no"));
72 server.AddStreamHandler(new AgentGetHandler(m_SimulationService, m_AuthenticationService)); 61 //server.AddStreamHandler(new AgentGetHandler(m_SimulationService, m_AuthenticationService));
73 server.AddStreamHandler(new AgentPostHandler(m_SimulationService, m_AuthenticationService, foreignGuests)); 62 //server.AddStreamHandler(new AgentPostHandler(m_SimulationService, m_AuthenticationService));
74 server.AddStreamHandler(new AgentPutHandler(m_SimulationService, m_AuthenticationService)); 63 //server.AddStreamHandler(new AgentPutHandler(m_SimulationService, m_AuthenticationService));
75 server.AddStreamHandler(new AgentDeleteHandler(m_SimulationService, m_AuthenticationService)); 64 //server.AddStreamHandler(new AgentDeleteHandler(m_SimulationService, m_AuthenticationService));
65 server.AddHTTPHandler("/agent/", new AgentHandler(m_LocalSimulationService).Handler);
66 server.AddHTTPHandler("/object/", new ObjectHandler(m_LocalSimulationService).Handler);
67
76 //server.AddStreamHandler(new ObjectPostHandler(m_SimulationService, authentication)); 68 //server.AddStreamHandler(new ObjectPostHandler(m_SimulationService, authentication));
77 //server.AddStreamHandler(new NeighborPostHandler(m_SimulationService, authentication));
78 } 69 }
79 } 70 }
80} 71}
diff --git a/OpenSim/Server/Handlers/Simulation/Utils.cs b/OpenSim/Server/Handlers/Simulation/Utils.cs
new file mode 100644
index 0000000..ed379da
--- /dev/null
+++ b/OpenSim/Server/Handlers/Simulation/Utils.cs
@@ -0,0 +1,103 @@
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 System.Reflection;
31
32using OpenMetaverse;
33using OpenMetaverse.StructuredData;
34
35using log4net;
36
37namespace OpenSim.Server.Handlers.Simulation
38{
39 public class Utils
40 {
41 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
42
43 /// <summary>
44 /// Extract the param from an uri.
45 /// </summary>
46 /// <param name="uri">Something like this: /agent/uuid/ or /agent/uuid/handle/release</param>
47 /// <param name="uri">uuid on uuid field</param>
48 /// <param name="action">optional action</param>
49 public static bool GetParams(string uri, out UUID uuid, out UUID regionID, out string action)
50 {
51 uuid = UUID.Zero;
52 regionID = UUID.Zero;
53 action = "";
54
55 uri = uri.Trim(new char[] { '/' });
56 string[] parts = uri.Split('/');
57 if (parts.Length <= 1)
58 {
59 return false;
60 }
61 else
62 {
63 if (!UUID.TryParse(parts[1], out uuid))
64 return false;
65
66 if (parts.Length >= 3)
67 UUID.TryParse(parts[2], out regionID);
68 if (parts.Length >= 4)
69 action = parts[3];
70
71 return true;
72 }
73 }
74
75 public static OSDMap GetOSDMap(string data)
76 {
77 OSDMap args = null;
78 try
79 {
80 OSD buffer;
81 // We should pay attention to the content-type, but let's assume we know it's Json
82 buffer = OSDParser.DeserializeJson(data);
83 if (buffer.Type == OSDType.Map)
84 {
85 args = (OSDMap)buffer;
86 return args;
87 }
88 else
89 {
90 // uh?
91 m_log.Debug(("[REST COMMS]: Got OSD of unexpected type " + buffer.Type.ToString()));
92 return null;
93 }
94 }
95 catch (Exception ex)
96 {
97 m_log.Debug("[REST COMMS]: exception on parse of REST message " + ex.Message);
98 return null;
99 }
100 }
101
102 }
103}
diff --git a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs
new file mode 100644
index 0000000..f17a8de
--- /dev/null
+++ b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs
@@ -0,0 +1,61 @@
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 Nini.Config;
30using OpenSim.Server.Base;
31using OpenSim.Services.Interfaces;
32using OpenSim.Framework.Servers.HttpServer;
33using OpenSim.Server.Handlers.Base;
34
35namespace OpenSim.Server.Handlers.UserAccounts
36{
37 public class UserAccountServiceConnector : ServiceConnector
38 {
39 private IUserAccountService m_UserAccountService;
40 private string m_ConfigName = "UserAccountService";
41
42 public UserAccountServiceConnector(IConfigSource config, IHttpServer server, string configName) :
43 base(config, server, configName)
44 {
45 IConfig serverConfig = config.Configs[m_ConfigName];
46 if (serverConfig == null)
47 throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
48
49 string service = serverConfig.GetString("LocalServiceModule",
50 String.Empty);
51
52 if (service == String.Empty)
53 throw new Exception("No LocalServiceModule in config file");
54
55 Object[] args = new Object[] { config };
56 m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(service, args);
57
58 server.AddStreamHandler(new UserAccountServerPostHandler(m_UserAccountService));
59 }
60 }
61}
diff --git a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs
new file mode 100644
index 0000000..6a82165
--- /dev/null
+++ b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs
@@ -0,0 +1,258 @@
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 Nini.Config;
29using log4net;
30using System;
31using System.Reflection;
32using System.IO;
33using System.Net;
34using System.Text;
35using System.Text.RegularExpressions;
36using System.Xml;
37using System.Xml.Serialization;
38using System.Collections.Generic;
39using OpenSim.Server.Base;
40using OpenSim.Services.Interfaces;
41using OpenSim.Framework;
42using OpenSim.Framework.Servers.HttpServer;
43using OpenMetaverse;
44
45namespace OpenSim.Server.Handlers.UserAccounts
46{
47 public class UserAccountServerPostHandler : BaseStreamHandler
48 {
49 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
50
51 private IUserAccountService m_UserAccountService;
52
53 public UserAccountServerPostHandler(IUserAccountService service) :
54 base("POST", "/accounts")
55 {
56 m_UserAccountService = service;
57 }
58
59 public override byte[] Handle(string path, Stream requestData,
60 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
61 {
62 StreamReader sr = new StreamReader(requestData);
63 string body = sr.ReadToEnd();
64 sr.Close();
65 body = body.Trim();
66
67 // We need to check the authorization header
68 //httpRequest.Headers["authorization"] ...
69
70 //m_log.DebugFormat("[XXX]: query String: {0}", body);
71 string method = string.Empty;
72 try
73 {
74 Dictionary<string, object> request =
75 ServerUtils.ParseQueryString(body);
76
77 if (!request.ContainsKey("METHOD"))
78 return FailureResult();
79
80 method = request["METHOD"].ToString();
81
82 switch (method)
83 {
84 case "getaccount":
85 return GetAccount(request);
86 case "getaccounts":
87 return GetAccounts(request);
88 case "setaccount":
89 return StoreAccount(request);
90 }
91 m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method);
92 }
93 catch (Exception e)
94 {
95 m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e);
96 }
97
98 return FailureResult();
99
100 }
101
102 byte[] GetAccount(Dictionary<string, object> request)
103 {
104 UserAccount account = null;
105 UUID scopeID = UUID.Zero;
106 Dictionary<string, object> result = new Dictionary<string, object>();
107
108 if (!request.ContainsKey("ScopeID"))
109 {
110 result["result"] = "null";
111 return ResultToBytes(result);
112 }
113
114 if (!UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
115 {
116 result["result"] = "null";
117 return ResultToBytes(result);
118 }
119
120 if (request.ContainsKey("UserID") && request["UserID"] != null)
121 {
122 UUID userID;
123 if (UUID.TryParse(request["UserID"].ToString(), out userID))
124 account = m_UserAccountService.GetUserAccount(scopeID, userID);
125 }
126
127 else if (request.ContainsKey("Email") && request["Email"] != null)
128 account = m_UserAccountService.GetUserAccount(scopeID, request["Email"].ToString());
129
130 else if (request.ContainsKey("FirstName") && request.ContainsKey("LastName") &&
131 request["FirstName"] != null && request["LastName"] != null)
132 account = m_UserAccountService.GetUserAccount(scopeID, request["FirstName"].ToString(), request["LastName"].ToString());
133
134 if (account == null)
135 result["result"] = "null";
136 else
137 {
138 result["result"] = account.ToKeyValuePairs();
139 }
140
141 return ResultToBytes(result);
142 }
143
144 byte[] GetAccounts(Dictionary<string, object> request)
145 {
146 if (!request.ContainsKey("ScopeID") || !request.ContainsKey("query"))
147 return FailureResult();
148
149 UUID scopeID = UUID.Zero;
150 if (!UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
151 return FailureResult();
152
153 string query = request["query"].ToString();
154
155 List<UserAccount> accounts = m_UserAccountService.GetUserAccounts(scopeID, query);
156
157 Dictionary<string, object> result = new Dictionary<string, object>();
158 if ((accounts == null) || ((accounts != null) && (accounts.Count == 0)))
159 result["result"] = "null";
160 else
161 {
162 int i = 0;
163 foreach (UserAccount acc in accounts)
164 {
165 Dictionary<string, object> rinfoDict = acc.ToKeyValuePairs();
166 result["account" + i] = rinfoDict;
167 i++;
168 }
169 }
170
171 string xmlString = ServerUtils.BuildXmlResponse(result);
172 //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
173 UTF8Encoding encoding = new UTF8Encoding();
174 return encoding.GetBytes(xmlString);
175 }
176
177 byte[] StoreAccount(Dictionary<string, object> request)
178 {
179 //if (!request.ContainsKey("account"))
180 // return FailureResult();
181 //if (request["account"] == null)
182 // return FailureResult();
183 //if (!(request["account"] is Dictionary<string, object>))
184 // return FailureResult();
185
186 UserAccount account = new UserAccount(request);
187
188 if (m_UserAccountService.StoreUserAccount(account))
189 return SuccessResult();
190
191 return FailureResult();
192 }
193
194 private byte[] SuccessResult()
195 {
196 XmlDocument doc = new XmlDocument();
197
198 XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
199 "", "");
200
201 doc.AppendChild(xmlnode);
202
203 XmlElement rootElement = doc.CreateElement("", "ServerResponse",
204 "");
205
206 doc.AppendChild(rootElement);
207
208 XmlElement result = doc.CreateElement("", "result", "");
209 result.AppendChild(doc.CreateTextNode("Success"));
210
211 rootElement.AppendChild(result);
212
213 return DocToBytes(doc);
214 }
215
216 private byte[] FailureResult()
217 {
218 XmlDocument doc = new XmlDocument();
219
220 XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
221 "", "");
222
223 doc.AppendChild(xmlnode);
224
225 XmlElement rootElement = doc.CreateElement("", "ServerResponse",
226 "");
227
228 doc.AppendChild(rootElement);
229
230 XmlElement result = doc.CreateElement("", "result", "");
231 result.AppendChild(doc.CreateTextNode("Failure"));
232
233 rootElement.AppendChild(result);
234
235 return DocToBytes(doc);
236 }
237
238 private byte[] DocToBytes(XmlDocument doc)
239 {
240 MemoryStream ms = new MemoryStream();
241 XmlTextWriter xw = new XmlTextWriter(ms, null);
242 xw.Formatting = Formatting.Indented;
243 doc.WriteTo(xw);
244 xw.Flush();
245
246 return ms.ToArray();
247 }
248
249 private byte[] ResultToBytes(Dictionary<string, object> result)
250 {
251 string xmlString = ServerUtils.BuildXmlResponse(result);
252 UTF8Encoding encoding = new UTF8Encoding();
253 return encoding.GetBytes(xmlString);
254 }
255
256
257 }
258}