aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Services
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Services')
-rw-r--r--OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs29
-rw-r--r--OpenSim/Services/AuthenticationService/PasswordAuthenticationService.cs10
-rw-r--r--OpenSim/Services/AvatarService/AvatarService.cs144
-rw-r--r--OpenSim/Services/AvatarService/AvatarServiceBase.cs84
-rw-r--r--OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs10
-rw-r--r--OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs317
-rw-r--r--OpenSim/Services/Connectors/Grid/GridServiceConnector.cs107
-rw-r--r--OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs423
-rw-r--r--OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs575
-rw-r--r--OpenSim/Services/Connectors/User/UserServiceConnector.cs114
-rw-r--r--OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs277
-rw-r--r--OpenSim/Services/GridService/GridService.cs259
-rw-r--r--OpenSim/Services/Interfaces/IAuthenticationService.cs11
-rw-r--r--OpenSim/Services/Interfaces/IAvatarService.cs241
-rw-r--r--OpenSim/Services/Interfaces/IGridService.cs15
-rw-r--r--OpenSim/Services/Interfaces/ILibraryService.cs (renamed from OpenSim/Services/UserService/UserService.cs)49
-rw-r--r--OpenSim/Services/Interfaces/ILoginService.cs53
-rw-r--r--OpenSim/Services/Interfaces/IPresenceService.cs88
-rw-r--r--OpenSim/Services/Interfaces/ISimulationService.cs26
-rw-r--r--OpenSim/Services/Interfaces/IUserAccountService.cs153
-rw-r--r--OpenSim/Services/Interfaces/IUserService.cs103
-rw-r--r--OpenSim/Services/InventoryService/InventoryService.cs1
-rw-r--r--OpenSim/Services/InventoryService/LibraryService.cs283
-rw-r--r--OpenSim/Services/LLLoginService/LLLoginResponse.cs971
-rw-r--r--OpenSim/Services/LLLoginService/LLLoginService.cs494
-rw-r--r--OpenSim/Services/PresenceService/PresenceService.cs172
-rw-r--r--OpenSim/Services/PresenceService/PresenceServiceBase.cs4
-rw-r--r--OpenSim/Services/UserAccountService/UserAccountService.cs359
-rw-r--r--OpenSim/Services/UserAccountService/UserAccountServiceBase.cs (renamed from OpenSim/Services/UserService/UserServiceBase.cs)19
29 files changed, 5083 insertions, 308 deletions
diff --git a/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs b/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs
index dcf090e..f6dd085 100644
--- a/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs
+++ b/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs
@@ -32,6 +32,7 @@ using Nini.Config;
32using System.Reflection; 32using System.Reflection;
33using OpenSim.Services.Base; 33using OpenSim.Services.Base;
34using OpenSim.Data; 34using OpenSim.Data;
35using OpenSim.Framework;
35 36
36namespace OpenSim.Services.AuthenticationService 37namespace OpenSim.Services.AuthenticationService
37{ 38{
@@ -43,9 +44,9 @@ namespace OpenSim.Services.AuthenticationService
43 // 44 //
44 public class AuthenticationServiceBase : ServiceBase 45 public class AuthenticationServiceBase : ServiceBase
45 { 46 {
46// private static readonly ILog m_log = 47 private static readonly ILog m_log =
47// LogManager.GetLogger( 48 LogManager.GetLogger(
48// MethodBase.GetCurrentMethod().DeclaringType); 49 MethodBase.GetCurrentMethod().DeclaringType);
49 50
50 protected IAuthenticationData m_Database; 51 protected IAuthenticationData m_Database;
51 52
@@ -100,6 +101,27 @@ namespace OpenSim.Services.AuthenticationService
100 return m_Database.CheckToken(principalID, token, 0); 101 return m_Database.CheckToken(principalID, token, 0);
101 } 102 }
102 103
104 public virtual bool SetPassword(UUID principalID, string password)
105 {
106 string passwordSalt = Util.Md5Hash(UUID.Random().ToString());
107 string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + passwordSalt);
108
109 AuthenticationData auth = new AuthenticationData();
110 auth.PrincipalID = principalID;
111 auth.Data = new System.Collections.Generic.Dictionary<string, object>();
112 auth.Data["passwordHash"] = md5PasswdHash;
113 auth.Data["passwordSalt"] = passwordSalt;
114 auth.Data["webLoginKey"] = UUID.Zero.ToString();
115 if (!m_Database.Store(auth))
116 {
117 m_log.DebugFormat("[AUTHENTICATION DB]: Failed to store authentication data");
118 return false;
119 }
120
121 m_log.InfoFormat("[AUTHENTICATION DB]: Set password for principalID {0}", principalID);
122 return true;
123 }
124
103 protected string GetToken(UUID principalID, int lifetime) 125 protected string GetToken(UUID principalID, int lifetime)
104 { 126 {
105 UUID token = UUID.Random(); 127 UUID token = UUID.Random();
@@ -109,5 +131,6 @@ namespace OpenSim.Services.AuthenticationService
109 131
110 return String.Empty; 132 return String.Empty;
111 } 133 }
134
112 } 135 }
113} 136}
diff --git a/OpenSim/Services/AuthenticationService/PasswordAuthenticationService.cs b/OpenSim/Services/AuthenticationService/PasswordAuthenticationService.cs
index d65665a..021dcf3 100644
--- a/OpenSim/Services/AuthenticationService/PasswordAuthenticationService.cs
+++ b/OpenSim/Services/AuthenticationService/PasswordAuthenticationService.cs
@@ -47,9 +47,9 @@ namespace OpenSim.Services.AuthenticationService
47 public class PasswordAuthenticationService : 47 public class PasswordAuthenticationService :
48 AuthenticationServiceBase, IAuthenticationService 48 AuthenticationServiceBase, IAuthenticationService
49 { 49 {
50// private static readonly ILog m_log = 50 //private static readonly ILog m_log =
51// LogManager.GetLogger( 51 // LogManager.GetLogger(
52// MethodBase.GetCurrentMethod().DeclaringType); 52 // MethodBase.GetCurrentMethod().DeclaringType);
53 53
54 public PasswordAuthenticationService(IConfigSource config) : 54 public PasswordAuthenticationService(IConfigSource config) :
55 base(config) 55 base(config)
@@ -66,9 +66,11 @@ namespace OpenSim.Services.AuthenticationService
66 return String.Empty; 66 return String.Empty;
67 } 67 }
68 68
69 string hashed = Util.Md5Hash(Util.Md5Hash(password) + ":" + 69 string hashed = Util.Md5Hash(password + ":" +
70 data.Data["passwordSalt"].ToString()); 70 data.Data["passwordSalt"].ToString());
71 71
72 //m_log.DebugFormat("[PASS AUTH]: got {0}; hashed = {1}; stored = {2}", password, hashed, data.Data["passwordHash"].ToString());
73
72 if (data.Data["passwordHash"].ToString() == hashed) 74 if (data.Data["passwordHash"].ToString() == hashed)
73 { 75 {
74 return GetToken(principalID, lifetime); 76 return GetToken(principalID, lifetime);
diff --git a/OpenSim/Services/AvatarService/AvatarService.cs b/OpenSim/Services/AvatarService/AvatarService.cs
new file mode 100644
index 0000000..19e662c
--- /dev/null
+++ b/OpenSim/Services/AvatarService/AvatarService.cs
@@ -0,0 +1,144 @@
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.Net;
31using System.Reflection;
32using Nini.Config;
33using log4net;
34using OpenSim.Framework;
35using OpenSim.Framework.Console;
36using OpenSim.Data;
37using OpenSim.Services.Interfaces;
38using OpenMetaverse;
39
40namespace OpenSim.Services.AvatarService
41{
42 public class AvatarService : AvatarServiceBase, IAvatarService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48 public AvatarService(IConfigSource config)
49 : base(config)
50 {
51 m_log.Debug("[AVATAR SERVICE]: Starting avatar service");
52 }
53
54 public AvatarData GetAvatar(UUID principalID)
55 {
56 AvatarBaseData[] av = m_Database.Get("PrincipalID", principalID.ToString());
57 if (av.Length == 0)
58 return null;
59
60 AvatarData ret = new AvatarData();
61 ret.Data = new Dictionary<string,string>();
62
63 foreach (AvatarBaseData b in av)
64 {
65 if (b.Data["Name"] == "AvatarType")
66 ret.AvatarType = Convert.ToInt32(b.Data["Value"]);
67 else
68 ret.Data[b.Data["Name"]] = b.Data["Value"];
69 }
70
71 return ret;
72 }
73
74 public bool SetAvatar(UUID principalID, AvatarData avatar)
75 {
76 int count = 0;
77 foreach (KeyValuePair<string, string> kvp in avatar.Data)
78 if (kvp.Key.StartsWith("_"))
79 count++;
80
81 m_log.DebugFormat("[AVATAR SERVICE]: SetAvatar for {0}, attachs={1}", principalID, count);
82 m_Database.Delete("PrincipalID", principalID.ToString());
83
84 AvatarBaseData av = new AvatarBaseData();
85 av.Data = new Dictionary<string,string>();
86
87 av.PrincipalID = principalID;
88 av.Data["Name"] = "AvatarType";
89 av.Data["Value"] = avatar.AvatarType.ToString();
90
91 if (!m_Database.Store(av))
92 return false;
93
94 foreach (KeyValuePair<string,string> kvp in avatar.Data)
95 {
96 av.Data["Name"] = kvp.Key;
97 av.Data["Value"] = kvp.Value;
98
99 if (!m_Database.Store(av))
100 {
101 m_Database.Delete("PrincipalID", principalID.ToString());
102 return false;
103 }
104 }
105
106 return true;
107 }
108
109 public bool ResetAvatar(UUID principalID)
110 {
111 return m_Database.Delete("PrincipalID", principalID.ToString());
112 }
113
114 public bool SetItems(UUID principalID, string[] names, string[] values)
115 {
116 AvatarBaseData av = new AvatarBaseData();
117 av.Data = new Dictionary<string,string>();
118 av.PrincipalID = principalID;
119
120 if (names.Length != values.Length)
121 return false;
122
123 for (int i = 0 ; i < names.Length ; i++)
124 {
125 av.Data["Name"] = names[i];
126 av.Data["Value"] = values[i];
127
128 if (!m_Database.Store(av))
129 return false;
130 }
131
132 return true;
133 }
134
135 public bool RemoveItems(UUID principalID, string[] names)
136 {
137 foreach (string name in names)
138 {
139 m_Database.Delete(principalID, name);
140 }
141 return true;
142 }
143 }
144}
diff --git a/OpenSim/Services/AvatarService/AvatarServiceBase.cs b/OpenSim/Services/AvatarService/AvatarServiceBase.cs
new file mode 100644
index 0000000..ab9d7cd
--- /dev/null
+++ b/OpenSim/Services/AvatarService/AvatarServiceBase.cs
@@ -0,0 +1,84 @@
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 OpenSim.Framework;
32using OpenSim.Data;
33using OpenSim.Services.Interfaces;
34using OpenSim.Services.Base;
35
36namespace OpenSim.Services.AvatarService
37{
38 public class AvatarServiceBase : ServiceBase
39 {
40 protected IAvatarData m_Database = null;
41
42 public AvatarServiceBase(IConfigSource config)
43 : base(config)
44 {
45 string dllName = String.Empty;
46 string connString = String.Empty;
47 string realm = "Avatars";
48
49 //
50 // Try reading the [DatabaseService] section, if it exists
51 //
52 IConfig dbConfig = config.Configs["DatabaseService"];
53 if (dbConfig != null)
54 {
55 if (dllName == String.Empty)
56 dllName = dbConfig.GetString("StorageProvider", String.Empty);
57 if (connString == String.Empty)
58 connString = dbConfig.GetString("ConnectionString", String.Empty);
59 }
60
61 //
62 // [AvatarService] section overrides [DatabaseService], if it exists
63 //
64 IConfig presenceConfig = config.Configs["AvatarService"];
65 if (presenceConfig != null)
66 {
67 dllName = presenceConfig.GetString("StorageProvider", dllName);
68 connString = presenceConfig.GetString("ConnectionString", connString);
69 realm = presenceConfig.GetString("Realm", realm);
70 }
71
72 //
73 // We tried, but this doesn't exist. We can't proceed.
74 //
75 if (dllName.Equals(String.Empty))
76 throw new Exception("No StorageProvider configured");
77
78 m_Database = LoadPlugin<IAvatarData>(dllName, new Object[] { connString, realm });
79 if (m_Database == null)
80 throw new Exception("Could not find a storage interface in the given module " + dllName);
81
82 }
83 }
84}
diff --git a/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs b/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs
index 19bb3e2..f36fe5b 100644
--- a/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs
+++ b/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs
@@ -67,7 +67,7 @@ namespace OpenSim.Services.Connectors
67 IConfig assetConfig = source.Configs["AuthenticationService"]; 67 IConfig assetConfig = source.Configs["AuthenticationService"];
68 if (assetConfig == null) 68 if (assetConfig == null)
69 { 69 {
70 m_log.Error("[USER CONNECTOR]: AuthenticationService missing from OpanSim.ini"); 70 m_log.Error("[AUTH CONNECTOR]: AuthenticationService missing from OpanSim.ini");
71 throw new Exception("Authentication connector init error"); 71 throw new Exception("Authentication connector init error");
72 } 72 }
73 73
@@ -76,7 +76,7 @@ namespace OpenSim.Services.Connectors
76 76
77 if (serviceURI == String.Empty) 77 if (serviceURI == String.Empty)
78 { 78 {
79 m_log.Error("[USER CONNECTOR]: No Server URI named in section AuthenticationService"); 79 m_log.Error("[AUTH CONNECTOR]: No Server URI named in section AuthenticationService");
80 throw new Exception("Authentication connector init error"); 80 throw new Exception("Authentication connector init error");
81 } 81 }
82 m_ServerURI = serviceURI; 82 m_ServerURI = serviceURI;
@@ -146,5 +146,11 @@ namespace OpenSim.Services.Connectors
146 146
147 return true; 147 return true;
148 } 148 }
149
150 public bool SetPassword(UUID principalID, string passwd)
151 {
152 // nope, we don't do this
153 return false;
154 }
149 } 155 }
150} 156}
diff --git a/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs b/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs
new file mode 100644
index 0000000..96c05a9
--- /dev/null
+++ b/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs
@@ -0,0 +1,317 @@
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 log4net;
29using System;
30using System.Collections.Generic;
31using System.IO;
32using System.Reflection;
33using Nini.Config;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications;
36using OpenSim.Framework.Servers.HttpServer;
37using OpenSim.Services.Interfaces;
38using GridRegion = OpenSim.Services.Interfaces.GridRegion;
39using IAvatarService = OpenSim.Services.Interfaces.IAvatarService;
40using OpenSim.Server.Base;
41using OpenMetaverse;
42
43namespace OpenSim.Services.Connectors
44{
45 public class AvatarServicesConnector : IAvatarService
46 {
47 private static readonly ILog m_log =
48 LogManager.GetLogger(
49 MethodBase.GetCurrentMethod().DeclaringType);
50
51 private string m_ServerURI = String.Empty;
52
53 public AvatarServicesConnector()
54 {
55 }
56
57 public AvatarServicesConnector(string serverURI)
58 {
59 m_ServerURI = serverURI.TrimEnd('/');
60 }
61
62 public AvatarServicesConnector(IConfigSource source)
63 {
64 Initialise(source);
65 }
66
67 public virtual void Initialise(IConfigSource source)
68 {
69 IConfig gridConfig = source.Configs["AvatarService"];
70 if (gridConfig == null)
71 {
72 m_log.Error("[AVATAR CONNECTOR]: AvatarService missing from OpenSim.ini");
73 throw new Exception("Avatar connector init error");
74 }
75
76 string serviceURI = gridConfig.GetString("AvatarServerURI",
77 String.Empty);
78
79 if (serviceURI == String.Empty)
80 {
81 m_log.Error("[AVATAR CONNECTOR]: No Server URI named in section AvatarService");
82 throw new Exception("Avatar connector init error");
83 }
84 m_ServerURI = serviceURI;
85 }
86
87
88 #region IAvatarService
89
90 public AvatarData GetAvatar(UUID userID)
91 {
92 Dictionary<string, object> sendData = new Dictionary<string, object>();
93 //sendData["SCOPEID"] = scopeID.ToString();
94 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
95 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
96 sendData["METHOD"] = "getavatar";
97
98 sendData["UserID"] = userID;
99
100 string reply = string.Empty;
101 string reqString = ServerUtils.BuildQueryString(sendData);
102 // m_log.DebugFormat("[AVATAR CONNECTOR]: queryString = {0}", reqString);
103 try
104 {
105 reply = SynchronousRestFormsRequester.MakeRequest("POST",
106 m_ServerURI + "/avatar",
107 reqString);
108 if (reply == null || (reply != null && reply == string.Empty))
109 {
110 m_log.DebugFormat("[AVATAR CONNECTOR]: GetAgent received null or empty reply");
111 return null;
112 }
113 }
114 catch (Exception e)
115 {
116 m_log.DebugFormat("[AVATAR CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
117 }
118
119 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
120 AvatarData avatar = null;
121
122 if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
123 {
124 if (replyData["result"] is Dictionary<string, object>)
125 {
126 avatar = new AvatarData((Dictionary<string, object>)replyData["result"]);
127 }
128 }
129
130 return avatar;
131
132 }
133
134 public bool SetAvatar(UUID userID, AvatarData avatar)
135 {
136 Dictionary<string, object> sendData = new Dictionary<string, object>();
137 //sendData["SCOPEID"] = scopeID.ToString();
138 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
139 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
140 sendData["METHOD"] = "setavatar";
141
142 sendData["UserID"] = userID.ToString();
143
144 Dictionary<string, object> structData = avatar.ToKeyValuePairs();
145
146 foreach (KeyValuePair<string, object> kvp in structData)
147 sendData[kvp.Key] = kvp.Value.ToString();
148
149
150 string reqString = ServerUtils.BuildQueryString(sendData);
151 //m_log.DebugFormat("[AVATAR CONNECTOR]: queryString = {0}", reqString);
152 try
153 {
154 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
155 m_ServerURI + "/avatar",
156 reqString);
157 if (reply != string.Empty)
158 {
159 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
160
161 if (replyData.ContainsKey("result"))
162 {
163 if (replyData["result"].ToString().ToLower() == "success")
164 return true;
165 else
166 return false;
167 }
168 else
169 m_log.DebugFormat("[AVATAR CONNECTOR]: SetAvatar reply data does not contain result field");
170
171 }
172 else
173 m_log.DebugFormat("[AVATAR CONNECTOR]: SetAvatar received empty reply");
174 }
175 catch (Exception e)
176 {
177 m_log.DebugFormat("[AVATAR CONNECTOR]: Exception when contacting avatar server: {0}", e.Message);
178 }
179
180 return false;
181 }
182
183 public bool ResetAvatar(UUID userID)
184 {
185 Dictionary<string, object> sendData = new Dictionary<string, object>();
186 //sendData["SCOPEID"] = scopeID.ToString();
187 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
188 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
189 sendData["METHOD"] = "resetavatar";
190
191 sendData["UserID"] = userID.ToString();
192
193 string reqString = ServerUtils.BuildQueryString(sendData);
194 // m_log.DebugFormat("[AVATAR CONNECTOR]: queryString = {0}", reqString);
195 try
196 {
197 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
198 m_ServerURI + "/avatar",
199 reqString);
200 if (reply != string.Empty)
201 {
202 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
203
204 if (replyData.ContainsKey("result"))
205 {
206 if (replyData["result"].ToString().ToLower() == "success")
207 return true;
208 else
209 return false;
210 }
211 else
212 m_log.DebugFormat("[AVATAR CONNECTOR]: SetItems reply data does not contain result field");
213
214 }
215 else
216 m_log.DebugFormat("[AVATAR CONNECTOR]: SetItems received empty reply");
217 }
218 catch (Exception e)
219 {
220 m_log.DebugFormat("[AVATAR CONNECTOR]: Exception when contacting avatar server: {0}", e.Message);
221 }
222
223 return false;
224 }
225
226 public bool SetItems(UUID userID, string[] names, string[] values)
227 {
228 Dictionary<string, object> sendData = new Dictionary<string, object>();
229 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
230 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
231 sendData["METHOD"] = "setitems";
232
233 sendData["UserID"] = userID.ToString();
234 sendData["Names"] = new List<string>(names);
235 sendData["Values"] = new List<string>(values);
236
237 string reqString = ServerUtils.BuildQueryString(sendData);
238 // m_log.DebugFormat("[AVATAR CONNECTOR]: queryString = {0}", reqString);
239 try
240 {
241 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
242 m_ServerURI + "/avatar",
243 reqString);
244 if (reply != string.Empty)
245 {
246 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
247
248 if (replyData.ContainsKey("result"))
249 {
250 if (replyData["result"].ToString().ToLower() == "success")
251 return true;
252 else
253 return false;
254 }
255 else
256 m_log.DebugFormat("[AVATAR CONNECTOR]: SetItems reply data does not contain result field");
257
258 }
259 else
260 m_log.DebugFormat("[AVATAR CONNECTOR]: SetItems received empty reply");
261 }
262 catch (Exception e)
263 {
264 m_log.DebugFormat("[AVATAR CONNECTOR]: Exception when contacting avatar server: {0}", e.Message);
265 }
266
267 return false;
268 }
269
270 public bool RemoveItems(UUID userID, string[] names)
271 {
272 Dictionary<string, object> sendData = new Dictionary<string, object>();
273 //sendData["SCOPEID"] = scopeID.ToString();
274 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
275 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
276 sendData["METHOD"] = "removeitems";
277
278 sendData["UserID"] = userID.ToString();
279 sendData["Names"] = new List<string>(names);
280
281 string reqString = ServerUtils.BuildQueryString(sendData);
282 // m_log.DebugFormat("[AVATAR CONNECTOR]: queryString = {0}", reqString);
283 try
284 {
285 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
286 m_ServerURI + "/avatar",
287 reqString);
288 if (reply != string.Empty)
289 {
290 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
291
292 if (replyData.ContainsKey("result"))
293 {
294 if (replyData["result"].ToString().ToLower() == "success")
295 return true;
296 else
297 return false;
298 }
299 else
300 m_log.DebugFormat("[AVATAR CONNECTOR]: RemoveItems reply data does not contain result field");
301
302 }
303 else
304 m_log.DebugFormat("[AVATAR CONNECTOR]: RemoveItems received empty reply");
305 }
306 catch (Exception e)
307 {
308 m_log.DebugFormat("[AVATAR CONNECTOR]: Exception when contacting avatar server: {0}", e.Message);
309 }
310
311 return false;
312 }
313
314 #endregion
315
316 }
317}
diff --git a/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs b/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs
index 04c7c53..a1ca58e 100644
--- a/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs
+++ b/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs
@@ -460,6 +460,113 @@ namespace OpenSim.Services.Connectors
460 return rinfos; 460 return rinfos;
461 } 461 }
462 462
463 public List<GridRegion> GetDefaultRegions(UUID scopeID)
464 {
465 Dictionary<string, object> sendData = new Dictionary<string, object>();
466
467 sendData["SCOPEID"] = scopeID.ToString();
468
469 sendData["METHOD"] = "get_default_regions";
470
471 List<GridRegion> rinfos = new List<GridRegion>();
472 string reply = string.Empty;
473 try
474 {
475 reply = SynchronousRestFormsRequester.MakeRequest("POST",
476 m_ServerURI + "/grid",
477 ServerUtils.BuildQueryString(sendData));
478
479 //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
480 }
481 catch (Exception e)
482 {
483 m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
484 return rinfos;
485 }
486
487 if (reply != string.Empty)
488 {
489 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
490
491 if (replyData != null)
492 {
493 Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
494 foreach (object r in rinfosList)
495 {
496 if (r is Dictionary<string, object>)
497 {
498 GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
499 rinfos.Add(rinfo);
500 }
501 }
502 }
503 else
504 m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions {0} received null response",
505 scopeID);
506 }
507 else
508 m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions received null reply");
509
510 return rinfos;
511 }
512
513 public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
514 {
515 Dictionary<string, object> sendData = new Dictionary<string, object>();
516
517 sendData["SCOPEID"] = scopeID.ToString();
518 sendData["X"] = x.ToString();
519 sendData["Y"] = y.ToString();
520
521 sendData["METHOD"] = "get_fallback_regions";
522
523 List<GridRegion> rinfos = new List<GridRegion>();
524 string reply = string.Empty;
525 try
526 {
527 reply = SynchronousRestFormsRequester.MakeRequest("POST",
528 m_ServerURI + "/grid",
529 ServerUtils.BuildQueryString(sendData));
530
531 //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
532 }
533 catch (Exception e)
534 {
535 m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
536 return rinfos;
537 }
538
539 if (reply != string.Empty)
540 {
541 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
542
543 if (replyData != null)
544 {
545 Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
546 foreach (object r in rinfosList)
547 {
548 if (r is Dictionary<string, object>)
549 {
550 GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
551 rinfos.Add(rinfo);
552 }
553 }
554 }
555 else
556 m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions {0}, {1}-{2} received null response",
557 scopeID, x, y);
558 }
559 else
560 m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions received null reply");
561
562 return rinfos;
563 }
564
565 public int GetRegionFlags(UUID scopeID, UUID regionID)
566 {
567 return 0;
568 }
569
463 #endregion 570 #endregion
464 571
465 } 572 }
diff --git a/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs b/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs
new file mode 100644
index 0000000..fac3d1f
--- /dev/null
+++ b/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs
@@ -0,0 +1,423 @@
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 log4net;
29using System;
30using System.Collections.Generic;
31using System.IO;
32using System.Reflection;
33using Nini.Config;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications;
36using OpenSim.Framework.Servers.HttpServer;
37using OpenSim.Services.Interfaces;
38using GridRegion = OpenSim.Services.Interfaces.GridRegion;
39using OpenSim.Server.Base;
40using OpenMetaverse;
41
42namespace OpenSim.Services.Connectors
43{
44 public class PresenceServicesConnector : IPresenceService
45 {
46 private static readonly ILog m_log =
47 LogManager.GetLogger(
48 MethodBase.GetCurrentMethod().DeclaringType);
49
50 private string m_ServerURI = String.Empty;
51
52 public PresenceServicesConnector()
53 {
54 }
55
56 public PresenceServicesConnector(string serverURI)
57 {
58 m_ServerURI = serverURI.TrimEnd('/');
59 }
60
61 public PresenceServicesConnector(IConfigSource source)
62 {
63 Initialise(source);
64 }
65
66 public virtual void Initialise(IConfigSource source)
67 {
68 IConfig gridConfig = source.Configs["PresenceService"];
69 if (gridConfig == null)
70 {
71 m_log.Error("[PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini");
72 throw new Exception("Presence connector init error");
73 }
74
75 string serviceURI = gridConfig.GetString("PresenceServerURI",
76 String.Empty);
77
78 if (serviceURI == String.Empty)
79 {
80 m_log.Error("[PRESENCE CONNECTOR]: No Server URI named in section PresenceService");
81 throw new Exception("Presence connector init error");
82 }
83 m_ServerURI = serviceURI;
84 }
85
86
87 #region IPresenceService
88
89 public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
90 {
91 Dictionary<string, object> sendData = new Dictionary<string, object>();
92 //sendData["SCOPEID"] = scopeID.ToString();
93 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
94 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
95 sendData["METHOD"] = "login";
96
97 sendData["UserID"] = userID;
98 sendData["SessionID"] = sessionID.ToString();
99 sendData["SecureSessionID"] = secureSessionID.ToString();
100
101 string reqString = ServerUtils.BuildQueryString(sendData);
102 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
103 try
104 {
105 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
106 m_ServerURI + "/presence",
107 reqString);
108 if (reply != string.Empty)
109 {
110 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
111
112 if (replyData.ContainsKey("result"))
113 {
114 if (replyData["result"].ToString().ToLower() == "success")
115 return true;
116 else
117 return false;
118 }
119 else
120 m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent reply data does not contain result field");
121
122 }
123 else
124 m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent received empty reply");
125 }
126 catch (Exception e)
127 {
128 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
129 }
130
131 return false;
132
133 }
134
135 public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookat)
136 {
137 Dictionary<string, object> sendData = new Dictionary<string, object>();
138 //sendData["SCOPEID"] = scopeID.ToString();
139 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
140 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
141 sendData["METHOD"] = "logout";
142
143 sendData["SessionID"] = sessionID.ToString();
144 sendData["Position"] = position.ToString();
145 sendData["LookAt"] = lookat.ToString();
146
147 string reqString = ServerUtils.BuildQueryString(sendData);
148 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
149 try
150 {
151 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
152 m_ServerURI + "/presence",
153 reqString);
154 if (reply != string.Empty)
155 {
156 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
157
158 if (replyData.ContainsKey("result"))
159 {
160 if (replyData["result"].ToString().ToLower() == "success")
161 return true;
162 else
163 return false;
164 }
165 else
166 m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent reply data does not contain result field");
167
168 }
169 else
170 m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent received empty reply");
171 }
172 catch (Exception e)
173 {
174 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
175 }
176
177 return false;
178 }
179
180 public bool LogoutRegionAgents(UUID regionID)
181 {
182 Dictionary<string, object> sendData = new Dictionary<string, object>();
183 //sendData["SCOPEID"] = scopeID.ToString();
184 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
185 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
186 sendData["METHOD"] = "logoutregion";
187
188 sendData["RegionID"] = regionID.ToString();
189
190 string reqString = ServerUtils.BuildQueryString(sendData);
191 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
192 try
193 {
194 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
195 m_ServerURI + "/presence",
196 reqString);
197 if (reply != string.Empty)
198 {
199 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
200
201 if (replyData.ContainsKey("result"))
202 {
203 if (replyData["result"].ToString().ToLower() == "success")
204 return true;
205 else
206 return false;
207 }
208 else
209 m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents reply data does not contain result field");
210
211 }
212 else
213 m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents received empty reply");
214 }
215 catch (Exception e)
216 {
217 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
218 }
219
220 return false;
221 }
222
223 public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt)
224 {
225 Dictionary<string, object> sendData = new Dictionary<string, object>();
226 //sendData["SCOPEID"] = scopeID.ToString();
227 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
228 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
229 sendData["METHOD"] = "report";
230
231 sendData["SessionID"] = sessionID.ToString();
232 sendData["RegionID"] = regionID.ToString();
233 sendData["position"] = position.ToString();
234 sendData["lookAt"] = lookAt.ToString();
235
236 string reqString = ServerUtils.BuildQueryString(sendData);
237 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
238 try
239 {
240 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
241 m_ServerURI + "/presence",
242 reqString);
243 if (reply != string.Empty)
244 {
245 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
246
247 if (replyData.ContainsKey("result"))
248 {
249 if (replyData["result"].ToString().ToLower() == "success")
250 return true;
251 else
252 return false;
253 }
254 else
255 m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent reply data does not contain result field");
256
257 }
258 else
259 m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent received empty reply");
260 }
261 catch (Exception e)
262 {
263 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
264 }
265
266 return false;
267 }
268
269 public PresenceInfo GetAgent(UUID sessionID)
270 {
271 Dictionary<string, object> sendData = new Dictionary<string, object>();
272 //sendData["SCOPEID"] = scopeID.ToString();
273 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
274 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
275 sendData["METHOD"] = "getagent";
276
277 sendData["SessionID"] = sessionID.ToString();
278
279 string reply = string.Empty;
280 string reqString = ServerUtils.BuildQueryString(sendData);
281 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
282 try
283 {
284 reply = SynchronousRestFormsRequester.MakeRequest("POST",
285 m_ServerURI + "/presence",
286 reqString);
287 if (reply == null || (reply != null && reply == string.Empty))
288 {
289 m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply");
290 return null;
291 }
292 }
293 catch (Exception e)
294 {
295 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
296 }
297
298 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
299 PresenceInfo pinfo = null;
300
301 if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
302 {
303 if (replyData["result"] is Dictionary<string, object>)
304 {
305 pinfo = new PresenceInfo((Dictionary<string, object>)replyData["result"]);
306 }
307 }
308
309 return pinfo;
310 }
311
312 public PresenceInfo[] GetAgents(string[] userIDs)
313 {
314 Dictionary<string, object> sendData = new Dictionary<string, object>();
315 //sendData["SCOPEID"] = scopeID.ToString();
316 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
317 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
318 sendData["METHOD"] = "getagents";
319
320 sendData["uuids"] = new List<string>(userIDs);
321
322 string reply = string.Empty;
323 string reqString = ServerUtils.BuildQueryString(sendData);
324 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
325 try
326 {
327 reply = SynchronousRestFormsRequester.MakeRequest("POST",
328 m_ServerURI + "/presence",
329 reqString);
330 if (reply == null || (reply != null && reply == string.Empty))
331 {
332 m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply");
333 return null;
334 }
335 }
336 catch (Exception e)
337 {
338 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
339 }
340
341 List<PresenceInfo> rinfos = new List<PresenceInfo>();
342
343 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
344
345 if (replyData != null)
346 {
347 if (replyData.ContainsKey("result") &&
348 (replyData["result"].ToString() == "null" || replyData["result"].ToString() == "Failure"))
349 {
350 return new PresenceInfo[0];
351 }
352
353 Dictionary<string, object>.ValueCollection pinfosList = replyData.Values;
354 //m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
355 foreach (object presence in pinfosList)
356 {
357 if (presence is Dictionary<string, object>)
358 {
359 PresenceInfo pinfo = new PresenceInfo((Dictionary<string, object>)presence);
360 rinfos.Add(pinfo);
361 }
362 else
363 m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received invalid response type {0}",
364 presence.GetType());
365 }
366 }
367 else
368 m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null response");
369
370 return rinfos.ToArray();
371 }
372
373
374 public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
375 {
376 Dictionary<string, object> sendData = new Dictionary<string, object>();
377 //sendData["SCOPEID"] = scopeID.ToString();
378 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
379 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
380 sendData["METHOD"] = "sethome";
381
382 sendData["UserID"] = userID;
383 sendData["RegionID"] = regionID.ToString();
384 sendData["position"] = position.ToString();
385 sendData["lookAt"] = lookAt.ToString();
386
387 string reqString = ServerUtils.BuildQueryString(sendData);
388 // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString);
389 try
390 {
391 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
392 m_ServerURI + "/presence",
393 reqString);
394 if (reply != string.Empty)
395 {
396 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
397
398 if (replyData.ContainsKey("result"))
399 {
400 if (replyData["result"].ToString().ToLower() == "success")
401 return true;
402 else
403 return false;
404 }
405 else
406 m_log.DebugFormat("[PRESENCE CONNECTOR]: SetHomeLocation reply data does not contain result field");
407
408 }
409 else
410 m_log.DebugFormat("[PRESENCE CONNECTOR]: SetHomeLocation received empty reply");
411 }
412 catch (Exception e)
413 {
414 m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message);
415 }
416
417 return false;
418 }
419
420 #endregion
421
422 }
423}
diff --git a/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs b/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs
new file mode 100644
index 0000000..b1b2a30
--- /dev/null
+++ b/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs
@@ -0,0 +1,575 @@
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.IO;
31using System.Net;
32using System.Reflection;
33using System.Text;
34
35using OpenSim.Framework;
36using OpenSim.Services.Interfaces;
37using GridRegion = OpenSim.Services.Interfaces.GridRegion;
38
39using OpenMetaverse;
40using OpenMetaverse.StructuredData;
41using log4net;
42using Nini.Config;
43
44namespace OpenSim.Services.Connectors.Simulation
45{
46 public class SimulationServiceConnector : ISimulationService
47 {
48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
49
50 //private GridRegion m_Region;
51
52 public SimulationServiceConnector()
53 {
54 }
55
56 public SimulationServiceConnector(IConfigSource config)
57 {
58 //m_Region = region;
59 }
60
61 public IScene GetScene(ulong regionHandle)
62 {
63 return null;
64 }
65
66 #region Agents
67
68 public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason)
69 {
70 reason = String.Empty;
71
72 if (destination == null)
73 {
74 reason = "Destination is null";
75 m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Given destination is null");
76 return false;
77 }
78
79 // Eventually, we want to use a caps url instead of the agentID
80 string uri = string.Empty;
81 try
82 {
83 uri = "http://" + destination.ExternalEndPoint.Address + ":" + destination.HttpPort + "/agent/" + aCircuit.AgentID + "/";
84 }
85 catch (Exception e)
86 {
87 m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Unable to resolve external endpoint on agent create. Reason: " + e.Message);
88 reason = e.Message;
89 return false;
90 }
91
92 //Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri);
93
94 HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
95 AgentCreateRequest.Method = "POST";
96 AgentCreateRequest.ContentType = "application/json";
97 AgentCreateRequest.Timeout = 10000;
98 //AgentCreateRequest.KeepAlive = false;
99 //AgentCreateRequest.Headers.Add("Authorization", authKey);
100
101 // Fill it in
102 OSDMap args = null;
103 try
104 {
105 args = aCircuit.PackAgentCircuitData();
106 }
107 catch (Exception e)
108 {
109 m_log.Debug("[REMOTE SIMULATION CONNECTOR]: PackAgentCircuitData failed with exception: " + e.Message);
110 }
111 // Add the input arguments
112 args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
113 args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
114 args["destination_name"] = OSD.FromString(destination.RegionName);
115 args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
116 args["teleport_flags"] = OSD.FromString(flags.ToString());
117
118 string strBuffer = "";
119 byte[] buffer = new byte[1];
120 try
121 {
122 strBuffer = OSDParser.SerializeJsonString(args);
123 Encoding str = Util.UTF8;
124 buffer = str.GetBytes(strBuffer);
125
126 }
127 catch (Exception e)
128 {
129 m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
130 // ignore. buffer will be empty, caller should check.
131 }
132
133 Stream os = null;
134 try
135 { // send the Post
136 AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
137 os = AgentCreateRequest.GetRequestStream();
138 os.Write(buffer, 0, strBuffer.Length); //Send it
139 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: Posted CreateAgent request to remote sim {0}, region {1}, x={2} y={3}",
140 uri, destination.RegionName, destination.RegionLocX, destination.RegionLocY);
141 }
142 //catch (WebException ex)
143 catch
144 {
145 //m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: Bad send on ChildAgentUpdate {0}", ex.Message);
146 reason = "cannot contact remote region";
147 return false;
148 }
149 finally
150 {
151 if (os != null)
152 os.Close();
153 }
154
155 // Let's wait for the response
156 //m_log.Info("[REMOTE SIMULATION CONNECTOR]: Waiting for a reply after DoCreateChildAgentCall");
157
158 WebResponse webResponse = null;
159 StreamReader sr = null;
160 try
161 {
162 webResponse = AgentCreateRequest.GetResponse();
163 if (webResponse == null)
164 {
165 m_log.Info("[REMOTE SIMULATION CONNECTOR]: Null reply on DoCreateChildAgentCall post");
166 }
167 else
168 {
169
170 sr = new StreamReader(webResponse.GetResponseStream());
171 string response = sr.ReadToEnd().Trim();
172 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: DoCreateChildAgentCall reply was {0} ", response);
173
174 if (!String.IsNullOrEmpty(response))
175 {
176 try
177 {
178 // we assume we got an OSDMap back
179 OSDMap r = Util.GetOSDMap(response);
180 bool success = r["success"].AsBoolean();
181 reason = r["reason"].AsString();
182 return success;
183 }
184 catch (NullReferenceException e)
185 {
186 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
187
188 // check for old style response
189 if (response.ToLower().StartsWith("true"))
190 return true;
191
192 return false;
193 }
194 }
195 }
196 }
197 catch (WebException ex)
198 {
199 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
200 // ignore, really
201 }
202 finally
203 {
204 if (sr != null)
205 sr.Close();
206 }
207
208 return true;
209 }
210
211 public bool UpdateAgent(GridRegion destination, AgentData data)
212 {
213 return UpdateAgent(destination, (IAgentData)data);
214 }
215
216 public bool UpdateAgent(GridRegion destination, AgentPosition data)
217 {
218 return UpdateAgent(destination, (IAgentData)data);
219 }
220
221 private bool UpdateAgent(GridRegion destination, IAgentData cAgentData)
222 {
223 // Eventually, we want to use a caps url instead of the agentID
224 string uri = string.Empty;
225 try
226 {
227 uri = "http://" + destination.ExternalEndPoint.Address + ":" + destination.HttpPort + "/agent/" + cAgentData.AgentID + "/";
228 }
229 catch (Exception e)
230 {
231 m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Unable to resolve external endpoint on agent update. Reason: " + e.Message);
232 return false;
233 }
234 //Console.WriteLine(" >>> DoAgentUpdateCall <<< " + uri);
235
236 HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri);
237 ChildUpdateRequest.Method = "PUT";
238 ChildUpdateRequest.ContentType = "application/json";
239 ChildUpdateRequest.Timeout = 10000;
240 //ChildUpdateRequest.KeepAlive = false;
241
242 // Fill it in
243 OSDMap args = null;
244 try
245 {
246 args = cAgentData.Pack();
247 }
248 catch (Exception e)
249 {
250 m_log.Debug("[REMOTE SIMULATION CONNECTOR]: PackUpdateMessage failed with exception: " + e.Message);
251 }
252 // Add the input arguments
253 args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
254 args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
255 args["destination_name"] = OSD.FromString(destination.RegionName);
256 args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
257
258 string strBuffer = "";
259 byte[] buffer = new byte[1];
260 try
261 {
262 strBuffer = OSDParser.SerializeJsonString(args);
263 Encoding str = Util.UTF8;
264 buffer = str.GetBytes(strBuffer);
265
266 }
267 catch (Exception e)
268 {
269 m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
270 // ignore. buffer will be empty, caller should check.
271 }
272
273 Stream os = null;
274 try
275 { // send the Post
276 ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
277 os = ChildUpdateRequest.GetRequestStream();
278 os.Write(buffer, 0, strBuffer.Length); //Send it
279 //m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: Posted AgentUpdate request to remote sim {0}", uri);
280 }
281 catch (WebException ex)
282 //catch
283 {
284 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: Bad send on AgentUpdate {0}", ex.Message);
285
286 return false;
287 }
288 finally
289 {
290 if (os != null)
291 os.Close();
292 }
293
294 // Let's wait for the response
295 //m_log.Info("[REMOTE SIMULATION CONNECTOR]: Waiting for a reply after ChildAgentUpdate");
296
297 WebResponse webResponse = null;
298 StreamReader sr = null;
299 try
300 {
301 webResponse = ChildUpdateRequest.GetResponse();
302 if (webResponse == null)
303 {
304 m_log.Info("[REMOTE SIMULATION CONNECTOR]: Null reply on ChilAgentUpdate post");
305 }
306
307 sr = new StreamReader(webResponse.GetResponseStream());
308 //reply = sr.ReadToEnd().Trim();
309 sr.ReadToEnd().Trim();
310 sr.Close();
311 //m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: ChilAgentUpdate reply was {0} ", reply);
312
313 }
314 catch (WebException ex)
315 {
316 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of ChilAgentUpdate {0}", ex.Message);
317 // ignore, really
318 }
319 finally
320 {
321 if (sr != null)
322 sr.Close();
323 }
324
325 return true;
326 }
327
328 public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
329 {
330 agent = null;
331 // Eventually, we want to use a caps url instead of the agentID
332 string uri = "http://" + destination.ExternalEndPoint.Address + ":" + destination.HttpPort + "/agent/" + id + "/" + destination.RegionID.ToString() + "/";
333 //Console.WriteLine(" >>> DoRetrieveRootAgentCall <<< " + uri);
334
335 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
336 request.Method = "GET";
337 request.Timeout = 10000;
338 //request.Headers.Add("authorization", ""); // coming soon
339
340 HttpWebResponse webResponse = null;
341 string reply = string.Empty;
342 StreamReader sr = null;
343 try
344 {
345 webResponse = (HttpWebResponse)request.GetResponse();
346 if (webResponse == null)
347 {
348 m_log.Info("[REMOTE SIMULATION CONNECTOR]: Null reply on agent get ");
349 }
350
351 sr = new StreamReader(webResponse.GetResponseStream());
352 reply = sr.ReadToEnd().Trim();
353
354 //Console.WriteLine("[REMOTE SIMULATION CONNECTOR]: ChilAgentUpdate reply was " + reply);
355
356 }
357 catch (WebException ex)
358 {
359 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of agent get {0}", ex.Message);
360 // ignore, really
361 return false;
362 }
363 finally
364 {
365 if (sr != null)
366 sr.Close();
367 }
368
369 if (webResponse.StatusCode == HttpStatusCode.OK)
370 {
371 // we know it's jason
372 OSDMap args = Util.GetOSDMap(reply);
373 if (args == null)
374 {
375 //Console.WriteLine("[REMOTE SIMULATION CONNECTOR]: Error getting OSDMap from reply");
376 return false;
377 }
378
379 agent = new CompleteAgentData();
380 agent.Unpack(args);
381 return true;
382 }
383
384 //Console.WriteLine("[REMOTE SIMULATION CONNECTOR]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode);
385 return false;
386 }
387
388 public bool ReleaseAgent(UUID origin, UUID id, string uri)
389 {
390 WebRequest request = WebRequest.Create(uri);
391 request.Method = "DELETE";
392 request.Timeout = 10000;
393
394 StreamReader sr = null;
395 try
396 {
397 WebResponse webResponse = request.GetResponse();
398 if (webResponse == null)
399 {
400 m_log.Info("[REMOTE SIMULATION CONNECTOR]: Null reply on ReleaseAgent");
401 }
402
403 sr = new StreamReader(webResponse.GetResponseStream());
404 //reply = sr.ReadToEnd().Trim();
405 sr.ReadToEnd().Trim();
406 sr.Close();
407 //m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: ChilAgentUpdate reply was {0} ", reply);
408
409 }
410 catch (WebException ex)
411 {
412 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of ReleaseAgent {0}", ex.Message);
413 return false;
414 }
415 finally
416 {
417 if (sr != null)
418 sr.Close();
419 }
420
421 return true;
422 }
423
424 public bool CloseAgent(GridRegion destination, UUID id)
425 {
426 string uri = string.Empty;
427 try
428 {
429 uri = "http://" + destination.ExternalEndPoint.Address + ":" + destination.HttpPort + "/agent/" + id + "/" + destination.RegionID.ToString() + "/";
430 }
431 catch (Exception e)
432 {
433 m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Unable to resolve external endpoint on agent close. Reason: " + e.Message);
434 return false;
435 }
436
437 //Console.WriteLine(" >>> DoCloseAgentCall <<< " + uri);
438
439 WebRequest request = WebRequest.Create(uri);
440 request.Method = "DELETE";
441 request.Timeout = 10000;
442
443 StreamReader sr = null;
444 try
445 {
446 WebResponse webResponse = request.GetResponse();
447 if (webResponse == null)
448 {
449 m_log.Info("[REMOTE SIMULATION CONNECTOR]: Null reply on agent delete ");
450 }
451
452 sr = new StreamReader(webResponse.GetResponseStream());
453 //reply = sr.ReadToEnd().Trim();
454 sr.ReadToEnd().Trim();
455 sr.Close();
456 //m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: ChilAgentUpdate reply was {0} ", reply);
457
458 }
459 catch (WebException ex)
460 {
461 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of agent delete {0}", ex.Message);
462 return false;
463 }
464 finally
465 {
466 if (sr != null)
467 sr.Close();
468 }
469
470 return true;
471 }
472
473 #endregion Agents
474
475 #region Objects
476
477 public bool CreateObject(GridRegion destination, ISceneObject sog, bool isLocalCall)
478 {
479 string uri
480 = "http://" + destination.ExternalEndPoint.Address + ":" + destination.HttpPort + "/object/" + sog.UUID + "/";
481 //m_log.Debug(" >>> DoCreateObjectCall <<< " + uri);
482
483 WebRequest ObjectCreateRequest = WebRequest.Create(uri);
484 ObjectCreateRequest.Method = "POST";
485 ObjectCreateRequest.ContentType = "application/json";
486 ObjectCreateRequest.Timeout = 10000;
487
488 OSDMap args = new OSDMap(2);
489 args["sog"] = OSD.FromString(sog.ToXml2());
490 args["extra"] = OSD.FromString(sog.ExtraToXmlString());
491 string state = sog.GetStateSnapshot();
492 if (state.Length > 0)
493 args["state"] = OSD.FromString(state);
494 // Add the input general arguments
495 args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
496 args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
497 args["destination_name"] = OSD.FromString(destination.RegionName);
498 args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
499
500 string strBuffer = "";
501 byte[] buffer = new byte[1];
502 try
503 {
504 strBuffer = OSDParser.SerializeJsonString(args);
505 Encoding str = Util.UTF8;
506 buffer = str.GetBytes(strBuffer);
507
508 }
509 catch (Exception e)
510 {
511 m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR]: Exception thrown on serialization of CreateObject: {0}", e.Message);
512 // ignore. buffer will be empty, caller should check.
513 }
514
515 Stream os = null;
516 try
517 { // send the Post
518 ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
519 os = ObjectCreateRequest.GetRequestStream();
520 os.Write(buffer, 0, strBuffer.Length); //Send it
521 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: Posted CreateObject request to remote sim {0}", uri);
522 }
523 catch (WebException ex)
524 {
525 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: Bad send on CreateObject {0}", ex.Message);
526 return false;
527 }
528 finally
529 {
530 if (os != null)
531 os.Close();
532 }
533
534 // Let's wait for the response
535 //m_log.Info("[REMOTE SIMULATION CONNECTOR]: Waiting for a reply after DoCreateChildAgentCall");
536
537 StreamReader sr = null;
538 try
539 {
540 WebResponse webResponse = ObjectCreateRequest.GetResponse();
541 if (webResponse == null)
542 {
543 m_log.Info("[REMOTE SIMULATION CONNECTOR]: Null reply on CreateObject post");
544 return false;
545 }
546
547 sr = new StreamReader(webResponse.GetResponseStream());
548 //reply = sr.ReadToEnd().Trim();
549 sr.ReadToEnd().Trim();
550 //m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: DoCreateChildAgentCall reply was {0} ", reply);
551
552 }
553 catch (WebException ex)
554 {
555 m_log.InfoFormat("[REMOTE SIMULATION CONNECTOR]: exception on reply of CreateObject {0}", ex.Message);
556 return false;
557 }
558 finally
559 {
560 if (sr != null)
561 sr.Close();
562 }
563
564 return true;
565 }
566
567 public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
568 {
569 // TODO, not that urgent
570 return false;
571 }
572
573 #endregion Objects
574 }
575}
diff --git a/OpenSim/Services/Connectors/User/UserServiceConnector.cs b/OpenSim/Services/Connectors/User/UserServiceConnector.cs
deleted file mode 100644
index 683990f..0000000
--- a/OpenSim/Services/Connectors/User/UserServiceConnector.cs
+++ /dev/null
@@ -1,114 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using log4net;
29using System;
30using System.Collections.Generic;
31using System.IO;
32using System.Reflection;
33using Nini.Config;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications;
36using OpenSim.Framework.Servers.HttpServer;
37using OpenSim.Services.Interfaces;
38using OpenMetaverse;
39
40namespace OpenSim.Services.Connectors
41{
42 public class UserServicesConnector : IUserAccountService
43 {
44 private static readonly ILog m_log =
45 LogManager.GetLogger(
46 MethodBase.GetCurrentMethod().DeclaringType);
47
48// private string m_ServerURI = String.Empty;
49
50 public UserServicesConnector()
51 {
52 }
53
54 public UserServicesConnector(string serverURI)
55 {
56// m_ServerURI = serverURI.TrimEnd('/');
57 }
58
59 public UserServicesConnector(IConfigSource source)
60 {
61 Initialise(source);
62 }
63
64 public virtual void Initialise(IConfigSource source)
65 {
66 IConfig assetConfig = source.Configs["UserService"];
67 if (assetConfig == null)
68 {
69 m_log.Error("[USER CONNECTOR]: UserService missing from OpanSim.ini");
70 throw new Exception("User connector init error");
71 }
72
73 string serviceURI = assetConfig.GetString("UserServerURI",
74 String.Empty);
75
76 if (serviceURI == String.Empty)
77 {
78 m_log.Error("[USER CONNECTOR]: No Server URI named in section UserService");
79 throw new Exception("User connector init error");
80 }
81 //m_ServerURI = serviceURI;
82 }
83
84 public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
85 {
86 return null;
87 }
88
89 public UserAccount GetUserAccount(UUID scopeID, UUID userID)
90 {
91 return null;
92 }
93
94 public bool SetHomePosition(UserAccount data, UUID regionID, UUID regionSecret)
95 {
96 return false;
97 }
98
99 public bool SetUserAccount(UserAccount data, UUID principalID, string token)
100 {
101 return false;
102 }
103
104 public bool CreateUserAccount(UserAccount data, UUID principalID, string token)
105 {
106 return false;
107 }
108
109 public List<UserAccount> GetUserAccount(UUID scopeID, string query)
110 {
111 return null;
112 }
113 }
114}
diff --git a/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs b/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs
new file mode 100644
index 0000000..e1621b8
--- /dev/null
+++ b/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs
@@ -0,0 +1,277 @@
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 log4net;
29using System;
30using System.Collections.Generic;
31using System.IO;
32using System.Reflection;
33using Nini.Config;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications;
36using OpenSim.Framework.Servers.HttpServer;
37using OpenSim.Server.Base;
38using OpenSim.Services.Interfaces;
39using OpenMetaverse;
40
41namespace OpenSim.Services.Connectors
42{
43 public class UserAccountServicesConnector : IUserAccountService
44 {
45 private static readonly ILog m_log =
46 LogManager.GetLogger(
47 MethodBase.GetCurrentMethod().DeclaringType);
48
49 private string m_ServerURI = String.Empty;
50
51 public UserAccountServicesConnector()
52 {
53 }
54
55 public UserAccountServicesConnector(string serverURI)
56 {
57 m_ServerURI = serverURI.TrimEnd('/');
58 }
59
60 public UserAccountServicesConnector(IConfigSource source)
61 {
62 Initialise(source);
63 }
64
65 public virtual void Initialise(IConfigSource source)
66 {
67 IConfig assetConfig = source.Configs["UserAccountService"];
68 if (assetConfig == null)
69 {
70 m_log.Error("[ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini");
71 throw new Exception("User account connector init error");
72 }
73
74 string serviceURI = assetConfig.GetString("UserAccountServerURI",
75 String.Empty);
76
77 if (serviceURI == String.Empty)
78 {
79 m_log.Error("[ACCOUNT CONNECTOR]: No Server URI named in section UserAccountService");
80 throw new Exception("User account connector init error");
81 }
82 m_ServerURI = serviceURI;
83 }
84
85 public virtual UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
86 {
87 Dictionary<string, object> sendData = new Dictionary<string, object>();
88 //sendData["SCOPEID"] = scopeID.ToString();
89 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
90 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
91 sendData["METHOD"] = "getaccount";
92
93 sendData["ScopeID"] = scopeID;
94 sendData["FirstName"] = firstName.ToString();
95 sendData["LastName"] = lastName.ToString();
96
97 return SendAndGetReply(sendData);
98 }
99
100 public virtual UserAccount GetUserAccount(UUID scopeID, string email)
101 {
102 Dictionary<string, object> sendData = new Dictionary<string, object>();
103 //sendData["SCOPEID"] = scopeID.ToString();
104 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
105 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
106 sendData["METHOD"] = "getaccount";
107
108 sendData["ScopeID"] = scopeID;
109 sendData["Email"] = email;
110
111 return SendAndGetReply(sendData);
112 }
113
114 public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID)
115 {
116 Dictionary<string, object> sendData = new Dictionary<string, object>();
117 //sendData["SCOPEID"] = scopeID.ToString();
118 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
119 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
120 sendData["METHOD"] = "getaccount";
121
122 sendData["ScopeID"] = scopeID;
123 sendData["UserID"] = userID.ToString();
124
125 return SendAndGetReply(sendData);
126 }
127
128 public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
129 {
130 Dictionary<string, object> sendData = new Dictionary<string, object>();
131 //sendData["SCOPEID"] = scopeID.ToString();
132 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
133 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
134 sendData["METHOD"] = "getagents";
135
136 sendData["ScopeID"] = scopeID.ToString();
137 sendData["query"] = query;
138
139 string reply = string.Empty;
140 string reqString = ServerUtils.BuildQueryString(sendData);
141 // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
142 try
143 {
144 reply = SynchronousRestFormsRequester.MakeRequest("POST",
145 m_ServerURI + "/accounts",
146 reqString);
147 if (reply == null || (reply != null && reply == string.Empty))
148 {
149 m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received null or empty reply");
150 return null;
151 }
152 }
153 catch (Exception e)
154 {
155 m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting accounts server: {0}", e.Message);
156 }
157
158 List<UserAccount> accounts = new List<UserAccount>();
159
160 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
161
162 if (replyData != null)
163 {
164 if (replyData.ContainsKey("result") && replyData.ContainsKey("result").ToString() == "null")
165 {
166 return accounts;
167 }
168
169 Dictionary<string, object>.ValueCollection accountList = replyData.Values;
170 //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
171 foreach (object acc in accountList)
172 {
173 if (acc is Dictionary<string, object>)
174 {
175 UserAccount pinfo = new UserAccount((Dictionary<string, object>)acc);
176 accounts.Add(pinfo);
177 }
178 else
179 m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}",
180 acc.GetType());
181 }
182 }
183 else
184 m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response");
185
186 return accounts;
187 }
188
189 public bool StoreUserAccount(UserAccount data)
190 {
191 Dictionary<string, object> sendData = new Dictionary<string, object>();
192 //sendData["SCOPEID"] = scopeID.ToString();
193 sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
194 sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
195 sendData["METHOD"] = "setaccount";
196
197 Dictionary<string, object> structData = data.ToKeyValuePairs();
198
199 foreach (KeyValuePair<string,object> kvp in structData)
200 sendData[kvp.Key] = kvp.Value.ToString();
201
202 return SendAndGetBoolReply(sendData);
203 }
204
205 private UserAccount SendAndGetReply(Dictionary<string, object> sendData)
206 {
207 string reply = string.Empty;
208 string reqString = ServerUtils.BuildQueryString(sendData);
209 // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
210 try
211 {
212 reply = SynchronousRestFormsRequester.MakeRequest("POST",
213 m_ServerURI + "/accounts",
214 reqString);
215 if (reply == null || (reply != null && reply == string.Empty))
216 {
217 m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccount received null or empty reply");
218 return null;
219 }
220 }
221 catch (Exception e)
222 {
223 m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user account server: {0}", e.Message);
224 }
225
226 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
227 UserAccount account = null;
228
229 if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
230 {
231 if (replyData["result"] is Dictionary<string, object>)
232 {
233 account = new UserAccount((Dictionary<string, object>)replyData["result"]);
234 }
235 }
236
237 return account;
238
239 }
240
241 private bool SendAndGetBoolReply(Dictionary<string, object> sendData)
242 {
243 string reqString = ServerUtils.BuildQueryString(sendData);
244 // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
245 try
246 {
247 string reply = SynchronousRestFormsRequester.MakeRequest("POST",
248 m_ServerURI + "/accounts",
249 reqString);
250 if (reply != string.Empty)
251 {
252 Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
253
254 if (replyData.ContainsKey("result"))
255 {
256 if (replyData["result"].ToString().ToLower() == "success")
257 return true;
258 else
259 return false;
260 }
261 else
262 m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount reply data does not contain result field");
263
264 }
265 else
266 m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount received empty reply");
267 }
268 catch (Exception e)
269 {
270 m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Exception when contacting user account server: {0}", e.Message);
271 }
272
273 return false;
274 }
275
276 }
277}
diff --git a/OpenSim/Services/GridService/GridService.cs b/OpenSim/Services/GridService/GridService.cs
index 7749c37..e912705 100644
--- a/OpenSim/Services/GridService/GridService.cs
+++ b/OpenSim/Services/GridService/GridService.cs
@@ -34,6 +34,7 @@ using log4net;
34using OpenSim.Framework; 34using OpenSim.Framework;
35using OpenSim.Framework.Console; 35using OpenSim.Framework.Console;
36using OpenSim.Data; 36using OpenSim.Data;
37using OpenSim.Server.Base;
37using OpenSim.Services.Interfaces; 38using OpenSim.Services.Interfaces;
38using GridRegion = OpenSim.Services.Interfaces.GridRegion; 39using GridRegion = OpenSim.Services.Interfaces.GridRegion;
39using OpenMetaverse; 40using OpenMetaverse;
@@ -46,6 +47,11 @@ namespace OpenSim.Services.GridService
46 LogManager.GetLogger( 47 LogManager.GetLogger(
47 MethodBase.GetCurrentMethod().DeclaringType); 48 MethodBase.GetCurrentMethod().DeclaringType);
48 49
50 private bool m_DeleteOnUnregister = true;
51 private static GridService m_RootInstance = null;
52 protected IConfigSource m_config;
53
54 protected IAuthenticationService m_AuthenticationService = null;
49 protected bool m_AllowDuplicateNames = false; 55 protected bool m_AllowDuplicateNames = false;
50 56
51 public GridService(IConfigSource config) 57 public GridService(IConfigSource config)
@@ -53,20 +59,88 @@ namespace OpenSim.Services.GridService
53 { 59 {
54 m_log.DebugFormat("[GRID SERVICE]: Starting..."); 60 m_log.DebugFormat("[GRID SERVICE]: Starting...");
55 61
62 m_config = config;
56 IConfig gridConfig = config.Configs["GridService"]; 63 IConfig gridConfig = config.Configs["GridService"];
57 if (gridConfig != null) 64 if (gridConfig != null)
58 { 65 {
66 m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
67
68 string authService = gridConfig.GetString("AuthenticationService", String.Empty);
69
70 if (authService != String.Empty)
71 {
72 Object[] args = new Object[] { config };
73 m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
74 }
59 m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames); 75 m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
60 } 76 }
77
78 if (m_RootInstance == null)
79 {
80 m_RootInstance = this;
81
82 MainConsole.Instance.Commands.AddCommand("grid", true,
83 "show region",
84 "show region <Region name>",
85 "Show details on a region",
86 String.Empty,
87 HandleShowRegion);
88
89 MainConsole.Instance.Commands.AddCommand("grid", true,
90 "set region flags",
91 "set region flags <Region name> <flags>",
92 "Set database flags for region",
93 String.Empty,
94 HandleSetFlags);
95 }
61 } 96 }
62 97
63 #region IGridService 98 #region IGridService
64 99
65 public string RegisterRegion(UUID scopeID, GridRegion regionInfos) 100 public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
66 { 101 {
102 IConfig gridConfig = m_config.Configs["GridService"];
67 // This needs better sanity testing. What if regionInfo is registering in 103 // This needs better sanity testing. What if regionInfo is registering in
68 // overlapping coords? 104 // overlapping coords?
69 RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID); 105 RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
106 if (region != null)
107 {
108 // There is a preexisting record
109 //
110 // Get it's flags
111 //
112 OpenSim.Data.RegionFlags rflags = (OpenSim.Data.RegionFlags)Convert.ToInt32(region.Data["Flags"]);
113
114 // Is this a reservation?
115 //
116 if ((rflags & OpenSim.Data.RegionFlags.Reservation) != 0)
117 {
118 // Regions reserved for the null key cannot be taken.
119 //
120 if (region.Data["PrincipalID"] == UUID.Zero.ToString())
121 return "Region location us reserved";
122
123 // Treat it as an auth request
124 //
125 // NOTE: Fudging the flags value here, so these flags
126 // should not be used elsewhere. Don't optimize
127 // this with the later retrieval of the same flags!
128 //
129 rflags |= OpenSim.Data.RegionFlags.Authenticate;
130 }
131
132 if ((rflags & OpenSim.Data.RegionFlags.Authenticate) != 0)
133 {
134 // Can we authenticate at all?
135 //
136 if (m_AuthenticationService == null)
137 return "No authentication possible";
138
139 if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
140 return "Bad authentication";
141 }
142 }
143
70 if ((region != null) && (region.RegionID != regionInfos.RegionID)) 144 if ((region != null) && (region.RegionID != regionInfos.RegionID))
71 { 145 {
72 m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.", 146 m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.",
@@ -76,6 +150,9 @@ namespace OpenSim.Services.GridService
76 if ((region != null) && (region.RegionID == regionInfos.RegionID) && 150 if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
77 ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY))) 151 ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
78 { 152 {
153 if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Data.RegionFlags.NoMove) != 0)
154 return "Can't move this region";
155
79 // Region reregistering in other coordinates. Delete the old entry 156 // Region reregistering in other coordinates. Delete the old entry
80 m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.", 157 m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
81 regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY); 158 regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);
@@ -110,8 +187,37 @@ namespace OpenSim.Services.GridService
110 // Everything is ok, let's register 187 // Everything is ok, let's register
111 RegionData rdata = RegionInfo2RegionData(regionInfos); 188 RegionData rdata = RegionInfo2RegionData(regionInfos);
112 rdata.ScopeID = scopeID; 189 rdata.ScopeID = scopeID;
190
191 if (region != null)
192 {
193 int oldFlags = Convert.ToInt32(region.Data["flags"]);
194 if ((oldFlags & (int)OpenSim.Data.RegionFlags.LockedOut) != 0)
195 return "Region locked out";
196
197 oldFlags &= ~(int)OpenSim.Data.RegionFlags.Reservation;
198
199 rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
200 }
201 else
202 {
203 rdata.Data["flags"] = "0";
204 if ((gridConfig != null) && rdata.RegionName != string.Empty)
205 {
206 int newFlags = 0;
207 string regionName = rdata.RegionName.Trim().Replace(' ', '_');
208 newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
209 newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
210 rdata.Data["flags"] = newFlags.ToString();
211 }
212 }
213
214 int flags = Convert.ToInt32(rdata.Data["flags"]);
215 flags |= (int)OpenSim.Data.RegionFlags.RegionOnline;
216 rdata.Data["flags"] = flags.ToString();
217
113 try 218 try
114 { 219 {
220 rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
115 m_Database.Store(rdata); 221 m_Database.Store(rdata);
116 } 222 }
117 catch (Exception e) 223 catch (Exception e)
@@ -128,6 +234,30 @@ namespace OpenSim.Services.GridService
128 public bool DeregisterRegion(UUID regionID) 234 public bool DeregisterRegion(UUID regionID)
129 { 235 {
130 m_log.DebugFormat("[GRID SERVICE]: Region {0} deregistered", regionID); 236 m_log.DebugFormat("[GRID SERVICE]: Region {0} deregistered", regionID);
237 RegionData region = m_Database.Get(regionID, UUID.Zero);
238 if (region == null)
239 return false;
240
241 int flags = Convert.ToInt32(region.Data["flags"]);
242
243 if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Data.RegionFlags.Persistent) != 0)
244 {
245 flags &= ~(int)OpenSim.Data.RegionFlags.RegionOnline;
246 region.Data["flags"] = flags.ToString();
247 region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
248 try
249 {
250 m_Database.Store(region);
251 }
252 catch (Exception e)
253 {
254 m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
255 }
256
257 return true;
258
259 }
260
131 return m_Database.Delete(regionID); 261 return m_Database.Delete(regionID);
132 } 262 }
133 263
@@ -243,5 +373,134 @@ namespace OpenSim.Services.GridService
243 373
244 #endregion 374 #endregion
245 375
376 public List<GridRegion> GetDefaultRegions(UUID scopeID)
377 {
378 List<GridRegion> ret = new List<GridRegion>();
379
380 List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
381
382 foreach (RegionData r in regions)
383 {
384 if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)
385 ret.Add(RegionData2RegionInfo(r));
386 }
387
388 return ret;
389 }
390
391 public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
392 {
393 List<GridRegion> ret = new List<GridRegion>();
394
395 List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
396
397 foreach (RegionData r in regions)
398 {
399 if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)
400 ret.Add(RegionData2RegionInfo(r));
401 }
402
403 return ret;
404 }
405
406 public int GetRegionFlags(UUID scopeID, UUID regionID)
407 {
408 RegionData region = m_Database.Get(regionID, scopeID);
409
410 return Convert.ToInt32(region.Data["flags"]);
411 }
412
413 private void HandleShowRegion(string module, string[] cmd)
414 {
415 if (cmd.Length != 3)
416 {
417 MainConsole.Instance.Output("Syntax: show region <region name>");
418 return;
419 }
420 List<RegionData> regions = m_Database.Get(cmd[2], UUID.Zero);
421 if (regions == null || regions.Count < 1)
422 {
423 MainConsole.Instance.Output("Region not found");
424 return;
425 }
426
427 MainConsole.Instance.Output("Region Name Region UUID");
428 MainConsole.Instance.Output("Location URI");
429 MainConsole.Instance.Output("Owner ID Flags");
430 MainConsole.Instance.Output("-------------------------------------------------------------------------------");
431 foreach (RegionData r in regions)
432 {
433 OpenSim.Data.RegionFlags flags = (OpenSim.Data.RegionFlags)Convert.ToInt32(r.Data["flags"]);
434 MainConsole.Instance.Output(String.Format("{0,-20} {1}\n{2,-20} {3}\n{4,-39} {5}\n\n",
435 r.RegionName, r.RegionID,
436 String.Format("{0},{1}", r.posX, r.posY), "http://" + r.Data["serverIP"].ToString() + ":" + r.Data["serverPort"].ToString(),
437 r.Data["owner_uuid"].ToString(), flags.ToString()));
438 }
439 return;
440 }
441
442 private int ParseFlags(int prev, string flags)
443 {
444 OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)prev;
445
446 string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
447
448 foreach (string p in parts)
449 {
450 int val;
451
452 try
453 {
454 if (p.StartsWith("+"))
455 {
456 val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1));
457 f |= (OpenSim.Data.RegionFlags)val;
458 }
459 else if (p.StartsWith("-"))
460 {
461 val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1));
462 f &= ~(OpenSim.Data.RegionFlags)val;
463 }
464 else
465 {
466 val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p);
467 f |= (OpenSim.Data.RegionFlags)val;
468 }
469 }
470 catch (Exception e)
471 {
472 MainConsole.Instance.Output("Error in flag specification: " + p);
473 }
474 }
475
476 return (int)f;
477 }
478
479 private void HandleSetFlags(string module, string[] cmd)
480 {
481 if (cmd.Length < 5)
482 {
483 MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
484 return;
485 }
486
487 List<RegionData> regions = m_Database.Get(cmd[3], UUID.Zero);
488 if (regions == null || regions.Count < 1)
489 {
490 MainConsole.Instance.Output("Region not found");
491 return;
492 }
493
494 foreach (RegionData r in regions)
495 {
496 int flags = Convert.ToInt32(r.Data["flags"]);
497 flags = ParseFlags(flags, cmd[4]);
498 r.Data["flags"] = flags.ToString();
499 OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)flags;
500
501 MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
502 m_Database.Store(r);
503 }
504 }
246 } 505 }
247} 506}
diff --git a/OpenSim/Services/Interfaces/IAuthenticationService.cs b/OpenSim/Services/Interfaces/IAuthenticationService.cs
index 9225773..9de261b 100644
--- a/OpenSim/Services/Interfaces/IAuthenticationService.cs
+++ b/OpenSim/Services/Interfaces/IAuthenticationService.cs
@@ -66,6 +66,17 @@ namespace OpenSim.Services.Interfaces
66 bool Release(UUID principalID, string token); 66 bool Release(UUID principalID, string token);
67 67
68 ////////////////////////////////////////////////////// 68 //////////////////////////////////////////////////////
69 // SetPassword for a principal
70 //
71 // This method exists for the service, but may or may not
72 // be served remotely. That is, the authentication
73 // handlers may not include one handler for this,
74 // because it's a bit risky. Such handlers require
75 // authentication/authorization.
76 //
77 bool SetPassword(UUID principalID, string passwd);
78
79 //////////////////////////////////////////////////////
69 // Grid 80 // Grid
70 // 81 //
71 // We no longer need a shared secret between grid 82 // We no longer need a shared secret between grid
diff --git a/OpenSim/Services/Interfaces/IAvatarService.cs b/OpenSim/Services/Interfaces/IAvatarService.cs
new file mode 100644
index 0000000..de3bcf9
--- /dev/null
+++ b/OpenSim/Services/Interfaces/IAvatarService.cs
@@ -0,0 +1,241 @@
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.Collections.Generic;
31
32using OpenSim.Framework;
33
34using OpenMetaverse;
35
36namespace OpenSim.Services.Interfaces
37{
38 public interface IAvatarService
39 {
40 /// <summary>
41 /// Called by the login service
42 /// </summary>
43 /// <param name="userID"></param>
44 /// <returns></returns>
45 AvatarData GetAvatar(UUID userID);
46
47 /// <summary>
48 /// Called by everyone who can change the avatar data (so, regions)
49 /// </summary>
50 /// <param name="userID"></param>
51 /// <param name="avatar"></param>
52 /// <returns></returns>
53 bool SetAvatar(UUID userID, AvatarData avatar);
54
55 /// <summary>
56 /// Not sure if it's needed
57 /// </summary>
58 /// <param name="userID"></param>
59 /// <returns></returns>
60 bool ResetAvatar(UUID userID);
61
62 /// <summary>
63 /// These methods raison d'etre:
64 /// No need to send the entire avatar data (SetAvatar) for changing attachments
65 /// </summary>
66 /// <param name="userID"></param>
67 /// <param name="attach"></param>
68 /// <returns></returns>
69 bool SetItems(UUID userID, string[] names, string[] values);
70 bool RemoveItems(UUID userID, string[] names);
71 }
72
73 /// <summary>
74 /// Each region/client that uses avatars will have a data structure
75 /// of this type representing the avatars.
76 /// </summary>
77 public class AvatarData
78 {
79 // This pretty much determines which name/value pairs will be
80 // present below. The name/value pair describe a part of
81 // the avatar. For SL avatars, these would be "shape", "texture1",
82 // etc. For other avatars, they might be "mesh", "skin", etc.
83 // The value portion is a URL that is expected to resolve to an
84 // asset of the type required by the handler for that field.
85 // It is required that regions can access these URLs. Allowing
86 // direct access by a viewer is not required, and, if provided,
87 // may be read-only. A "naked" UUID can be used to refer to an
88 // asset int he current region's asset service, which is not
89 // portable, but allows legacy appearance to continue to
90 // function. Closed, LL-based grids will never need URLs here.
91
92 public int AvatarType;
93 public Dictionary<string,string> Data;
94
95 public AvatarData()
96 {
97 }
98
99 public AvatarData(Dictionary<string, object> kvp)
100 {
101 Data = new Dictionary<string, string>();
102
103 if (kvp.ContainsKey("AvatarType"))
104 Int32.TryParse(kvp["AvatarType"].ToString(), out AvatarType);
105
106 foreach (KeyValuePair<string, object> _kvp in kvp)
107 {
108 if (_kvp.Value != null)
109 Data[_kvp.Key] = _kvp.Value.ToString();
110 }
111 }
112
113 /// <summary>
114 /// </summary>
115 /// <returns></returns>
116 public Dictionary<string, object> ToKeyValuePairs()
117 {
118 Dictionary<string, object> result = new Dictionary<string, object>();
119
120 result["AvatarType"] = AvatarType.ToString();
121 foreach (KeyValuePair<string, string> _kvp in Data)
122 {
123 if (_kvp.Value != null)
124 result[_kvp.Key] = _kvp.Value;
125 }
126 return result;
127 }
128
129 public AvatarData(AvatarAppearance appearance)
130 {
131 AvatarType = 1; // SL avatars
132 Data = new Dictionary<string, string>();
133
134 Data["Serial"] = appearance.Serial.ToString();
135 // Wearables
136 Data["AvatarHeight"] = appearance.AvatarHeight.ToString();
137 Data["BodyItem"] = appearance.BodyItem.ToString();
138 Data["EyesItem"] = appearance.EyesItem.ToString();
139 Data["GlovesItem"] = appearance.GlovesItem.ToString();
140 Data["HairItem"] = appearance.HairItem.ToString();
141 Data["JacketItem"] = appearance.JacketItem.ToString();
142 Data["PantsItem"] = appearance.PantsItem.ToString();
143 Data["ShirtItem"] = appearance.ShirtItem.ToString();
144 Data["ShoesItem"] = appearance.ShoesItem.ToString();
145 Data["SkinItem"] = appearance.SkinItem.ToString();
146 Data["SkirtItem"] = appearance.SkirtItem.ToString();
147 Data["SocksItem"] = appearance.SocksItem.ToString();
148 Data["UnderPantsItem"] = appearance.UnderPantsItem.ToString();
149 Data["UnderShirtItem"] = appearance.UnderShirtItem.ToString();
150
151 Data["BodyAsset"] = appearance.BodyAsset.ToString();
152 Data["EyesAsset"] = appearance.EyesAsset.ToString();
153 Data["GlovesAsset"] = appearance.GlovesAsset.ToString();
154 Data["HairAsset"] = appearance.HairAsset.ToString();
155 Data["JacketAsset"] = appearance.JacketAsset.ToString();
156 Data["PantsAsset"] = appearance.PantsAsset.ToString();
157 Data["ShirtAsset"] = appearance.ShirtAsset.ToString();
158 Data["ShoesAsset"] = appearance.ShoesAsset.ToString();
159 Data["SkinAsset"] = appearance.SkinAsset.ToString();
160 Data["SkirtAsset"] = appearance.SkirtAsset.ToString();
161 Data["SocksAsset"] = appearance.SocksAsset.ToString();
162 Data["UnderPantsAsset"] = appearance.UnderPantsAsset.ToString();
163 Data["UnderShirtAsset"] = appearance.UnderShirtAsset.ToString();
164
165 // Attachments
166 Hashtable attachs = appearance.GetAttachments();
167 if (attachs != null)
168 foreach (DictionaryEntry dentry in attachs)
169 {
170 if (dentry.Value != null)
171 {
172 Hashtable tab = (Hashtable)dentry.Value;
173 if (tab.ContainsKey("item") && tab["item"] != null)
174 Data["_ap_" + dentry.Key] = tab["item"].ToString();
175 }
176 }
177 }
178
179 public AvatarAppearance ToAvatarAppearance(UUID owner)
180 {
181 AvatarAppearance appearance = new AvatarAppearance(owner);
182 try
183 {
184 appearance.Serial = Int32.Parse(Data["Serial"]);
185
186 // Wearables
187 appearance.BodyItem = UUID.Parse(Data["BodyItem"]);
188 appearance.EyesItem = UUID.Parse(Data["EyesItem"]);
189 appearance.GlovesItem = UUID.Parse(Data["GlovesItem"]);
190 appearance.HairItem = UUID.Parse(Data["HairItem"]);
191 appearance.JacketItem = UUID.Parse(Data["JacketItem"]);
192 appearance.PantsItem = UUID.Parse(Data["PantsItem"]);
193 appearance.ShirtItem = UUID.Parse(Data["ShirtItem"]);
194 appearance.ShoesItem = UUID.Parse(Data["ShoesItem"]);
195 appearance.SkinItem = UUID.Parse(Data["SkinItem"]);
196 appearance.SkirtItem = UUID.Parse(Data["SkirtItem"]);
197 appearance.SocksItem = UUID.Parse(Data["SocksItem"]);
198 appearance.UnderPantsItem = UUID.Parse(Data["UnderPantsItem"]);
199 appearance.UnderShirtItem = UUID.Parse(Data["UnderShirtItem"]);
200
201 appearance.BodyAsset = UUID.Parse(Data["BodyAsset"]);
202 appearance.EyesAsset = UUID.Parse(Data["EyesAsset"]);
203 appearance.GlovesAsset = UUID.Parse(Data["GlovesAsset"]);
204 appearance.HairAsset = UUID.Parse(Data["HairAsset"]);
205 appearance.JacketAsset = UUID.Parse(Data["JacketAsset"]);
206 appearance.PantsAsset = UUID.Parse(Data["PantsAsset"]);
207 appearance.ShirtAsset = UUID.Parse(Data["ShirtAsset"]);
208 appearance.ShoesAsset = UUID.Parse(Data["ShoesAsset"]);
209 appearance.SkinAsset = UUID.Parse(Data["SkinAsset"]);
210 appearance.SkirtAsset = UUID.Parse(Data["SkirtAsset"]);
211 appearance.SocksAsset = UUID.Parse(Data["SocksAsset"]);
212 appearance.UnderPantsAsset = UUID.Parse(Data["UnderPantsAsset"]);
213 appearance.UnderShirtAsset = UUID.Parse(Data["UnderShirtAsset"]);
214
215 // Attachments
216 Dictionary<string, string> attchs = new Dictionary<string, string>();
217 foreach (KeyValuePair<string, string> _kvp in Data)
218 if (_kvp.Key.StartsWith("_ap_"))
219 attchs[_kvp.Key] = _kvp.Value;
220 Hashtable aaAttachs = new Hashtable();
221 foreach (KeyValuePair<string, string> _kvp in attchs)
222 {
223 string pointStr = _kvp.Key.Substring(4);
224 int point = 0;
225 if (!Int32.TryParse(pointStr, out point))
226 continue;
227 Hashtable tmp = new Hashtable();
228 UUID uuid = UUID.Zero;
229 UUID.TryParse(_kvp.Value, out uuid);
230 tmp["item"] = uuid;
231 tmp["asset"] = UUID.Zero.ToString();
232 aaAttachs[point] = tmp;
233 }
234 appearance.SetAttachments(aaAttachs);
235 }
236 catch { }
237
238 return appearance;
239 }
240 }
241}
diff --git a/OpenSim/Services/Interfaces/IGridService.cs b/OpenSim/Services/Interfaces/IGridService.cs
index 5135f6d..6186d80 100644
--- a/OpenSim/Services/Interfaces/IGridService.cs
+++ b/OpenSim/Services/Interfaces/IGridService.cs
@@ -90,6 +90,10 @@ namespace OpenSim.Services.Interfaces
90 90
91 List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax); 91 List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax);
92 92
93 List<GridRegion> GetDefaultRegions(UUID scopeID);
94 List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y);
95
96 int GetRegionFlags(UUID scopeID, UUID regionID);
93 } 97 }
94 98
95 public class GridRegion 99 public class GridRegion
@@ -155,6 +159,7 @@ namespace OpenSim.Services.Interfaces
155 public byte Access; 159 public byte Access;
156 public int Maturity; 160 public int Maturity;
157 public string RegionSecret; 161 public string RegionSecret;
162 public string Token;
158 163
159 public GridRegion() 164 public GridRegion()
160 { 165 {
@@ -200,12 +205,6 @@ namespace OpenSim.Services.Interfaces
200 Maturity = ConvertFrom.RegionSettings.Maturity; 205 Maturity = ConvertFrom.RegionSettings.Maturity;
201 RegionSecret = ConvertFrom.regionSecret; 206 RegionSecret = ConvertFrom.regionSecret;
202 EstateOwner = ConvertFrom.EstateSettings.EstateOwner; 207 EstateOwner = ConvertFrom.EstateSettings.EstateOwner;
203 if (EstateOwner == UUID.Zero)
204 {
205 EstateOwner = ConvertFrom.MasterAvatarAssignedUUID;
206 ConvertFrom.EstateSettings.EstateOwner = EstateOwner;
207 ConvertFrom.EstateSettings.Save();
208 }
209 } 208 }
210 209
211 public GridRegion(GridRegion ConvertFrom) 210 public GridRegion(GridRegion ConvertFrom)
@@ -308,6 +307,7 @@ namespace OpenSim.Services.Interfaces
308 kvp["access"] = Access.ToString(); 307 kvp["access"] = Access.ToString();
309 kvp["regionSecret"] = RegionSecret; 308 kvp["regionSecret"] = RegionSecret;
310 kvp["owner_uuid"] = EstateOwner.ToString(); 309 kvp["owner_uuid"] = EstateOwner.ToString();
310 kvp["token"] = Token.ToString();
311 // Maturity doesn't seem to exist in the DB 311 // Maturity doesn't seem to exist in the DB
312 return kvp; 312 return kvp;
313 } 313 }
@@ -365,6 +365,9 @@ namespace OpenSim.Services.Interfaces
365 if (kvp.ContainsKey("owner_uuid")) 365 if (kvp.ContainsKey("owner_uuid"))
366 EstateOwner = new UUID(kvp["owner_uuid"].ToString()); 366 EstateOwner = new UUID(kvp["owner_uuid"].ToString());
367 367
368 if (kvp.ContainsKey("token"))
369 Token = kvp["token"].ToString();
370
368 } 371 }
369 } 372 }
370 373
diff --git a/OpenSim/Services/UserService/UserService.cs b/OpenSim/Services/Interfaces/ILibraryService.cs
index e8b9fc3..861cf0e 100644
--- a/OpenSim/Services/UserService/UserService.cs
+++ b/OpenSim/Services/Interfaces/ILibraryService.cs
@@ -1,4 +1,4 @@
1/* 1/*
2 * Copyright (c) Contributors, http://opensimulator.org/ 2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders. 3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 * 4 *
@@ -26,51 +26,18 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Reflection;
30using Nini.Config;
31using OpenSim.Data;
32using OpenSim.Services.Interfaces;
33using System.Collections.Generic; 29using System.Collections.Generic;
30
31using OpenSim.Framework;
34using OpenMetaverse; 32using OpenMetaverse;
35 33
36namespace OpenSim.Services.UserAccountService 34namespace OpenSim.Services.Interfaces
37{ 35{
38 public class UserAccountService : UserAccountServiceBase, IUserAccountService 36 public interface ILibraryService
39 { 37 {
40 public UserAccountService(IConfigSource config) : base(config) 38 InventoryFolderImpl LibraryRootFolder { get; }
41 {
42 }
43
44 public UserAccount GetUserAccount(UUID scopeID, string firstName,
45 string lastName)
46 {
47 return null;
48 }
49
50 public UserAccount GetUserAccount(UUID scopeID, UUID userID)
51 {
52 return null;
53 }
54
55 public bool SetHomePosition(UserAccount data, UUID regionID, UUID regionSecret)
56 {
57 return false;
58 }
59 39
60 public bool SetUserAccount(UserAccount data, UUID principalID, string token) 40 Dictionary<UUID, InventoryFolderImpl> GetAllFolders();
61 {
62 return false;
63 }
64
65 public bool CreateUserAccount(UserAccount data, UUID principalID, string token)
66 {
67 return false;
68 }
69
70 public List<UserAccount> GetUserAccount(UUID scopeID,
71 string query)
72 {
73 return null;
74 }
75 } 41 }
42
76} 43}
diff --git a/OpenSim/Services/Interfaces/ILoginService.cs b/OpenSim/Services/Interfaces/ILoginService.cs
new file mode 100644
index 0000000..24bf342
--- /dev/null
+++ b/OpenSim/Services/Interfaces/ILoginService.cs
@@ -0,0 +1,53 @@
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.Collections.Generic;
31using System.Net;
32
33using OpenMetaverse.StructuredData;
34
35namespace OpenSim.Services.Interfaces
36{
37 public abstract class LoginResponse
38 {
39 public abstract Hashtable ToHashtable();
40 public abstract OSD ToOSDMap();
41 }
42
43 public abstract class FailedLoginResponse : LoginResponse
44 {
45 }
46
47 public interface ILoginService
48 {
49 LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, IPEndPoint clientIP);
50 }
51
52
53}
diff --git a/OpenSim/Services/Interfaces/IPresenceService.cs b/OpenSim/Services/Interfaces/IPresenceService.cs
index aa1c5bf..b4c1859 100644
--- a/OpenSim/Services/Interfaces/IPresenceService.cs
+++ b/OpenSim/Services/Interfaces/IPresenceService.cs
@@ -25,6 +25,7 @@
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System;
28using OpenSim.Framework; 29using OpenSim.Framework;
29using System.Collections.Generic; 30using System.Collections.Generic;
30using OpenMetaverse; 31using OpenMetaverse;
@@ -33,13 +34,94 @@ namespace OpenSim.Services.Interfaces
33{ 34{
34 public class PresenceInfo 35 public class PresenceInfo
35 { 36 {
36 public UUID PrincipalID; 37 public string UserID;
37 public UUID RegionID; 38 public UUID RegionID;
38 public Dictionary<string, string> Data; 39 public bool Online;
40 public DateTime Login;
41 public DateTime Logout;
42 public Vector3 Position;
43 public Vector3 LookAt;
44 public UUID HomeRegionID;
45 public Vector3 HomePosition;
46 public Vector3 HomeLookAt;
47
48 public PresenceInfo()
49 {
50 }
51
52 public PresenceInfo(Dictionary<string, object> kvp)
53 {
54 if (kvp.ContainsKey("UserID"))
55 UserID = kvp["UserID"].ToString();
56 if (kvp.ContainsKey("RegionID"))
57 UUID.TryParse(kvp["RegionID"].ToString(), out RegionID);
58 if (kvp.ContainsKey("login"))
59 DateTime.TryParse(kvp["login"].ToString(), out Login);
60 if (kvp.ContainsKey("logout"))
61 DateTime.TryParse(kvp["logout"].ToString(), out Logout);
62 if (kvp.ContainsKey("lookAt"))
63 Vector3.TryParse(kvp["lookAt"].ToString(), out LookAt);
64 if (kvp.ContainsKey("online"))
65 Boolean.TryParse(kvp["online"].ToString(), out Online);
66 if (kvp.ContainsKey("position"))
67 Vector3.TryParse(kvp["position"].ToString(), out Position);
68 if (kvp.ContainsKey("HomeRegionID"))
69 UUID.TryParse(kvp["HomeRegionID"].ToString(), out HomeRegionID);
70 if (kvp.ContainsKey("HomePosition"))
71 Vector3.TryParse(kvp["HomePosition"].ToString(), out HomePosition);
72 if (kvp.ContainsKey("HomeLookAt"))
73 Vector3.TryParse(kvp["HomeLookAt"].ToString(), out HomeLookAt);
74
75 }
76
77 public Dictionary<string, object> ToKeyValuePairs()
78 {
79 Dictionary<string, object> result = new Dictionary<string, object>();
80 result["UserID"] = UserID;
81 result["RegionID"] = RegionID.ToString();
82 result["online"] = Online.ToString();
83 result["login"] = Login.ToString();
84 result["logout"] = Logout.ToString();
85 result["position"] = Position.ToString();
86 result["lookAt"] = LookAt.ToString();
87 result["HomeRegionID"] = HomeRegionID.ToString();
88 result["HomePosition"] = HomePosition.ToString();
89 result["HomeLookAt"] = HomeLookAt.ToString();
90
91 return result;
92 }
93
94 public static PresenceInfo[] GetOnlinePresences(PresenceInfo[] pinfos)
95 {
96 if (pinfos == null)
97 return null;
98
99 List<PresenceInfo> lst = new List<PresenceInfo>(pinfos);
100 lst = lst.FindAll(delegate(PresenceInfo each) { return each.Online; });
101
102 return lst.ToArray();
103 }
104
105 public static PresenceInfo GetOnlinePresence(PresenceInfo[] pinfos)
106 {
107 pinfos = GetOnlinePresences(pinfos);
108 if (pinfos != null && pinfos.Length >= 1)
109 return pinfos[0];
110
111 return null;
112 }
39 } 113 }
40 114
41 public interface IPresenceService 115 public interface IPresenceService
42 { 116 {
43 bool Report(PresenceInfo presence); 117 bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID);
118 bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookAt);
119 bool LogoutRegionAgents(UUID regionID);
120
121 bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt);
122 bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt);
123
124 PresenceInfo GetAgent(UUID sessionID);
125 PresenceInfo[] GetAgents(string[] userIDs);
44 } 126 }
45} 127}
diff --git a/OpenSim/Services/Interfaces/ISimulationService.cs b/OpenSim/Services/Interfaces/ISimulationService.cs
index a169ab7..ec24d90 100644
--- a/OpenSim/Services/Interfaces/ISimulationService.cs
+++ b/OpenSim/Services/Interfaces/ISimulationService.cs
@@ -29,13 +29,17 @@ using System;
29using OpenSim.Framework; 29using OpenSim.Framework;
30using OpenMetaverse; 30using OpenMetaverse;
31 31
32using GridRegion = OpenSim.Services.Interfaces.GridRegion;
33
32namespace OpenSim.Services.Interfaces 34namespace OpenSim.Services.Interfaces
33{ 35{
34 public interface ISimulationService 36 public interface ISimulationService
35 { 37 {
38 IScene GetScene(ulong regionHandle);
39
36 #region Agents 40 #region Agents
37 41
38 bool CreateAgent(ulong regionHandle, AgentCircuitData aCircuit, out string reason); 42 bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason);
39 43
40 /// <summary> 44 /// <summary>
41 /// Full child agent update. 45 /// Full child agent update.
@@ -43,7 +47,7 @@ namespace OpenSim.Services.Interfaces
43 /// <param name="regionHandle"></param> 47 /// <param name="regionHandle"></param>
44 /// <param name="data"></param> 48 /// <param name="data"></param>
45 /// <returns></returns> 49 /// <returns></returns>
46 bool UpdateAgent(ulong regionHandle, AgentData data); 50 bool UpdateAgent(GridRegion destination, AgentData data);
47 51
48 /// <summary> 52 /// <summary>
49 /// Short child agent update, mostly for position. 53 /// Short child agent update, mostly for position.
@@ -51,9 +55,9 @@ namespace OpenSim.Services.Interfaces
51 /// <param name="regionHandle"></param> 55 /// <param name="regionHandle"></param>
52 /// <param name="data"></param> 56 /// <param name="data"></param>
53 /// <returns></returns> 57 /// <returns></returns>
54 bool UpdateAgent(ulong regionHandle, AgentPosition data); 58 bool UpdateAgent(GridRegion destination, AgentPosition data);
55 59
56 bool RetrieveAgent(ulong regionHandle, UUID id, out IAgentData agent); 60 bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent);
57 61
58 /// <summary> 62 /// <summary>
59 /// Message from receiving region to departing region, telling it got contacted by the client. 63 /// Message from receiving region to departing region, telling it got contacted by the client.
@@ -63,7 +67,7 @@ namespace OpenSim.Services.Interfaces
63 /// <param name="id"></param> 67 /// <param name="id"></param>
64 /// <param name="uri"></param> 68 /// <param name="uri"></param>
65 /// <returns></returns> 69 /// <returns></returns>
66 bool ReleaseAgent(ulong regionHandle, UUID id, string uri); 70 bool ReleaseAgent(UUID originRegion, UUID id, string uri);
67 71
68 /// <summary> 72 /// <summary>
69 /// Close agent. 73 /// Close agent.
@@ -71,7 +75,7 @@ namespace OpenSim.Services.Interfaces
71 /// <param name="regionHandle"></param> 75 /// <param name="regionHandle"></param>
72 /// <param name="id"></param> 76 /// <param name="id"></param>
73 /// <returns></returns> 77 /// <returns></returns>
74 bool CloseAgent(ulong regionHandle, UUID id); 78 bool CloseAgent(GridRegion destination, UUID id);
75 79
76 #endregion Agents 80 #endregion Agents
77 81
@@ -84,7 +88,7 @@ namespace OpenSim.Services.Interfaces
84 /// <param name="sog"></param> 88 /// <param name="sog"></param>
85 /// <param name="isLocalCall"></param> 89 /// <param name="isLocalCall"></param>
86 /// <returns></returns> 90 /// <returns></returns>
87 bool CreateObject(ulong regionHandle, ISceneObject sog, bool isLocalCall); 91 bool CreateObject(GridRegion destination, ISceneObject sog, bool isLocalCall);
88 92
89 /// <summary> 93 /// <summary>
90 /// Create an object from the user's inventory in the destination region. 94 /// Create an object from the user's inventory in the destination region.
@@ -94,15 +98,9 @@ namespace OpenSim.Services.Interfaces
94 /// <param name="userID"></param> 98 /// <param name="userID"></param>
95 /// <param name="itemID"></param> 99 /// <param name="itemID"></param>
96 /// <returns></returns> 100 /// <returns></returns>
97 bool CreateObject(ulong regionHandle, UUID userID, UUID itemID); 101 bool CreateObject(GridRegion destination, UUID userID, UUID itemID);
98 102
99 #endregion Objects 103 #endregion Objects
100 104
101 #region Regions
102
103 bool HelloNeighbour(ulong regionHandle, RegionInfo thisRegion);
104
105 #endregion Regions
106
107 } 105 }
108} 106}
diff --git a/OpenSim/Services/Interfaces/IUserAccountService.cs b/OpenSim/Services/Interfaces/IUserAccountService.cs
new file mode 100644
index 0000000..3dacf53
--- /dev/null
+++ b/OpenSim/Services/Interfaces/IUserAccountService.cs
@@ -0,0 +1,153 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31
32namespace OpenSim.Services.Interfaces
33{
34 public class UserAccount
35 {
36 public UserAccount()
37 {
38 }
39
40 public UserAccount(UUID principalID)
41 {
42 PrincipalID = principalID;
43 }
44
45 public UserAccount(UUID scopeID, string firstName, string lastName, string email)
46 {
47 PrincipalID = UUID.Random();
48 ScopeID = scopeID;
49 FirstName = firstName;
50 LastName = lastName;
51 Email = email;
52 ServiceURLs = new Dictionary<string, object>();
53 // Created = ???
54 }
55
56 public string FirstName;
57 public string LastName;
58 public string Email;
59 public UUID PrincipalID;
60 public UUID ScopeID;
61 public int UserLevel;
62 public int UserFlags;
63 public string UserTitle;
64
65 public Dictionary<string, object> ServiceURLs;
66
67 public int Created;
68
69 public string Name
70 {
71 get { return FirstName + " " + LastName; }
72 }
73
74 public UserAccount(Dictionary<string, object> kvp)
75 {
76 if (kvp.ContainsKey("FirstName"))
77 FirstName = kvp["FirstName"].ToString();
78 if (kvp.ContainsKey("LastName"))
79 LastName = kvp["LastName"].ToString();
80 if (kvp.ContainsKey("Email"))
81 Email = kvp["Email"].ToString();
82 if (kvp.ContainsKey("PrincipalID"))
83 UUID.TryParse(kvp["PrincipalID"].ToString(), out PrincipalID);
84 if (kvp.ContainsKey("ScopeID"))
85 UUID.TryParse(kvp["ScopeID"].ToString(), out ScopeID);
86 if (kvp.ContainsKey("UserLevel"))
87 Convert.ToInt32(kvp["UserLevel"].ToString());
88 if (kvp.ContainsKey("UserFlags"))
89 Convert.ToInt32(kvp["UserFlags"].ToString());
90 if (kvp.ContainsKey("UserTitle"))
91 Email = kvp["UserTitle"].ToString();
92
93 if (kvp.ContainsKey("Created"))
94 Convert.ToInt32(kvp["Created"].ToString());
95 if (kvp.ContainsKey("ServiceURLs") && kvp["ServiceURLs"] != null)
96 {
97 ServiceURLs = new Dictionary<string, object>();
98 string str = kvp["ServiceURLs"].ToString();
99 if (str != string.Empty)
100 {
101 string[] parts = str.Split(new char[] { ';' });
102 Dictionary<string, object> dic = new Dictionary<string, object>();
103 foreach (string s in parts)
104 {
105 string[] parts2 = s.Split(new char[] { '*' });
106 if (parts2.Length == 2)
107 ServiceURLs[parts2[0]] = parts2[1];
108 }
109 }
110 }
111 }
112
113 public Dictionary<string, object> ToKeyValuePairs()
114 {
115 Dictionary<string, object> result = new Dictionary<string, object>();
116 result["FirstName"] = FirstName;
117 result["LastName"] = LastName;
118 result["Email"] = Email;
119 result["PrincipalID"] = PrincipalID.ToString();
120 result["ScopeID"] = ScopeID.ToString();
121 result["Created"] = Created.ToString();
122 result["UserLevel"] = UserLevel.ToString();
123 result["UserFlags"] = UserFlags.ToString();
124 result["UserTitle"] = UserTitle;
125
126 string str = string.Empty;
127 foreach (KeyValuePair<string, object> kvp in ServiceURLs)
128 {
129 str += kvp.Key + "*" + (kvp.Value == null ? "" : kvp.Value) + ";";
130 }
131 result["ServiceURLs"] = str;
132
133 return result;
134 }
135
136 };
137
138 public interface IUserAccountService
139 {
140 UserAccount GetUserAccount(UUID scopeID, UUID userID);
141 UserAccount GetUserAccount(UUID scopeID, string FirstName, string LastName);
142 UserAccount GetUserAccount(UUID scopeID, string Email);
143 // Returns the list of avatars that matches both the search
144 // criterion and the scope ID passed
145 //
146 List<UserAccount> GetUserAccounts(UUID scopeID, string query);
147
148 // Store the data given, wich replaces the sotred data, therefore
149 // must be complete.
150 //
151 bool StoreUserAccount(UserAccount data);
152 }
153}
diff --git a/OpenSim/Services/Interfaces/IUserService.cs b/OpenSim/Services/Interfaces/IUserService.cs
deleted file mode 100644
index 92bd8ef..0000000
--- a/OpenSim/Services/Interfaces/IUserService.cs
+++ /dev/null
@@ -1,103 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using OpenMetaverse;
30
31namespace OpenSim.Services.Interfaces
32{
33 public class UserAccount
34 {
35 public UserAccount()
36 {
37 }
38
39 public UserAccount(UUID userID, UUID homeRegionID, float homePositionX,
40 float homePositionY, float homePositionZ, float homeLookAtX,
41 float homeLookAtY, float homeLookAtZ)
42 {
43 UserID = userID;
44 HomeRegionID = homeRegionID;
45 HomePositionX = homePositionX;
46 HomePositionY = homePositionY;
47 HomePositionZ = homePositionZ;
48 HomeLookAtX = homeLookAtX;
49 HomeLookAtY = homeLookAtY;
50 HomeLookAtZ = homeLookAtZ;
51 }
52
53 public string FirstName;
54 public string LastName;
55 public UUID UserID;
56 public UUID ScopeID;
57
58 // For informational purposes only!
59 //
60 public string HomeRegionName;
61
62 public UUID HomeRegionID;
63 public float HomePositionX;
64 public float HomePositionY;
65 public float HomePositionZ;
66 public float HomeLookAtX;
67 public float HomeLookAtY;
68 public float HomeLookAtZ;
69
70 // These are here because they
71 // concern the account rather than
72 // the profile. They just happen to
73 // be used in the Linden profile as well
74 //
75 public int GodLevel;
76 public int UserFlags;
77 public string AccountType;
78
79 };
80
81 public interface IUserAccountService
82 {
83 UserAccount GetUserAccount(UUID scopeID, UUID userID);
84 UserAccount GetUserAccount(UUID scopeID, string FirstName, string LastName);
85 // Returns the list of avatars that matches both the search
86 // criterion and the scope ID passed
87 //
88 List<UserAccount> GetUserAccount(UUID scopeID, string query);
89
90
91 // This will set only the home region portion of the data!
92 // Can't be used to set god level, flags, type or change the name!
93 //
94 bool SetHomePosition(UserAccount data, UUID RegionID, UUID RegionSecret);
95
96 // Update all updatable fields
97 //
98 bool SetUserAccount(UserAccount data, UUID PrincipalID, string token);
99
100 // Creates a user data record
101 bool CreateUserAccount(UserAccount data, UUID PrincipalID, string token);
102 }
103}
diff --git a/OpenSim/Services/InventoryService/InventoryService.cs b/OpenSim/Services/InventoryService/InventoryService.cs
index 95007f1..781b89b 100644
--- a/OpenSim/Services/InventoryService/InventoryService.cs
+++ b/OpenSim/Services/InventoryService/InventoryService.cs
@@ -298,6 +298,7 @@ namespace OpenSim.Services.InventoryService
298 if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown)) 298 if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
299 folders[(AssetType)folder.Type] = folder; 299 folders[(AssetType)folder.Type] = folder;
300 } 300 }
301 m_log.DebugFormat("[INVENTORY SERVICE]: Got {0} system folders for {1}", folders.Count, userID);
301 return folders; 302 return folders;
302 } 303 }
303 } 304 }
diff --git a/OpenSim/Services/InventoryService/LibraryService.cs b/OpenSim/Services/InventoryService/LibraryService.cs
new file mode 100644
index 0000000..383f311
--- /dev/null
+++ b/OpenSim/Services/InventoryService/LibraryService.cs
@@ -0,0 +1,283 @@
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.IO;
31using System.Reflection;
32using System.Xml;
33
34using OpenSim.Framework;
35using OpenSim.Services.Base;
36using OpenSim.Services.Interfaces;
37
38using log4net;
39using Nini.Config;
40using OpenMetaverse;
41
42namespace OpenSim.Services.InventoryService
43{
44 /// <summary>
45 /// Basically a hack to give us a Inventory library while we don't have a inventory server
46 /// once the server is fully implemented then should read the data from that
47 /// </summary>
48 public class LibraryService : ServiceBase, ILibraryService
49 {
50 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51
52 private InventoryFolderImpl m_LibraryRootFolder;
53
54 public InventoryFolderImpl LibraryRootFolder
55 {
56 get { return m_LibraryRootFolder; }
57 }
58
59 private UUID libOwner = new UUID("11111111-1111-0000-0000-000100bba000");
60
61 /// <summary>
62 /// Holds the root library folder and all its descendents. This is really only used during inventory
63 /// setup so that we don't have to repeatedly search the tree of library folders.
64 /// </summary>
65 protected Dictionary<UUID, InventoryFolderImpl> libraryFolders
66 = new Dictionary<UUID, InventoryFolderImpl>();
67
68 public LibraryService(IConfigSource config)
69 : base(config)
70 {
71 string pLibrariesLocation = Path.Combine("inventory", "Libraries.xml");
72 string pLibName = "OpenSim Library";
73
74 IConfig libConfig = config.Configs["LibraryService"];
75 if (libConfig != null)
76 {
77 pLibrariesLocation = libConfig.GetString("DefaultLibrary", pLibrariesLocation);
78 pLibName = libConfig.GetString("LibraryName", pLibName);
79 }
80
81 m_log.Debug("[LIBRARY]: Starting library service...");
82
83 m_LibraryRootFolder = new InventoryFolderImpl();
84 m_LibraryRootFolder.Owner = libOwner;
85 m_LibraryRootFolder.ID = new UUID("00000112-000f-0000-0000-000100bba000");
86 m_LibraryRootFolder.Name = pLibName;
87 m_LibraryRootFolder.ParentID = UUID.Zero;
88 m_LibraryRootFolder.Type = (short)8;
89 m_LibraryRootFolder.Version = (ushort)1;
90
91 libraryFolders.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder);
92
93 LoadLibraries(pLibrariesLocation);
94 }
95
96 public InventoryItemBase CreateItem(UUID inventoryID, UUID assetID, string name, string description,
97 int assetType, int invType, UUID parentFolderID)
98 {
99 InventoryItemBase item = new InventoryItemBase();
100 item.Owner = libOwner;
101 item.CreatorId = libOwner.ToString();
102 item.ID = inventoryID;
103 item.AssetID = assetID;
104 item.Description = description;
105 item.Name = name;
106 item.AssetType = assetType;
107 item.InvType = invType;
108 item.Folder = parentFolderID;
109 item.BasePermissions = 0x7FFFFFFF;
110 item.EveryOnePermissions = 0x7FFFFFFF;
111 item.CurrentPermissions = 0x7FFFFFFF;
112 item.NextPermissions = 0x7FFFFFFF;
113 return item;
114 }
115
116 /// <summary>
117 /// Use the asset set information at path to load assets
118 /// </summary>
119 /// <param name="path"></param>
120 /// <param name="assets"></param>
121 protected void LoadLibraries(string librariesControlPath)
122 {
123 m_log.InfoFormat("[LIBRARY INVENTORY]: Loading library control file {0}", librariesControlPath);
124 LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig);
125 }
126
127 /// <summary>
128 /// Read a library set from config
129 /// </summary>
130 /// <param name="config"></param>
131 protected void ReadLibraryFromConfig(IConfig config, string path)
132 {
133 string basePath = Path.GetDirectoryName(path);
134 string foldersPath
135 = Path.Combine(
136 basePath, config.GetString("foldersFile", String.Empty));
137
138 LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig);
139
140 string itemsPath
141 = Path.Combine(
142 basePath, config.GetString("itemsFile", String.Empty));
143
144 LoadFromFile(itemsPath, "Library items", ReadItemFromConfig);
145 }
146
147 /// <summary>
148 /// Read a library inventory folder from a loaded configuration
149 /// </summary>
150 /// <param name="source"></param>
151 private void ReadFolderFromConfig(IConfig config, string path)
152 {
153 InventoryFolderImpl folderInfo = new InventoryFolderImpl();
154
155 folderInfo.ID = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString()));
156 folderInfo.Name = config.GetString("name", "unknown");
157 folderInfo.ParentID = new UUID(config.GetString("parentFolderID", m_LibraryRootFolder.ID.ToString()));
158 folderInfo.Type = (short)config.GetInt("type", 8);
159
160 folderInfo.Owner = libOwner;
161 folderInfo.Version = 1;
162
163 if (libraryFolders.ContainsKey(folderInfo.ParentID))
164 {
165 InventoryFolderImpl parentFolder = libraryFolders[folderInfo.ParentID];
166
167 libraryFolders.Add(folderInfo.ID, folderInfo);
168 parentFolder.AddChildFolder(folderInfo);
169
170// m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID);
171 }
172 else
173 {
174 m_log.WarnFormat(
175 "[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!",
176 folderInfo.Name, folderInfo.ID, folderInfo.ParentID);
177 }
178 }
179
180 /// <summary>
181 /// Read a library inventory item metadata from a loaded configuration
182 /// </summary>
183 /// <param name="source"></param>
184 private void ReadItemFromConfig(IConfig config, string path)
185 {
186 InventoryItemBase item = new InventoryItemBase();
187 item.Owner = libOwner;
188 item.CreatorId = libOwner.ToString();
189 item.ID = new UUID(config.GetString("inventoryID", m_LibraryRootFolder.ID.ToString()));
190 item.AssetID = new UUID(config.GetString("assetID", item.ID.ToString()));
191 item.Folder = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString()));
192 item.Name = config.GetString("name", String.Empty);
193 item.Description = config.GetString("description", item.Name);
194 item.InvType = config.GetInt("inventoryType", 0);
195 item.AssetType = config.GetInt("assetType", item.InvType);
196 item.CurrentPermissions = (uint)config.GetLong("currentPermissions", 0x7FFFFFFF);
197 item.NextPermissions = (uint)config.GetLong("nextPermissions", 0x7FFFFFFF);
198 item.EveryOnePermissions = (uint)config.GetLong("everyonePermissions", 0x7FFFFFFF);
199 item.BasePermissions = (uint)config.GetLong("basePermissions", 0x7FFFFFFF);
200 item.Flags = (uint)config.GetInt("flags", 0);
201
202 if (libraryFolders.ContainsKey(item.Folder))
203 {
204 InventoryFolderImpl parentFolder = libraryFolders[item.Folder];
205 try
206 {
207 parentFolder.Items.Add(item.ID, item);
208 }
209 catch (Exception)
210 {
211 m_log.WarnFormat("[LIBRARY INVENTORY] Item {1} [{0}] not added, duplicate item", item.ID, item.Name);
212 }
213 }
214 else
215 {
216 m_log.WarnFormat(
217 "[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!",
218 item.Name, item.ID, item.Folder);
219 }
220 }
221
222 private delegate void ConfigAction(IConfig config, string path);
223
224 /// <summary>
225 /// Load the given configuration at a path and perform an action on each Config contained within it
226 /// </summary>
227 /// <param name="path"></param>
228 /// <param name="fileDescription"></param>
229 /// <param name="action"></param>
230 private static void LoadFromFile(string path, string fileDescription, ConfigAction action)
231 {
232 if (File.Exists(path))
233 {
234 try
235 {
236 XmlConfigSource source = new XmlConfigSource(path);
237
238 for (int i = 0; i < source.Configs.Count; i++)
239 {
240 action(source.Configs[i], path);
241 }
242 }
243 catch (XmlException e)
244 {
245 m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e);
246 }
247 }
248 else
249 {
250 m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path);
251 }
252 }
253
254 /// <summary>
255 /// Looks like a simple getter, but is written like this for some consistency with the other Request
256 /// methods in the superclass
257 /// </summary>
258 /// <returns></returns>
259 public Dictionary<UUID, InventoryFolderImpl> GetAllFolders()
260 {
261 Dictionary<UUID, InventoryFolderImpl> fs = new Dictionary<UUID, InventoryFolderImpl>();
262 fs.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder);
263 List<InventoryFolderImpl> fis = TraverseFolder(m_LibraryRootFolder);
264 foreach (InventoryFolderImpl f in fis)
265 {
266 fs.Add(f.ID, f);
267 }
268 //return libraryFolders;
269 return fs;
270 }
271
272 private List<InventoryFolderImpl> TraverseFolder(InventoryFolderImpl node)
273 {
274 List<InventoryFolderImpl> folders = node.RequestListOfFolderImpls();
275 List<InventoryFolderImpl> subs = new List<InventoryFolderImpl>();
276 foreach (InventoryFolderImpl f in folders)
277 subs.AddRange(TraverseFolder(f));
278
279 folders.AddRange(subs);
280 return folders;
281 }
282 }
283}
diff --git a/OpenSim/Services/LLLoginService/LLLoginResponse.cs b/OpenSim/Services/LLLoginService/LLLoginResponse.cs
new file mode 100644
index 0000000..4db6a05
--- /dev/null
+++ b/OpenSim/Services/LLLoginService/LLLoginResponse.cs
@@ -0,0 +1,971 @@
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.Collections.Generic;
31using System.Net;
32using System.Reflection;
33
34using OpenSim.Framework;
35using OpenSim.Framework.Capabilities;
36using OpenSim.Services.Interfaces;
37using GridRegion = OpenSim.Services.Interfaces.GridRegion;
38
39using log4net;
40using OpenMetaverse;
41using OpenMetaverse.StructuredData;
42using OSDArray = OpenMetaverse.StructuredData.OSDArray;
43using OSDMap = OpenMetaverse.StructuredData.OSDMap;
44
45namespace OpenSim.Services.LLLoginService
46{
47 public class LLFailedLoginResponse : OpenSim.Services.Interfaces.FailedLoginResponse
48 {
49 string m_key;
50 string m_value;
51 string m_login;
52
53 public static LLFailedLoginResponse UserProblem;
54 public static LLFailedLoginResponse AuthorizationProblem;
55 public static LLFailedLoginResponse GridProblem;
56 public static LLFailedLoginResponse InventoryProblem;
57 public static LLFailedLoginResponse DeadRegionProblem;
58 public static LLFailedLoginResponse LoginBlockedProblem;
59 public static LLFailedLoginResponse AlreadyLoggedInProblem;
60 public static LLFailedLoginResponse InternalError;
61
62 static LLFailedLoginResponse()
63 {
64 UserProblem = new LLFailedLoginResponse("key",
65 "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
66 "false");
67 AuthorizationProblem = new LLFailedLoginResponse("key",
68 "Error connecting to grid. Unable to authorize your session into the region.",
69 "false");
70 GridProblem = new LLFailedLoginResponse("key",
71 "Error connecting to the desired location. Try connecting to another region.",
72 "false");
73 InventoryProblem = new LLFailedLoginResponse("key",
74 "The inventory service is not responding. Please notify your login region operator.",
75 "false");
76 DeadRegionProblem = new LLFailedLoginResponse("key",
77 "The region you are attempting to log into is not responding. Please select another region and try again.",
78 "false");
79 LoginBlockedProblem = new LLFailedLoginResponse("presence",
80 "Logins are currently restricted. Please try again later.",
81 "false");
82 AlreadyLoggedInProblem = new LLFailedLoginResponse("presence",
83 "You appear to be already logged in. " +
84 "If this is not the case please wait for your session to timeout. " +
85 "If this takes longer than a few minutes please contact the grid owner. " +
86 "Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.",
87 "false");
88 InternalError = new LLFailedLoginResponse("Internal Error", "Error generating Login Response", "false");
89 }
90
91 public LLFailedLoginResponse(string key, string value, string login)
92 {
93 m_key = key;
94 m_value = value;
95 m_login = login;
96 }
97
98 public override Hashtable ToHashtable()
99 {
100 Hashtable loginError = new Hashtable();
101 loginError["reason"] = m_key;
102 loginError["message"] = m_value;
103 loginError["login"] = m_login;
104 return loginError;
105 }
106
107 public override OSD ToOSDMap()
108 {
109 OSDMap map = new OSDMap();
110
111 map["reason"] = OSD.FromString(m_key);
112 map["message"] = OSD.FromString(m_value);
113 map["login"] = OSD.FromString(m_login);
114
115 return map;
116 }
117 }
118
119 /// <summary>
120 /// A class to handle LL login response.
121 /// </summary>
122 public class LLLoginResponse : OpenSim.Services.Interfaces.LoginResponse
123 {
124 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
125 private static Hashtable globalTexturesHash;
126 // Global Textures
127 private static string sunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271";
128 private static string cloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621";
129 private static string moonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621";
130
131 private Hashtable loginFlagsHash;
132 private Hashtable uiConfigHash;
133
134 private ArrayList loginFlags;
135 private ArrayList globalTextures;
136 private ArrayList eventCategories;
137 private ArrayList uiConfig;
138 private ArrayList classifiedCategories;
139 private ArrayList inventoryRoot;
140 private ArrayList initialOutfit;
141 private ArrayList agentInventory;
142 private ArrayList inventoryLibraryOwner;
143 private ArrayList inventoryLibRoot;
144 private ArrayList inventoryLibrary;
145 private ArrayList activeGestures;
146
147 private UserInfo userProfile;
148
149 private UUID agentID;
150 private UUID sessionID;
151 private UUID secureSessionID;
152
153 // Login Flags
154 private string dst;
155 private string stipendSinceLogin;
156 private string gendered;
157 private string everLoggedIn;
158 private string login;
159 private uint simPort;
160 private uint simHttpPort;
161 private string simAddress;
162 private string agentAccess;
163 private string agentAccessMax;
164 private Int32 circuitCode;
165 private uint regionX;
166 private uint regionY;
167
168 // Login
169 private string firstname;
170 private string lastname;
171
172 // Error Flags
173 private string errorReason;
174 private string errorMessage;
175
176 private string welcomeMessage;
177 private string startLocation;
178 private string allowFirstLife;
179 private string home;
180 private string seedCapability;
181 private string lookAt;
182
183 private BuddyList m_buddyList = null;
184
185 static LLLoginResponse()
186 {
187 // This is being set, but it's not used
188 // not sure why.
189 globalTexturesHash = new Hashtable();
190 globalTexturesHash["sun_texture_id"] = sunTexture;
191 globalTexturesHash["cloud_texture_id"] = cloudTexture;
192 globalTexturesHash["moon_texture_id"] = moonTexture;
193 }
194
195 public LLLoginResponse()
196 {
197 loginFlags = new ArrayList();
198 globalTextures = new ArrayList();
199 eventCategories = new ArrayList();
200 uiConfig = new ArrayList();
201 classifiedCategories = new ArrayList();
202
203 uiConfigHash = new Hashtable();
204
205 // defaultXmlRpcResponse = new XmlRpcResponse();
206 userProfile = new UserInfo();
207 inventoryRoot = new ArrayList();
208 initialOutfit = new ArrayList();
209 agentInventory = new ArrayList();
210 inventoryLibrary = new ArrayList();
211 inventoryLibraryOwner = new ArrayList();
212 activeGestures = new ArrayList();
213
214 SetDefaultValues();
215 }
216
217 public LLLoginResponse(UserAccount account, AgentCircuitData aCircuit, PresenceInfo pinfo,
218 GridRegion destination, List<InventoryFolderBase> invSkel, ILibraryService libService,
219 string where, string startlocation, Vector3 position, Vector3 lookAt, string message,
220 GridRegion home, IPEndPoint clientIP)
221 : this()
222 {
223 FillOutInventoryData(invSkel, libService);
224
225 CircuitCode = (int)aCircuit.circuitcode;
226 Lastname = account.LastName;
227 Firstname = account.FirstName;
228 AgentID = account.PrincipalID;
229 SessionID = aCircuit.SessionID;
230 SecureSessionID = aCircuit.SecureSessionID;
231 Message = message;
232 // While we don't have friends...
233 //BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
234 BuddList = new LLLoginResponse.BuddyList();
235 StartLocation = where;
236
237 FillOutHomeData(pinfo, home);
238 LookAt = String.Format("[r{0},r{1},r{2}]", lookAt.X, lookAt.Y, lookAt.Z);
239
240 FillOutRegionData(destination);
241
242 FillOutSeedCap(aCircuit, destination, clientIP);
243
244 }
245
246 private void FillOutInventoryData(List<InventoryFolderBase> invSkel, ILibraryService libService)
247 {
248 InventoryData inventData = null;
249
250 try
251 {
252 inventData = GetInventorySkeleton(invSkel);
253 }
254 catch (Exception e)
255 {
256 m_log.WarnFormat(
257 "[LLLOGIN SERVICE]: Error processing inventory skeleton of agent {0} - {1}",
258 agentID, e);
259
260 // ignore and continue
261 }
262
263 if (inventData != null)
264 {
265 ArrayList AgentInventoryArray = inventData.InventoryArray;
266
267 Hashtable InventoryRootHash = new Hashtable();
268 InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
269 InventoryRoot = new ArrayList();
270 InventoryRoot.Add(InventoryRootHash);
271 InventorySkeleton = AgentInventoryArray;
272 }
273
274 // Inventory Library Section
275 if (libService != null && libService.LibraryRootFolder != null)
276 {
277 Hashtable InventoryLibRootHash = new Hashtable();
278 InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
279 InventoryLibRoot = new ArrayList();
280 InventoryLibRoot.Add(InventoryLibRootHash);
281
282 InventoryLibraryOwner = GetLibraryOwner(libService.LibraryRootFolder);
283 InventoryLibrary = GetInventoryLibrary(libService);
284 }
285 }
286
287 private void FillOutHomeData(PresenceInfo pinfo, GridRegion home)
288 {
289 int x = 1000 * (int)Constants.RegionSize, y = 1000 * (int)Constants.RegionSize;
290 if (home != null)
291 {
292 x = home.RegionLocX;
293 y = home.RegionLocY;
294 }
295
296 Home = string.Format(
297 "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
298 x,
299 y,
300 pinfo.HomePosition.X, pinfo.HomePosition.Y, pinfo.HomePosition.Z,
301 pinfo.HomeLookAt.X, pinfo.HomeLookAt.Y, pinfo.HomeLookAt.Z);
302
303 }
304
305 private void FillOutRegionData(GridRegion destination)
306 {
307 IPEndPoint endPoint = destination.ExternalEndPoint;
308 SimAddress = endPoint.Address.ToString();
309 SimPort = (uint)endPoint.Port;
310 RegionX = (uint)destination.RegionLocX;
311 RegionY = (uint)destination.RegionLocY;
312 }
313
314 private void FillOutSeedCap(AgentCircuitData aCircuit, GridRegion destination, IPEndPoint ipepClient)
315 {
316 string capsSeedPath = String.Empty;
317
318 // Don't use the following! It Fails for logging into any region not on the same port as the http server!
319 // Kept here so it doesn't happen again!
320 // response.SeedCapability = regionInfo.ServerURI + capsSeedPath;
321
322 #region IP Translation for NAT
323 if (ipepClient != null)
324 {
325 capsSeedPath
326 = "http://"
327 + NetworkUtil.GetHostFor(ipepClient.Address, destination.ExternalHostName)
328 + ":"
329 + destination.HttpPort
330 + CapsUtil.GetCapsSeedPath(aCircuit.CapsPath);
331 }
332 else
333 {
334 capsSeedPath
335 = "http://"
336 + destination.ExternalHostName
337 + ":"
338 + destination.HttpPort
339 + CapsUtil.GetCapsSeedPath(aCircuit.CapsPath);
340 }
341 #endregion
342
343 SeedCapability = capsSeedPath;
344 }
345
346 private void SetDefaultValues()
347 {
348 DST = TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now) ? "Y" : "N";
349 StipendSinceLogin = "N";
350 Gendered = "Y";
351 EverLoggedIn = "Y";
352 login = "false";
353 firstname = "Test";
354 lastname = "User";
355 agentAccess = "M";
356 agentAccessMax = "A";
357 startLocation = "last";
358 allowFirstLife = "Y";
359
360 ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock.";
361 ErrorReason = "key";
362 welcomeMessage = "Welcome to OpenSim!";
363 seedCapability = String.Empty;
364 home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" +
365 userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" +
366 userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" +
367 userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}";
368 lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]";
369 RegionX = (uint) 255232;
370 RegionY = (uint) 254976;
371
372 // Classifieds;
373 AddClassifiedCategory((Int32) 1, "Shopping");
374 AddClassifiedCategory((Int32) 2, "Land Rental");
375 AddClassifiedCategory((Int32) 3, "Property Rental");
376 AddClassifiedCategory((Int32) 4, "Special Attraction");
377 AddClassifiedCategory((Int32) 5, "New Products");
378 AddClassifiedCategory((Int32) 6, "Employment");
379 AddClassifiedCategory((Int32) 7, "Wanted");
380 AddClassifiedCategory((Int32) 8, "Service");
381 AddClassifiedCategory((Int32) 9, "Personal");
382
383 SessionID = UUID.Random();
384 SecureSessionID = UUID.Random();
385 AgentID = UUID.Random();
386
387 Hashtable InitialOutfitHash = new Hashtable();
388 InitialOutfitHash["folder_name"] = "Nightclub Female";
389 InitialOutfitHash["gender"] = "female";
390 initialOutfit.Add(InitialOutfitHash);
391 }
392
393
394 public override Hashtable ToHashtable()
395 {
396 try
397 {
398 Hashtable responseData = new Hashtable();
399
400 loginFlagsHash = new Hashtable();
401 loginFlagsHash["daylight_savings"] = DST;
402 loginFlagsHash["stipend_since_login"] = StipendSinceLogin;
403 loginFlagsHash["gendered"] = Gendered;
404 loginFlagsHash["ever_logged_in"] = EverLoggedIn;
405 loginFlags.Add(loginFlagsHash);
406
407 responseData["first_name"] = Firstname;
408 responseData["last_name"] = Lastname;
409 responseData["agent_access"] = agentAccess;
410 responseData["agent_access_max"] = agentAccessMax;
411
412 globalTextures.Add(globalTexturesHash);
413 // this.eventCategories.Add(this.eventCategoriesHash);
414
415 AddToUIConfig("allow_first_life", allowFirstLife);
416 uiConfig.Add(uiConfigHash);
417
418 responseData["sim_port"] = (Int32) SimPort;
419 responseData["sim_ip"] = SimAddress;
420 responseData["http_port"] = (Int32)SimHttpPort;
421
422 responseData["agent_id"] = AgentID.ToString();
423 responseData["session_id"] = SessionID.ToString();
424 responseData["secure_session_id"] = SecureSessionID.ToString();
425 responseData["circuit_code"] = CircuitCode;
426 responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
427 responseData["login-flags"] = loginFlags;
428 responseData["global-textures"] = globalTextures;
429 responseData["seed_capability"] = seedCapability;
430
431 responseData["event_categories"] = eventCategories;
432 responseData["event_notifications"] = new ArrayList(); // todo
433 responseData["classified_categories"] = classifiedCategories;
434 responseData["ui-config"] = uiConfig;
435
436 if (agentInventory != null)
437 {
438 responseData["inventory-skeleton"] = agentInventory;
439 responseData["inventory-root"] = inventoryRoot;
440 }
441 responseData["inventory-skel-lib"] = inventoryLibrary;
442 responseData["inventory-lib-root"] = inventoryLibRoot;
443 responseData["gestures"] = activeGestures;
444 responseData["inventory-lib-owner"] = inventoryLibraryOwner;
445 responseData["initial-outfit"] = initialOutfit;
446 responseData["start_location"] = startLocation;
447 responseData["seed_capability"] = seedCapability;
448 responseData["home"] = home;
449 responseData["look_at"] = lookAt;
450 responseData["message"] = welcomeMessage;
451 responseData["region_x"] = (Int32)(RegionX);
452 responseData["region_y"] = (Int32)(RegionY);
453
454 if (m_buddyList != null)
455 {
456 responseData["buddy-list"] = m_buddyList.ToArray();
457 }
458
459 responseData["login"] = "true";
460
461 return responseData;
462 }
463 catch (Exception e)
464 {
465 m_log.Warn("[CLIENT]: LoginResponse: Error creating Hashtable Response: " + e.Message);
466
467 return LLFailedLoginResponse.InternalError.ToHashtable();
468 }
469 }
470
471 public override OSD ToOSDMap()
472 {
473 try
474 {
475 OSDMap map = new OSDMap();
476
477 map["first_name"] = OSD.FromString(Firstname);
478 map["last_name"] = OSD.FromString(Lastname);
479 map["agent_access"] = OSD.FromString(agentAccess);
480 map["agent_access_max"] = OSD.FromString(agentAccessMax);
481
482 map["sim_port"] = OSD.FromInteger(SimPort);
483 map["sim_ip"] = OSD.FromString(SimAddress);
484
485 map["agent_id"] = OSD.FromUUID(AgentID);
486 map["session_id"] = OSD.FromUUID(SessionID);
487 map["secure_session_id"] = OSD.FromUUID(SecureSessionID);
488 map["circuit_code"] = OSD.FromInteger(CircuitCode);
489 map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
490
491 #region Login Flags
492
493 OSDMap loginFlagsLLSD = new OSDMap();
494 loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST);
495 loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin);
496 loginFlagsLLSD["gendered"] = OSD.FromString(Gendered);
497 loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn);
498 map["login-flags"] = WrapOSDMap(loginFlagsLLSD);
499
500 #endregion Login Flags
501
502 #region Global Textures
503
504 OSDMap globalTexturesLLSD = new OSDMap();
505 globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture);
506 globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture);
507 globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture);
508
509 map["global-textures"] = WrapOSDMap(globalTexturesLLSD);
510
511 #endregion Global Textures
512
513 map["seed_capability"] = OSD.FromString(seedCapability);
514
515 map["event_categories"] = ArrayListToOSDArray(eventCategories);
516 //map["event_notifications"] = new OSDArray(); // todo
517 map["classified_categories"] = ArrayListToOSDArray(classifiedCategories);
518
519 #region UI Config
520
521 OSDMap uiConfigLLSD = new OSDMap();
522 uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife);
523 map["ui-config"] = WrapOSDMap(uiConfigLLSD);
524
525 #endregion UI Config
526
527 #region Inventory
528
529 map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory);
530
531 map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary);
532 map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ;
533 map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot);
534 map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner);
535
536 #endregion Inventory
537
538 map["gestures"] = ArrayListToOSDArray(activeGestures);
539
540 map["initial-outfit"] = ArrayListToOSDArray(initialOutfit);
541 map["start_location"] = OSD.FromString(startLocation);
542
543 map["seed_capability"] = OSD.FromString(seedCapability);
544 map["home"] = OSD.FromString(home);
545 map["look_at"] = OSD.FromString(lookAt);
546 map["message"] = OSD.FromString(welcomeMessage);
547 map["region_x"] = OSD.FromInteger(RegionX);
548 map["region_y"] = OSD.FromInteger(RegionY);
549
550 if (m_buddyList != null)
551 {
552 map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray());
553 }
554
555 map["login"] = OSD.FromString("true");
556
557 return map;
558 }
559 catch (Exception e)
560 {
561 m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message);
562
563 return LLFailedLoginResponse.InternalError.ToOSDMap();
564 }
565 }
566
567 public OSDArray ArrayListToOSDArray(ArrayList arrlst)
568 {
569 OSDArray llsdBack = new OSDArray();
570 foreach (Hashtable ht in arrlst)
571 {
572 OSDMap mp = new OSDMap();
573 foreach (DictionaryEntry deHt in ht)
574 {
575 mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value));
576 }
577 llsdBack.Add(mp);
578 }
579 return llsdBack;
580 }
581
582 private static OSDArray WrapOSDMap(OSDMap wrapMe)
583 {
584 OSDArray array = new OSDArray();
585 array.Add(wrapMe);
586 return array;
587 }
588
589 public void SetEventCategories(string category, string value)
590 {
591 // this.eventCategoriesHash[category] = value;
592 //TODO
593 }
594
595 public void AddToUIConfig(string itemName, string item)
596 {
597 uiConfigHash[itemName] = item;
598 }
599
600 public void AddClassifiedCategory(Int32 ID, string categoryName)
601 {
602 Hashtable hash = new Hashtable();
603 hash["category_name"] = categoryName;
604 hash["category_id"] = ID;
605 classifiedCategories.Add(hash);
606 // this.classifiedCategoriesHash.Clear();
607 }
608
609
610 private static LLLoginResponse.BuddyList ConvertFriendListItem(List<FriendListItem> LFL)
611 {
612 LLLoginResponse.BuddyList buddylistreturn = new LLLoginResponse.BuddyList();
613 foreach (FriendListItem fl in LFL)
614 {
615 LLLoginResponse.BuddyList.BuddyInfo buddyitem = new LLLoginResponse.BuddyList.BuddyInfo(fl.Friend);
616 buddyitem.BuddyID = fl.Friend;
617 buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms;
618 buddyitem.BuddyRightsGiven = (int)fl.FriendPerms;
619 buddylistreturn.AddNewBuddy(buddyitem);
620 }
621 return buddylistreturn;
622 }
623
624 private InventoryData GetInventorySkeleton(List<InventoryFolderBase> folders)
625 {
626 UUID rootID = UUID.Zero;
627 ArrayList AgentInventoryArray = new ArrayList();
628 Hashtable TempHash;
629 foreach (InventoryFolderBase InvFolder in folders)
630 {
631 if (InvFolder.ParentID == UUID.Zero)
632 {
633 rootID = InvFolder.ID;
634 }
635 TempHash = new Hashtable();
636 TempHash["name"] = InvFolder.Name;
637 TempHash["parent_id"] = InvFolder.ParentID.ToString();
638 TempHash["version"] = (Int32)InvFolder.Version;
639 TempHash["type_default"] = (Int32)InvFolder.Type;
640 TempHash["folder_id"] = InvFolder.ID.ToString();
641 AgentInventoryArray.Add(TempHash);
642 }
643
644 return new InventoryData(AgentInventoryArray, rootID);
645
646 }
647
648 /// <summary>
649 /// Converts the inventory library skeleton into the form required by the rpc request.
650 /// </summary>
651 /// <returns></returns>
652 protected virtual ArrayList GetInventoryLibrary(ILibraryService library)
653 {
654 Dictionary<UUID, InventoryFolderImpl> rootFolders = library.GetAllFolders();
655 m_log.DebugFormat("[LLOGIN]: Library has {0} folders", rootFolders.Count);
656 //Dictionary<UUID, InventoryFolderImpl> rootFolders = new Dictionary<UUID,InventoryFolderImpl>();
657 ArrayList folderHashes = new ArrayList();
658
659 foreach (InventoryFolderBase folder in rootFolders.Values)
660 {
661 Hashtable TempHash = new Hashtable();
662 TempHash["name"] = folder.Name;
663 TempHash["parent_id"] = folder.ParentID.ToString();
664 TempHash["version"] = (Int32)folder.Version;
665 TempHash["type_default"] = (Int32)folder.Type;
666 TempHash["folder_id"] = folder.ID.ToString();
667 folderHashes.Add(TempHash);
668 }
669
670 return folderHashes;
671 }
672
673 /// <summary>
674 ///
675 /// </summary>
676 /// <returns></returns>
677 protected virtual ArrayList GetLibraryOwner(InventoryFolderImpl libFolder)
678 {
679 //for now create random inventory library owner
680 Hashtable TempHash = new Hashtable();
681 TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; // libFolder.Owner
682 ArrayList inventoryLibOwner = new ArrayList();
683 inventoryLibOwner.Add(TempHash);
684 return inventoryLibOwner;
685 }
686
687 public class InventoryData
688 {
689 public ArrayList InventoryArray = null;
690 public UUID RootFolderID = UUID.Zero;
691
692 public InventoryData(ArrayList invList, UUID rootID)
693 {
694 InventoryArray = invList;
695 RootFolderID = rootID;
696 }
697 }
698
699 #region Properties
700
701 public string Login
702 {
703 get { return login; }
704 set { login = value; }
705 }
706
707 public string DST
708 {
709 get { return dst; }
710 set { dst = value; }
711 }
712
713 public string StipendSinceLogin
714 {
715 get { return stipendSinceLogin; }
716 set { stipendSinceLogin = value; }
717 }
718
719 public string Gendered
720 {
721 get { return gendered; }
722 set { gendered = value; }
723 }
724
725 public string EverLoggedIn
726 {
727 get { return everLoggedIn; }
728 set { everLoggedIn = value; }
729 }
730
731 public uint SimPort
732 {
733 get { return simPort; }
734 set { simPort = value; }
735 }
736
737 public uint SimHttpPort
738 {
739 get { return simHttpPort; }
740 set { simHttpPort = value; }
741 }
742
743 public string SimAddress
744 {
745 get { return simAddress; }
746 set { simAddress = value; }
747 }
748
749 public UUID AgentID
750 {
751 get { return agentID; }
752 set { agentID = value; }
753 }
754
755 public UUID SessionID
756 {
757 get { return sessionID; }
758 set { sessionID = value; }
759 }
760
761 public UUID SecureSessionID
762 {
763 get { return secureSessionID; }
764 set { secureSessionID = value; }
765 }
766
767 public Int32 CircuitCode
768 {
769 get { return circuitCode; }
770 set { circuitCode = value; }
771 }
772
773 public uint RegionX
774 {
775 get { return regionX; }
776 set { regionX = value; }
777 }
778
779 public uint RegionY
780 {
781 get { return regionY; }
782 set { regionY = value; }
783 }
784
785 public string SunTexture
786 {
787 get { return sunTexture; }
788 set { sunTexture = value; }
789 }
790
791 public string CloudTexture
792 {
793 get { return cloudTexture; }
794 set { cloudTexture = value; }
795 }
796
797 public string MoonTexture
798 {
799 get { return moonTexture; }
800 set { moonTexture = value; }
801 }
802
803 public string Firstname
804 {
805 get { return firstname; }
806 set { firstname = value; }
807 }
808
809 public string Lastname
810 {
811 get { return lastname; }
812 set { lastname = value; }
813 }
814
815 public string AgentAccess
816 {
817 get { return agentAccess; }
818 set { agentAccess = value; }
819 }
820
821 public string AgentAccessMax
822 {
823 get { return agentAccessMax; }
824 set { agentAccessMax = value; }
825 }
826
827 public string StartLocation
828 {
829 get { return startLocation; }
830 set { startLocation = value; }
831 }
832
833 public string LookAt
834 {
835 get { return lookAt; }
836 set { lookAt = value; }
837 }
838
839 public string SeedCapability
840 {
841 get { return seedCapability; }
842 set { seedCapability = value; }
843 }
844
845 public string ErrorReason
846 {
847 get { return errorReason; }
848 set { errorReason = value; }
849 }
850
851 public string ErrorMessage
852 {
853 get { return errorMessage; }
854 set { errorMessage = value; }
855 }
856
857 public ArrayList InventoryRoot
858 {
859 get { return inventoryRoot; }
860 set { inventoryRoot = value; }
861 }
862
863 public ArrayList InventorySkeleton
864 {
865 get { return agentInventory; }
866 set { agentInventory = value; }
867 }
868
869 public ArrayList InventoryLibrary
870 {
871 get { return inventoryLibrary; }
872 set { inventoryLibrary = value; }
873 }
874
875 public ArrayList InventoryLibraryOwner
876 {
877 get { return inventoryLibraryOwner; }
878 set { inventoryLibraryOwner = value; }
879 }
880
881 public ArrayList InventoryLibRoot
882 {
883 get { return inventoryLibRoot; }
884 set { inventoryLibRoot = value; }
885 }
886
887 public ArrayList ActiveGestures
888 {
889 get { return activeGestures; }
890 set { activeGestures = value; }
891 }
892
893 public string Home
894 {
895 get { return home; }
896 set { home = value; }
897 }
898
899 public string Message
900 {
901 get { return welcomeMessage; }
902 set { welcomeMessage = value; }
903 }
904
905 public BuddyList BuddList
906 {
907 get { return m_buddyList; }
908 set { m_buddyList = value; }
909 }
910
911 #endregion
912
913 public class UserInfo
914 {
915 public string firstname;
916 public string lastname;
917 public ulong homeregionhandle;
918 public Vector3 homepos;
919 public Vector3 homelookat;
920 }
921
922 public class BuddyList
923 {
924 public List<BuddyInfo> Buddies = new List<BuddyInfo>();
925
926 public void AddNewBuddy(BuddyInfo buddy)
927 {
928 if (!Buddies.Contains(buddy))
929 {
930 Buddies.Add(buddy);
931 }
932 }
933
934 public ArrayList ToArray()
935 {
936 ArrayList buddyArray = new ArrayList();
937 foreach (BuddyInfo buddy in Buddies)
938 {
939 buddyArray.Add(buddy.ToHashTable());
940 }
941 return buddyArray;
942 }
943
944 public class BuddyInfo
945 {
946 public int BuddyRightsHave = 1;
947 public int BuddyRightsGiven = 1;
948 public UUID BuddyID;
949
950 public BuddyInfo(string buddyID)
951 {
952 BuddyID = new UUID(buddyID);
953 }
954
955 public BuddyInfo(UUID buddyID)
956 {
957 BuddyID = buddyID;
958 }
959
960 public Hashtable ToHashTable()
961 {
962 Hashtable hTable = new Hashtable();
963 hTable["buddy_rights_has"] = BuddyRightsHave;
964 hTable["buddy_rights_given"] = BuddyRightsGiven;
965 hTable["buddy_id"] = BuddyID.ToString();
966 return hTable;
967 }
968 }
969 }
970 }
971}
diff --git a/OpenSim/Services/LLLoginService/LLLoginService.cs b/OpenSim/Services/LLLoginService/LLLoginService.cs
new file mode 100644
index 0000000..b0e36f1
--- /dev/null
+++ b/OpenSim/Services/LLLoginService/LLLoginService.cs
@@ -0,0 +1,494 @@
1using System;
2using System.Collections.Generic;
3using System.Net;
4using System.Reflection;
5using System.Text.RegularExpressions;
6
7using log4net;
8using Nini.Config;
9using OpenMetaverse;
10
11using OpenSim.Framework;
12using OpenSim.Framework.Capabilities;
13using OpenSim.Framework.Console;
14using OpenSim.Server.Base;
15using OpenSim.Services.Interfaces;
16using GridRegion = OpenSim.Services.Interfaces.GridRegion;
17
18namespace OpenSim.Services.LLLoginService
19{
20 public class LLLoginService : ILoginService
21 {
22 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
23 private static bool Initialized = false;
24
25 private IUserAccountService m_UserAccountService;
26 private IAuthenticationService m_AuthenticationService;
27 private IInventoryService m_InventoryService;
28 private IGridService m_GridService;
29 private IPresenceService m_PresenceService;
30 private ISimulationService m_LocalSimulationService;
31 private ISimulationService m_RemoteSimulationService;
32 private ILibraryService m_LibraryService;
33 private IAvatarService m_AvatarService;
34
35 private string m_DefaultRegionName;
36 private string m_WelcomeMessage;
37 private bool m_RequireInventory;
38 private int m_MinLoginLevel;
39
40 public LLLoginService(IConfigSource config, ISimulationService simService, ILibraryService libraryService)
41 {
42 IConfig serverConfig = config.Configs["LoginService"];
43 if (serverConfig == null)
44 throw new Exception(String.Format("No section LoginService in config file"));
45
46 string accountService = serverConfig.GetString("UserAccountService", String.Empty);
47 string authService = serverConfig.GetString("AuthenticationService", String.Empty);
48 string invService = serverConfig.GetString("InventoryService", String.Empty);
49 string gridService = serverConfig.GetString("GridService", String.Empty);
50 string presenceService = serverConfig.GetString("PresenceService", String.Empty);
51 string libService = serverConfig.GetString("LibraryService", String.Empty);
52 string avatarService = serverConfig.GetString("AvatarService", String.Empty);
53 string simulationService = serverConfig.GetString("SimulationService", String.Empty);
54
55 m_DefaultRegionName = serverConfig.GetString("DefaultRegion", String.Empty);
56 m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
57 m_RequireInventory = serverConfig.GetBoolean("RequireInventory", true);
58
59 // These are required; the others aren't
60 if (accountService == string.Empty || authService == string.Empty)
61 throw new Exception("LoginService is missing service specifications");
62
63 Object[] args = new Object[] { config };
64 m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
65 m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
66 m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(invService, args);
67 if (gridService != string.Empty)
68 m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
69 if (presenceService != string.Empty)
70 m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
71 if (avatarService != string.Empty)
72 m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarService, args);
73 if (simulationService != string.Empty)
74 m_RemoteSimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
75 //
76 // deal with the services given as argument
77 //
78 m_LocalSimulationService = simService;
79 if (libraryService != null)
80 {
81 m_log.DebugFormat("[LLOGIN SERVICE]: Using LibraryService given as argument");
82 m_LibraryService = libraryService;
83 }
84 else if (libService != string.Empty)
85 {
86 m_log.DebugFormat("[LLOGIN SERVICE]: Using instantiated LibraryService");
87 m_LibraryService = ServerUtils.LoadPlugin<ILibraryService>(libService, args);
88 }
89
90 if (!Initialized)
91 {
92 Initialized = true;
93 RegisterCommands();
94 }
95
96 m_log.DebugFormat("[LLOGIN SERVICE]: Starting...");
97
98 }
99
100 public LLLoginService(IConfigSource config) : this(config, null, null)
101 {
102 }
103
104 public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, IPEndPoint clientIP)
105 {
106 bool success = false;
107 UUID session = UUID.Random();
108
109 try
110 {
111 //
112 // Get the account and check that it exists
113 //
114 UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
115 if (account == null)
116 {
117 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found");
118 return LLFailedLoginResponse.UserProblem;
119 }
120
121 if (account.UserLevel < m_MinLoginLevel)
122 {
123 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: login is blocked for user level {0}", account.UserLevel);
124 return LLFailedLoginResponse.LoginBlockedProblem;
125 }
126
127 //
128 // Authenticate this user
129 //
130 if (!passwd.StartsWith("$1$"))
131 passwd = "$1$" + Util.Md5Hash(passwd);
132 passwd = passwd.Remove(0, 3); //remove $1$
133 string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
134 UUID secureSession = UUID.Zero;
135 if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
136 {
137 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: authentication failed");
138 return LLFailedLoginResponse.UserProblem;
139 }
140
141 //
142 // Get the user's inventory
143 //
144 if (m_RequireInventory && m_InventoryService == null)
145 {
146 m_log.WarnFormat("[LLOGIN SERVICE]: Login failed, reason: inventory service not set up");
147 return LLFailedLoginResponse.InventoryProblem;
148 }
149 List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
150 if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
151 {
152 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: unable to retrieve user inventory");
153 return LLFailedLoginResponse.InventoryProblem;
154 }
155
156 //
157 // Login the presence
158 //
159 PresenceInfo presence = null;
160 GridRegion home = null;
161 if (m_PresenceService != null)
162 {
163 success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);
164 if (!success)
165 {
166 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: could not login presence");
167 return LLFailedLoginResponse.GridProblem;
168 }
169
170 // Get the updated presence info
171 presence = m_PresenceService.GetAgent(session);
172
173 // Get the home region
174 if ((presence.HomeRegionID != UUID.Zero) && m_GridService != null)
175 {
176 home = m_GridService.GetRegionByUUID(account.ScopeID, presence.HomeRegionID);
177 }
178 }
179
180 //
181 // Find the destination region/grid
182 //
183 string where = string.Empty;
184 Vector3 position = Vector3.Zero;
185 Vector3 lookAt = Vector3.Zero;
186 GridRegion destination = FindDestination(account, presence, session, startLocation, out where, out position, out lookAt);
187 if (destination == null)
188 {
189 m_PresenceService.LogoutAgent(session, presence.Position, presence.LookAt);
190 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: destination not found");
191 return LLFailedLoginResponse.GridProblem;
192 }
193
194 //
195 // Get the avatar
196 //
197 AvatarData avatar = null;
198 if (m_AvatarService != null)
199 {
200 avatar = m_AvatarService.GetAvatar(account.PrincipalID);
201 }
202
203 //
204 // Instantiate/get the simulation interface and launch an agent at the destination
205 //
206 ISimulationService simConnector = null;
207 string reason = string.Empty;
208 uint circuitCode = 0;
209 AgentCircuitData aCircuit = null;
210 Object[] args = new Object[] { destination };
211 // HG standalones have both a localSimulatonDll and a remoteSimulationDll
212 // non-HG standalones have just a localSimulationDll
213 // independent login servers have just a remoteSimulationDll
214 if (!startLocation.Contains("@") && (m_LocalSimulationService != null))
215 simConnector = m_LocalSimulationService;
216 else if (m_RemoteSimulationService != null)
217 simConnector = m_RemoteSimulationService;
218 if (simConnector != null)
219 {
220 circuitCode = (uint)Util.RandomClass.Next(); ;
221 aCircuit = LaunchAgent(simConnector, destination, account, avatar, session, secureSession, circuitCode, position, out reason);
222 }
223 if (aCircuit == null)
224 {
225 // Try the fallback regions
226 List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
227 if (fallbacks != null)
228 {
229 foreach (GridRegion r in fallbacks)
230 {
231 aCircuit = LaunchAgent(simConnector, r, account, avatar, session, secureSession, circuitCode, position, out reason);
232 if (aCircuit != null)
233 {
234 where = "safe";
235 destination = r;
236 break;
237 }
238 }
239 }
240
241 if (aCircuit == null)
242 {
243 // we tried...
244 m_PresenceService.LogoutAgent(session, presence.Position, presence.LookAt);
245 m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: {0}", reason);
246 return LLFailedLoginResponse.AuthorizationProblem;
247 }
248 }
249
250 // TODO: Get Friends list...
251
252 //
253 // Finally, fill out the response and return it
254 //
255 LLLoginResponse response = new LLLoginResponse(account, aCircuit, presence, destination, inventorySkel, m_LibraryService,
256 where, startLocation, position, lookAt, m_WelcomeMessage, home, clientIP);
257
258 return response;
259 }
260 catch (Exception e)
261 {
262 m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2}", firstName, lastName, e.StackTrace);
263 if (m_PresenceService != null)
264 m_PresenceService.LogoutAgent(session, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
265 return LLFailedLoginResponse.InternalError;
266 }
267 }
268
269 private GridRegion FindDestination(UserAccount account, PresenceInfo pinfo, UUID sessionID, string startLocation, out string where, out Vector3 position, out Vector3 lookAt)
270 {
271 m_log.DebugFormat("[LLOGIN SERVICE]: FindDestination for start location {0}", startLocation);
272
273 where = "home";
274 position = new Vector3(128, 128, 0);
275 lookAt = new Vector3(0, 1, 0);
276
277 if (m_GridService == null)
278 return null;
279
280 if (startLocation.Equals("home"))
281 {
282 // logging into home region
283 if (pinfo == null)
284 return null;
285
286 GridRegion region = null;
287
288 if (pinfo.HomeRegionID.Equals(UUID.Zero))
289 {
290 List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.ScopeID);
291 if (defaults != null && defaults.Count > 0)
292 {
293 region = defaults[0];
294 where = "safe";
295 }
296 else
297 m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a home set and this grid does not have default locations.",
298 account.FirstName, account.LastName);
299 }
300 else
301 region = m_GridService.GetRegionByUUID(account.ScopeID, pinfo.HomeRegionID);
302
303 return region;
304 }
305 else if (startLocation.Equals("last"))
306 {
307 // logging into last visited region
308 where = "last";
309
310 if (pinfo == null)
311 return null;
312
313 GridRegion region = null;
314
315 if (pinfo.RegionID.Equals(UUID.Zero))
316 {
317 List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.ScopeID);
318 if (defaults != null && defaults.Count > 0)
319 {
320 region = defaults[0];
321 where = "safe";
322 }
323 }
324 else
325 {
326 region = m_GridService.GetRegionByUUID(account.ScopeID, pinfo.RegionID);
327 position = pinfo.Position;
328 lookAt = pinfo.LookAt;
329 }
330 return region;
331
332 }
333 else
334 {
335 // free uri form
336 // e.g. New Moon&135&46 New Moon@osgrid.org:8002&153&34
337 where = "url";
338 Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
339 Match uriMatch = reURI.Match(startLocation);
340 if (uriMatch == null)
341 {
342 m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, but can't process it", startLocation);
343 return null;
344 }
345 else
346 {
347 position = new Vector3(float.Parse(uriMatch.Groups["x"].Value),
348 float.Parse(uriMatch.Groups["y"].Value),
349 float.Parse(uriMatch.Groups["z"].Value));
350
351 string regionName = uriMatch.Groups["region"].ToString();
352 if (regionName != null)
353 {
354 if (!regionName.Contains("@"))
355 {
356
357 List<GridRegion> regions = m_GridService.GetRegionsByName(account.ScopeID, regionName, 1);
358 if ((regions == null) || (regions != null && regions.Count == 0))
359 {
360 m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName);
361 regions = m_GridService.GetDefaultRegions(UUID.Zero);
362 if (regions != null && regions.Count > 0)
363 {
364 where = "safe";
365 return regions[0];
366 }
367 else
368 {
369 m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not provide default regions.", startLocation);
370 return null;
371 }
372 }
373 return regions[0];
374 }
375 else
376 {
377 string[] parts = regionName.Split(new char[] { '@' });
378 if (parts.Length < 2)
379 {
380 m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName);
381 return null;
382 }
383 // Valid specification of a remote grid
384 regionName = parts[0];
385 string domainLocator = parts[1];
386 parts = domainLocator.Split(new char[] {':'});
387 string domainName = parts[0];
388 uint port = 0;
389 if (parts.Length > 1)
390 UInt32.TryParse(parts[1], out port);
391 GridRegion region = new GridRegion();
392 region.ExternalHostName = domainName;
393 region.HttpPort = port;
394 region.RegionName = regionName;
395 return region;
396 }
397 }
398 else
399 {
400 List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.ScopeID);
401 if (defaults != null && defaults.Count > 0)
402 {
403 where = "safe";
404 return defaults[0];
405 }
406 else
407 return null;
408 }
409 }
410 //response.LookAt = "[r0,r1,r0]";
411 //// can be: last, home, safe, url
412 //response.StartLocation = "url";
413
414 }
415
416 }
417
418 private AgentCircuitData LaunchAgent(ISimulationService simConnector, GridRegion region, UserAccount account,
419 AvatarData avatar, UUID session, UUID secureSession, uint circuit, Vector3 position, out string reason)
420 {
421 reason = string.Empty;
422 AgentCircuitData aCircuit = new AgentCircuitData();
423
424 aCircuit.AgentID = account.PrincipalID;
425 if (avatar != null)
426 aCircuit.Appearance = avatar.ToAvatarAppearance(account.PrincipalID);
427 else
428 aCircuit.Appearance = new AvatarAppearance(account.PrincipalID);
429
430 //aCircuit.BaseFolder = irrelevant
431 aCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
432 aCircuit.child = false; // the first login agent is root
433 aCircuit.ChildrenCapSeeds = new Dictionary<ulong, string>();
434 aCircuit.circuitcode = circuit;
435 aCircuit.firstname = account.FirstName;
436 //aCircuit.InventoryFolder = irrelevant
437 aCircuit.lastname = account.LastName;
438 aCircuit.SecureSessionID = secureSession;
439 aCircuit.SessionID = session;
440 aCircuit.startpos = position;
441
442 if (simConnector.CreateAgent(region, aCircuit, 0, out reason))
443 return aCircuit;
444
445 return null;
446
447 }
448
449 #region Console Commands
450 private void RegisterCommands()
451 {
452 //MainConsole.Instance.Commands.AddCommand
453 MainConsole.Instance.Commands.AddCommand("loginservice", false, "login level",
454 "login level <level>",
455 "Set the minimum user level to log in", HandleLoginCommand);
456
457 MainConsole.Instance.Commands.AddCommand("loginservice", false, "login reset",
458 "login reset",
459 "Reset the login level to allow all users",
460 HandleLoginCommand);
461
462 MainConsole.Instance.Commands.AddCommand("loginservice", false, "login text",
463 "login text <text>",
464 "Set the text users will see on login", HandleLoginCommand);
465
466 }
467
468 private void HandleLoginCommand(string module, string[] cmd)
469 {
470 string subcommand = cmd[1];
471
472 switch (subcommand)
473 {
474 case "level":
475 // Set the minimum level to allow login
476 // Useful to allow grid update without worrying about users.
477 // or fixing critical issues
478 //
479 if (cmd.Length > 2)
480 Int32.TryParse(cmd[2], out m_MinLoginLevel);
481 break;
482 case "reset":
483 m_MinLoginLevel = 0;
484 break;
485 case "text":
486 if (cmd.Length > 2)
487 m_WelcomeMessage = cmd[2];
488 break;
489 }
490 }
491 }
492
493 #endregion
494}
diff --git a/OpenSim/Services/PresenceService/PresenceService.cs b/OpenSim/Services/PresenceService/PresenceService.cs
index 2157462..350eac8 100644
--- a/OpenSim/Services/PresenceService/PresenceService.cs
+++ b/OpenSim/Services/PresenceService/PresenceService.cs
@@ -41,27 +41,177 @@ namespace OpenSim.Services.PresenceService
41{ 41{
42 public class PresenceService : PresenceServiceBase, IPresenceService 42 public class PresenceService : PresenceServiceBase, IPresenceService
43 { 43 {
44// private static readonly ILog m_log = 44 private static readonly ILog m_log =
45// LogManager.GetLogger( 45 LogManager.GetLogger(
46// MethodBase.GetCurrentMethod().DeclaringType); 46 MethodBase.GetCurrentMethod().DeclaringType);
47 47
48 public PresenceService(IConfigSource config) 48 public PresenceService(IConfigSource config)
49 : base(config) 49 : base(config)
50 { 50 {
51 m_log.Debug("[PRESENCE SERVICE]: Starting presence service");
51 } 52 }
52 53
53 public bool Report(PresenceInfo presence) 54 public bool LoginAgent(string userID, UUID sessionID,
55 UUID secureSessionID)
54 { 56 {
55 PresenceData p = new PresenceData(); 57 m_Database.Prune(userID);
56 p.Data = new Dictionary<string, string>();
57 58
58 p.UUID = presence.PrincipalID; 59 PresenceData[] d = m_Database.Get("UserID", userID);
59 p.currentRegion = presence.RegionID;
60 60
61 foreach (KeyValuePair<string, string> kvp in presence.Data) 61 PresenceData data = new PresenceData();
62 p.Data[kvp.Key] = kvp.Value;
63 62
64 return false; 63 data.UserID = userID;
64 data.RegionID = UUID.Zero;
65 data.SessionID = sessionID;
66 data.Data = new Dictionary<string, string>();
67 data.Data["SecureSessionID"] = secureSessionID.ToString();
68 data.Data["Online"] = "true";
69 data.Data["Login"] = Util.UnixTimeSinceEpoch().ToString();
70 if (d != null && d.Length > 0)
71 {
72 data.Data["HomeRegionID"] = d[0].Data["HomeRegionID"];
73 data.Data["HomePosition"] = d[0].Data["HomePosition"];
74 data.Data["HomeLookAt"] = d[0].Data["HomeLookAt"];
75 }
76 else
77 {
78 data.Data["HomeRegionID"] = UUID.Zero.ToString();
79 data.Data["HomePosition"] = new Vector3(128, 128, 0).ToString();
80 data.Data["HomeLookAt"] = new Vector3(0, 1, 0).ToString();
81 }
82
83 m_Database.Store(data);
84
85 m_log.DebugFormat("[PRESENCE SERVICE]: LoginAgent {0} with session {1} and ssession {2}",
86 userID, sessionID, secureSessionID);
87 return true;
88 }
89
90 public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookat)
91 {
92 PresenceData data = m_Database.Get(sessionID);
93 if (data == null)
94 return false;
95
96 PresenceData[] d = m_Database.Get("UserID", data.UserID);
97
98 m_log.DebugFormat("[PRESENCE SERVICE]: LogoutAgent {0} with {1} sessions currently present", data.UserID, d.Length);
99 if (d.Length > 1)
100 {
101 m_Database.Delete("UserID", data.UserID);
102 }
103
104 data.Data["Online"] = "false";
105 data.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString();
106 data.Data["Position"] = position.ToString();
107 data.Data["LookAt"] = lookat.ToString();
108
109 m_Database.Store(data);
110
111 return true;
112 }
113
114 public bool LogoutRegionAgents(UUID regionID)
115 {
116 m_Database.LogoutRegionAgents(regionID);
117
118 return true;
119 }
120
121
122 public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt)
123 {
124 m_log.DebugFormat("[PRESENCE SERVICE]: ReportAgent with session {0} in region {1}", sessionID, regionID);
125 try
126 {
127 PresenceData pdata = m_Database.Get(sessionID);
128 if (pdata == null)
129 return false;
130 if (pdata.Data == null)
131 return false;
132
133 if (!pdata.Data.ContainsKey("Online") || (pdata.Data.ContainsKey("Online") && pdata.Data["Online"] == "false"))
134 {
135 m_log.WarnFormat("[PRESENCE SERVICE]: Someone tried to report presence of an agent who's not online");
136 return false;
137 }
138
139 return m_Database.ReportAgent(sessionID, regionID,
140 position.ToString(), lookAt.ToString());
141 }
142 catch (Exception e)
143 {
144 m_log.DebugFormat("[PRESENCE SERVICE]: ReportAgent threw exception {0}", e.StackTrace);
145 return false;
146 }
147 }
148
149 public PresenceInfo GetAgent(UUID sessionID)
150 {
151 PresenceInfo ret = new PresenceInfo();
152
153 PresenceData data = m_Database.Get(sessionID);
154 if (data == null)
155 return null;
156
157 ret.UserID = data.UserID;
158 ret.RegionID = data.RegionID;
159 if (data.Data.ContainsKey("Online"))
160 ret.Online = bool.Parse(data.Data["Online"]);
161 if (data.Data.ContainsKey("Login"))
162 ret.Login = Util.ToDateTime(Convert.ToInt32(data.Data["Login"]));
163 if (data.Data.ContainsKey("Logout"))
164 ret.Logout = Util.ToDateTime(Convert.ToInt32(data.Data["Logout"]));
165 if (data.Data.ContainsKey("Position"))
166 ret.Position = Vector3.Parse(data.Data["Position"]);
167 if (data.Data.ContainsKey("LookAt"))
168 ret.LookAt = Vector3.Parse(data.Data["LookAt"]);
169 if (data.Data.ContainsKey("HomeRegionID"))
170 ret.HomeRegionID = new UUID(data.Data["HomeRegionID"]);
171 if (data.Data.ContainsKey("HomePosition"))
172 ret.HomePosition = Vector3.Parse(data.Data["HomePosition"]);
173 if (data.Data.ContainsKey("HomeLookAt"))
174 ret.HomeLookAt = Vector3.Parse(data.Data["HomeLookAt"]);
175
176 return ret;
177 }
178
179 public PresenceInfo[] GetAgents(string[] userIDs)
180 {
181 List<PresenceInfo> info = new List<PresenceInfo>();
182
183 foreach (string userIDStr in userIDs)
184 {
185 PresenceData[] data = m_Database.Get("UserID",
186 userIDStr);
187
188 foreach (PresenceData d in data)
189 {
190 PresenceInfo ret = new PresenceInfo();
191
192 ret.UserID = d.UserID;
193 ret.RegionID = d.RegionID;
194 ret.Online = bool.Parse(d.Data["Online"]);
195 ret.Login = Util.ToDateTime(Convert.ToInt32(
196 d.Data["Login"]));
197 ret.Logout = Util.ToDateTime(Convert.ToInt32(
198 d.Data["Logout"]));
199 ret.Position = Vector3.Parse(d.Data["Position"]);
200 ret.LookAt = Vector3.Parse(d.Data["LookAt"]);
201 ret.HomeRegionID = new UUID(d.Data["HomeRegionID"]);
202 ret.HomePosition = Vector3.Parse(d.Data["HomePosition"]);
203 ret.HomeLookAt = Vector3.Parse(d.Data["HomeLookAt"]);
204
205 info.Add(ret);
206 }
207 }
208
209 return info.ToArray();
210 }
211
212 public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
213 {
214 return m_Database.SetHomeLocation(userID, regionID, position, lookAt);
65 } 215 }
66 } 216 }
67} 217}
diff --git a/OpenSim/Services/PresenceService/PresenceServiceBase.cs b/OpenSim/Services/PresenceService/PresenceServiceBase.cs
index 60a246b..a4adb2f 100644
--- a/OpenSim/Services/PresenceService/PresenceServiceBase.cs
+++ b/OpenSim/Services/PresenceService/PresenceServiceBase.cs
@@ -44,7 +44,7 @@ namespace OpenSim.Services.PresenceService
44 { 44 {
45 string dllName = String.Empty; 45 string dllName = String.Empty;
46 string connString = String.Empty; 46 string connString = String.Empty;
47 string realm = "agents"; 47 string realm = "Presence";
48 48
49 // 49 //
50 // Try reading the [DatabaseService] section, if it exists 50 // Try reading the [DatabaseService] section, if it exists
@@ -77,7 +77,7 @@ namespace OpenSim.Services.PresenceService
77 77
78 m_Database = LoadPlugin<IPresenceData>(dllName, new Object[] { connString, realm }); 78 m_Database = LoadPlugin<IPresenceData>(dllName, new Object[] { connString, realm });
79 if (m_Database == null) 79 if (m_Database == null)
80 throw new Exception("Could not find a storage interface in the given module"); 80 throw new Exception("Could not find a storage interface in the given module " + dllName);
81 81
82 } 82 }
83 } 83 }
diff --git a/OpenSim/Services/UserAccountService/UserAccountService.cs b/OpenSim/Services/UserAccountService/UserAccountService.cs
new file mode 100644
index 0000000..ffb9cca
--- /dev/null
+++ b/OpenSim/Services/UserAccountService/UserAccountService.cs
@@ -0,0 +1,359 @@
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 Nini.Config;
32using OpenSim.Data;
33using OpenSim.Services.Interfaces;
34using OpenSim.Framework.Console;
35using GridRegion = OpenSim.Services.Interfaces.GridRegion;
36
37using OpenMetaverse;
38using log4net;
39
40namespace OpenSim.Services.UserAccountService
41{
42 public class UserAccountService : UserAccountServiceBase, IUserAccountService
43 {
44 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
45 private static UserAccountService m_RootInstance;
46
47 protected IGridService m_GridService;
48 protected IAuthenticationService m_AuthenticationService;
49 protected IPresenceService m_PresenceService;
50 protected IInventoryService m_InventoryService;
51
52 public UserAccountService(IConfigSource config)
53 : base(config)
54 {
55 IConfig userConfig = config.Configs["UserAccountService"];
56 if (userConfig == null)
57 throw new Exception("No UserAccountService configuration");
58
59 // In case there are several instances of this class in the same process,
60 // the console commands are only registered for the root instance
61 if (m_RootInstance == null)
62 {
63 m_RootInstance = this;
64 string gridServiceDll = userConfig.GetString("GridService", string.Empty);
65 if (gridServiceDll != string.Empty)
66 m_GridService = LoadPlugin<IGridService>(gridServiceDll, new Object[] { config });
67
68 string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty);
69 if (authServiceDll != string.Empty)
70 m_AuthenticationService = LoadPlugin<IAuthenticationService>(authServiceDll, new Object[] { config });
71
72 string presenceServiceDll = userConfig.GetString("PresenceService", string.Empty);
73 if (presenceServiceDll != string.Empty)
74 m_PresenceService = LoadPlugin<IPresenceService>(presenceServiceDll, new Object[] { config });
75
76 string invServiceDll = userConfig.GetString("InventoryService", string.Empty);
77 if (invServiceDll != string.Empty)
78 m_InventoryService = LoadPlugin<IInventoryService>(invServiceDll, new Object[] { config });
79
80 MainConsole.Instance.Commands.AddCommand("UserService", false,
81 "create user",
82 "create user [<first> [<last> [<pass> [<email>]]]]",
83 "Create a new user", HandleCreateUser);
84 MainConsole.Instance.Commands.AddCommand("UserService", false, "reset user password",
85 "reset user password [<first> [<last> [<password>]]]",
86 "Reset a user password", HandleResetUserPassword);
87
88 }
89
90 }
91
92 #region IUserAccountService
93
94 public UserAccount GetUserAccount(UUID scopeID, string firstName,
95 string lastName)
96 {
97 UserAccountData[] d;
98
99 if (scopeID != UUID.Zero)
100 {
101 d = m_Database.Get(
102 new string[] { "ScopeID", "FirstName", "LastName" },
103 new string[] { scopeID.ToString(), firstName, lastName });
104 }
105 else
106 {
107 d = m_Database.Get(
108 new string[] { "FirstName", "LastName" },
109 new string[] { firstName, lastName });
110 }
111
112 if (d.Length < 1)
113 return null;
114
115 return MakeUserAccount(d[0]);
116 }
117
118 private UserAccount MakeUserAccount(UserAccountData d)
119 {
120 UserAccount u = new UserAccount();
121 u.FirstName = d.FirstName;
122 u.LastName = d.LastName;
123 u.PrincipalID = d.PrincipalID;
124 u.ScopeID = d.ScopeID;
125 if (d.Data.ContainsKey("Email") && d.Data["Email"] != null)
126 u.Email = d.Data["Email"].ToString();
127 else
128 u.Email = string.Empty;
129 u.Created = Convert.ToInt32(d.Data["Created"].ToString());
130 if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null)
131 u.UserTitle = d.Data["UserTitle"].ToString();
132 else
133 u.UserTitle = string.Empty;
134
135 if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null)
136 {
137 string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' });
138 u.ServiceURLs = new Dictionary<string, object>();
139
140 foreach (string url in URLs)
141 {
142 string[] parts = url.Split(new char[] { '=' });
143
144 if (parts.Length != 2)
145 continue;
146
147 string name = System.Web.HttpUtility.UrlDecode(parts[0]);
148 string val = System.Web.HttpUtility.UrlDecode(parts[1]);
149
150 u.ServiceURLs[name] = val;
151 }
152 }
153 else
154 u.ServiceURLs = new Dictionary<string, object>();
155
156 return u;
157 }
158
159 public UserAccount GetUserAccount(UUID scopeID, string email)
160 {
161 UserAccountData[] d;
162
163 if (scopeID != UUID.Zero)
164 {
165 d = m_Database.Get(
166 new string[] { "ScopeID", "Email" },
167 new string[] { scopeID.ToString(), email });
168 }
169 else
170 {
171 d = m_Database.Get(
172 new string[] { "Email" },
173 new string[] { email });
174 }
175
176 if (d.Length < 1)
177 return null;
178
179 return MakeUserAccount(d[0]);
180 }
181
182 public UserAccount GetUserAccount(UUID scopeID, UUID principalID)
183 {
184 UserAccountData[] d;
185
186 if (scopeID != UUID.Zero)
187 {
188 d = m_Database.Get(
189 new string[] { "ScopeID", "PrincipalID" },
190 new string[] { scopeID.ToString(), principalID.ToString() });
191 }
192 else
193 {
194 d = m_Database.Get(
195 new string[] { "PrincipalID" },
196 new string[] { principalID.ToString() });
197 }
198
199 if (d.Length < 1)
200 return null;
201
202 return MakeUserAccount(d[0]);
203 }
204
205 public bool StoreUserAccount(UserAccount data)
206 {
207 UserAccountData d = new UserAccountData();
208
209 d.FirstName = data.FirstName;
210 d.LastName = data.LastName;
211 d.PrincipalID = data.PrincipalID;
212 d.ScopeID = data.ScopeID;
213 d.Data = new Dictionary<string, string>();
214 d.Data["Email"] = data.Email;
215 d.Data["Created"] = data.Created.ToString();
216
217 List<string> parts = new List<string>();
218
219 foreach (KeyValuePair<string, object> kvp in data.ServiceURLs)
220 {
221 string key = System.Web.HttpUtility.UrlEncode(kvp.Key);
222 string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
223 parts.Add(key + "=" + val);
224 }
225
226 d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray());
227
228 return m_Database.Store(d);
229 }
230
231 public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
232 {
233 UserAccountData[] d = m_Database.GetUsers(scopeID, query);
234
235 if (d == null)
236 return new List<UserAccount>();
237
238 List<UserAccount> ret = new List<UserAccount>();
239
240 foreach (UserAccountData data in d)
241 ret.Add(MakeUserAccount(data));
242
243 return ret;
244 }
245
246 #endregion
247
248 #region Console commands
249 /// <summary>
250 /// Create a new user
251 /// </summary>
252 /// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param>
253 protected void HandleCreateUser(string module, string[] cmdparams)
254 {
255 string firstName;
256 string lastName;
257 string password;
258 string email;
259
260 if (cmdparams.Length < 3)
261 firstName = MainConsole.Instance.CmdPrompt("First name", "Default");
262 else firstName = cmdparams[2];
263
264 if (cmdparams.Length < 4)
265 lastName = MainConsole.Instance.CmdPrompt("Last name", "User");
266 else lastName = cmdparams[3];
267
268 if (cmdparams.Length < 5)
269 password = MainConsole.Instance.PasswdPrompt("Password");
270 else password = cmdparams[4];
271
272 if (cmdparams.Length < 6)
273 email = MainConsole.Instance.CmdPrompt("Email", "");
274 else email = cmdparams[5];
275
276 UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
277 if (null == account)
278 {
279 account = new UserAccount(UUID.Zero, firstName, lastName, email);
280 if (StoreUserAccount(account))
281 {
282 bool success = false;
283 if (m_AuthenticationService != null)
284 success = m_AuthenticationService.SetPassword(account.PrincipalID, password);
285 if (!success)
286 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.",
287 firstName, lastName);
288
289 GridRegion home = null;
290 if (m_GridService != null)
291 {
292 List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero);
293 if (defaultRegions != null && defaultRegions.Count >= 1)
294 home = defaultRegions[0];
295
296 if (m_PresenceService != null && home != null)
297 m_PresenceService.SetHomeLocation(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
298 else
299 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.",
300 firstName, lastName);
301
302 }
303 else
304 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.",
305 firstName, lastName);
306
307 if (m_InventoryService != null)
308 success = m_InventoryService.CreateUserInventory(account.PrincipalID);
309 if (!success)
310 m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.",
311 firstName, lastName);
312
313
314 m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", firstName, lastName);
315 }
316 }
317 else
318 {
319 m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName);
320 }
321
322 }
323
324 protected void HandleResetUserPassword(string module, string[] cmdparams)
325 {
326 string firstName;
327 string lastName;
328 string newPassword;
329
330 if (cmdparams.Length < 4)
331 firstName = MainConsole.Instance.CmdPrompt("First name");
332 else firstName = cmdparams[3];
333
334 if (cmdparams.Length < 5)
335 lastName = MainConsole.Instance.CmdPrompt("Last name");
336 else lastName = cmdparams[4];
337
338 if (cmdparams.Length < 6)
339 newPassword = MainConsole.Instance.PasswdPrompt("New password");
340 else newPassword = cmdparams[5];
341
342 UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
343 if (account == null)
344 m_log.ErrorFormat("[USER ACCOUNT SERVICE]: No such user");
345
346 bool success = false;
347 if (m_AuthenticationService != null)
348 success = m_AuthenticationService.SetPassword(account.PrincipalID, newPassword);
349 if (!success)
350 m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Unable to reset password for account {0} {1}.",
351 firstName, lastName);
352 else
353 m_log.InfoFormat("[USER ACCOUNT SERVICE]: Password reset for user {0} {1}", firstName, lastName);
354 }
355
356 #endregion
357
358 }
359}
diff --git a/OpenSim/Services/UserService/UserServiceBase.cs b/OpenSim/Services/UserAccountService/UserAccountServiceBase.cs
index fea8b01..c1a7b76 100644
--- a/OpenSim/Services/UserService/UserServiceBase.cs
+++ b/OpenSim/Services/UserAccountService/UserAccountServiceBase.cs
@@ -40,20 +40,29 @@ namespace OpenSim.Services.UserAccountService
40 40
41 public UserAccountServiceBase(IConfigSource config) : base(config) 41 public UserAccountServiceBase(IConfigSource config) : base(config)
42 { 42 {
43 string dllName = String.Empty;
44 string connString = String.Empty;
45 string realm = "UserAccounts";
46
47 IConfig dbConfig = config.Configs["DatabaseService"];
48 if (dbConfig != null)
49 {
50 dllName = dbConfig.GetString("StorageProvider", String.Empty);
51 connString = dbConfig.GetString("ConnectionString", String.Empty);
52 }
53
43 IConfig userConfig = config.Configs["UserAccountService"]; 54 IConfig userConfig = config.Configs["UserAccountService"];
44 if (userConfig == null) 55 if (userConfig == null)
45 throw new Exception("No UserAccountService configuration"); 56 throw new Exception("No UserAccountService configuration");
46 57
47 string dllName = userConfig.GetString("StorageProvider", 58 dllName = userConfig.GetString("StorageProvider", dllName);
48 String.Empty);
49 59
50 if (dllName == String.Empty) 60 if (dllName == String.Empty)
51 throw new Exception("No StorageProvider configured"); 61 throw new Exception("No StorageProvider configured");
52 62
53 string connString = userConfig.GetString("ConnectionString", 63 connString = userConfig.GetString("ConnectionString", connString);
54 String.Empty);
55 64
56 string realm = userConfig.GetString("Realm", "users"); 65 realm = userConfig.GetString("Realm", realm);
57 66
58 m_Database = LoadPlugin<IUserAccountData>(dllName, new Object[] {connString, realm}); 67 m_Database = LoadPlugin<IUserAccountData>(dllName, new Object[] {connString, realm});
59 68