clockwerk-opensim – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 vero 1 /*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27  
28 using System;
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Globalization;
32 using System.IO;
33 using System.Xml;
34 using System.Net;
35 using System.Reflection;
36 using System.Timers;
37 using System.Threading;
38 using log4net;
39 using Nini.Config;
40 using Nwc.XmlRpc;
41 using OpenMetaverse;
42 using OpenSim;
43 using OpenSim.Framework;
44 using OpenSim.Framework.Communications;
45 using OpenSim.Framework.Console;
46 using OpenSim.Framework.Servers;
47 using OpenSim.Framework.Servers.HttpServer;
48 using OpenSim.Region.CoreModules.World.Terrain;
49 using OpenSim.Region.Framework.Interfaces;
50 using OpenSim.Region.Framework.Scenes;
51 using OpenSim.Services.Interfaces;
52 using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
53 using GridRegion = OpenSim.Services.Interfaces.GridRegion;
54 using PermissionMask = OpenSim.Framework.PermissionMask;
55 using RegionInfo = OpenSim.Framework.RegionInfo;
56  
57 namespace OpenSim.ApplicationPlugins.RemoteController
58 {
59 public class RemoteAdminPlugin : IApplicationPlugin
60 {
61 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
62  
63 private static bool m_defaultAvatarsLoaded = false;
64 private static Object m_requestLock = new Object();
65 private static Object m_saveOarLock = new Object();
66  
67 private OpenSimBase m_application;
68 private IHttpServer m_httpServer;
69 private IConfig m_config;
70 private IConfigSource m_configSource;
71 private string m_requiredPassword = String.Empty;
72 private HashSet<string> m_accessIP;
73  
74 private string m_name = "RemoteAdminPlugin";
75 private string m_version = "0.0";
76  
77 public string Version
78 {
79 get { return m_version; }
80 }
81  
82 public string Name
83 {
84 get { return m_name; }
85 }
86  
87 public void Initialise()
88 {
89 m_log.Error("[RADMIN]: " + Name + " cannot be default-initialized!");
90 throw new PluginNotInitialisedException(Name);
91 }
92  
93 public void Initialise(OpenSimBase openSim)
94 {
95 m_configSource = openSim.ConfigSource.Source;
96 try
97 {
98 if (m_configSource.Configs["RemoteAdmin"] == null ||
99 !m_configSource.Configs["RemoteAdmin"].GetBoolean("enabled", false))
100 {
101 // No config or disabled
102 }
103 else
104 {
105 m_config = m_configSource.Configs["RemoteAdmin"];
106 m_log.Debug("[RADMIN]: Remote Admin Plugin Enabled");
107 m_requiredPassword = m_config.GetString("access_password", String.Empty);
108 int port = m_config.GetInt("port", 0);
109  
110 string accessIP = m_config.GetString("access_ip_addresses", String.Empty);
111 m_accessIP = new HashSet<string>();
112 if (accessIP != String.Empty)
113 {
114 string[] ips = accessIP.Split(new char[] { ',' });
115 foreach (string ip in ips)
116 {
117 string current = ip.Trim();
118  
119 if (current != String.Empty)
120 m_accessIP.Add(current);
121 }
122 }
123  
124 m_application = openSim;
125 string bind_ip_address = m_config.GetString("bind_ip_address", "0.0.0.0");
126 IPAddress ipaddr = IPAddress.Parse(bind_ip_address);
127 m_httpServer = MainServer.GetHttpServer((uint)port,ipaddr);
128  
129 Dictionary<string, XmlRpcMethod> availableMethods = new Dictionary<string, XmlRpcMethod>();
130 availableMethods["admin_create_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateRegionMethod);
131 availableMethods["admin_delete_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcDeleteRegionMethod);
132 availableMethods["admin_close_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCloseRegionMethod);
133 availableMethods["admin_modify_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcModifyRegionMethod);
134 availableMethods["admin_region_query"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRegionQueryMethod);
135 availableMethods["admin_shutdown"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcShutdownMethod);
136 availableMethods["admin_broadcast"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAlertMethod);
137 availableMethods["admin_restart"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRestartMethod);
138 availableMethods["admin_load_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadHeightmapMethod);
139 availableMethods["admin_save_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveHeightmapMethod);
140  
141 // Agent management
142 availableMethods["admin_get_agents"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcGetAgentsMethod);
143 availableMethods["admin_teleport_agent"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcTeleportAgentMethod);
144  
145 // User management
146 availableMethods["admin_create_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateUserMethod);
147 availableMethods["admin_create_user_email"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateUserMethod);
148 availableMethods["admin_exists_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcUserExistsMethod);
149 availableMethods["admin_update_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcUpdateUserAccountMethod);
150 availableMethods["admin_authenticate_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAuthenticateUserMethod);
151  
152 // Region state management
153 availableMethods["admin_load_xml"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadXMLMethod);
154 availableMethods["admin_save_xml"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveXMLMethod);
155 availableMethods["admin_load_oar"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadOARMethod);
156 availableMethods["admin_save_oar"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveOARMethod);
157  
158 // Estate access list management
159 availableMethods["admin_acl_clear"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListClear);
160 availableMethods["admin_acl_add"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListAdd);
161 availableMethods["admin_acl_remove"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListRemove);
162 availableMethods["admin_acl_list"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListList);
163 availableMethods["admin_estate_reload"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcEstateReload);
164  
165 // Land management
166 availableMethods["admin_reset_land"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcResetLand);
167  
168 // Either enable full remote functionality or just selected features
169 string enabledMethods = m_config.GetString("enabled_methods", "all");
170  
171 // To get this, you must explicitly specify "all" or
172 // mention it in a whitelist. It won't be available
173 // If you just leave the option out!
174 //
175 if (!String.IsNullOrEmpty(enabledMethods))
176 availableMethods["admin_console_command"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcConsoleCommandMethod);
177  
178 // The assumption here is that simply enabling Remote Admin as before will produce the same
179 // behavior - enable all methods unless the whitelist is in place for backward-compatibility.
180 if (enabledMethods.ToLower() == "all" || String.IsNullOrEmpty(enabledMethods))
181 {
182 foreach (string method in availableMethods.Keys)
183 {
184 m_httpServer.AddXmlRPCHandler(method, availableMethods[method], false);
185 }
186 }
187 else
188 {
189 foreach (string enabledMethod in enabledMethods.Split('|'))
190 {
191 m_httpServer.AddXmlRPCHandler(enabledMethod, availableMethods[enabledMethod], false);
192 }
193 }
194 }
195 }
196 catch (NullReferenceException)
197 {
198 // Ignore.
199 }
200 }
201  
202 public void PostInitialise()
203 {
204 if (!CreateDefaultAvatars())
205 {
206 m_log.Info("[RADMIN]: Default avatars not loaded");
207 }
208 }
209  
210 /// <summary>
211 /// Invoke an XmlRpc method with the standard actions (password check, etc.)
212 /// </summary>
213 /// <param name="method"></param>
214 private XmlRpcResponse InvokeXmlRpcMethod(
215 XmlRpcRequest request, IPEndPoint remoteClient, Action<XmlRpcRequest, XmlRpcResponse, IPEndPoint> method)
216 {
217 XmlRpcResponse response = new XmlRpcResponse();
218 Hashtable responseData = new Hashtable();
219 response.Value = responseData;
220  
221 try
222 {
223 Hashtable requestData = (Hashtable) request.Params[0];
224  
225 CheckStringParameters(requestData, responseData, new string[] {"password"});
226  
227 FailIfRemoteAdminNotAllowed((string)requestData["password"], responseData, remoteClient.Address.ToString());
228  
229 method(request, response, remoteClient);
230 }
231 catch (Exception e)
232 {
233 m_log.ErrorFormat(
234 "[RADMIN]: Method {0} failed. Exception {1}{2}", request.MethodName, e.Message, e.StackTrace);
235  
236 responseData["success"] = false;
237 responseData["error"] = e.Message;
238 }
239  
240 return response;
241 }
242  
243 private void FailIfRemoteAdminNotAllowed(string password, Hashtable responseData, string check_ip_address)
244 {
245 if (m_accessIP.Count > 0 && !m_accessIP.Contains(check_ip_address))
246 {
247 m_log.WarnFormat("[RADMIN]: Unauthorized access blocked from IP {0}", check_ip_address);
248 responseData["accepted"] = false;
249 throw new Exception("not authorized");
250 }
251  
252 if (m_requiredPassword != String.Empty && password != m_requiredPassword)
253 {
254 m_log.WarnFormat("[RADMIN]: Wrong password, blocked access from IP {0}", check_ip_address);
255 responseData["accepted"] = false;
256 throw new Exception("wrong password");
257 }
258 }
259  
260 private void XmlRpcRestartMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
261 {
262 Hashtable responseData = (Hashtable)response.Value;
263 Hashtable requestData = (Hashtable)request.Params[0];
264  
265 try
266 {
267 m_log.Info("[RADMIN]: Request to restart Region.");
268  
269 CheckRegionParams(requestData, responseData);
270  
271 Scene rebootedScene = null;
272 GetSceneFromRegionParams(requestData, responseData, out rebootedScene);
273  
274 responseData["success"] = false;
275 responseData["accepted"] = true;
276 responseData["rebooting"] = true;
277  
278 IRestartModule restartModule = rebootedScene.RequestModuleInterface<IRestartModule>();
279 if (restartModule != null)
280 {
281 List<int> times = new List<int> { 30, 15 };
282  
283 restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), true);
284 responseData["success"] = true;
285 }
286 }
287 catch (Exception e)
288 {
289 // m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace);
290 responseData["rebooting"] = false;
291  
292 throw e;
293 }
294  
295 m_log.Info("[RADMIN]: Restart Region request complete");
296 }
297  
298 private void XmlRpcAlertMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
299 {
300 m_log.Info("[RADMIN]: Alert request started");
301  
302 Hashtable responseData = (Hashtable)response.Value;
303 Hashtable requestData = (Hashtable)request.Params[0];
304  
305 string message = (string) requestData["message"];
306 m_log.InfoFormat("[RADMIN]: Broadcasting: {0}", message);
307  
308 responseData["accepted"] = true;
309 responseData["success"] = true;
310  
311 m_application.SceneManager.ForEachScene(
312 delegate(Scene scene)
313 {
314 IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
315 if (dialogModule != null)
316 dialogModule.SendGeneralAlert(message);
317 });
318  
319 m_log.Info("[RADMIN]: Alert request complete");
320 }
321  
322 private void XmlRpcLoadHeightmapMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
323 {
324 m_log.Info("[RADMIN]: Load height maps request started");
325  
326 Hashtable responseData = (Hashtable)response.Value;
327 Hashtable requestData = (Hashtable)request.Params[0];
328  
329 // m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request);
330 // foreach (string k in requestData.Keys)
331 // {
332 // m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}: >{1}< {2}",
333 // k, (string)requestData[k], ((string)requestData[k]).Length);
334 // }
335  
336 CheckStringParameters(requestData, responseData, new string[] { "filename" });
337 CheckRegionParams(requestData, responseData);
338  
339 Scene scene = null;
340 GetSceneFromRegionParams(requestData, responseData, out scene);
341  
342 if (scene != null)
343 {
344 string file = (string)requestData["filename"];
345  
346 responseData["accepted"] = true;
347  
348 LoadHeightmap(file, scene.RegionInfo.RegionID);
349  
350 responseData["success"] = true;
351 }
352 else
353 {
354 responseData["success"] = false;
355 }
356  
357 m_log.Info("[RADMIN]: Load height maps request complete");
358 }
359  
360 private void XmlRpcSaveHeightmapMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
361 {
362 m_log.Info("[RADMIN]: Save height maps request started");
363  
364 Hashtable responseData = (Hashtable)response.Value;
365 Hashtable requestData = (Hashtable)request.Params[0];
366  
367 // m_log.DebugFormat("[RADMIN]: Save Terrain: XmlRpc {0}", request.ToString());
368  
369 CheckStringParameters(requestData, responseData, new string[] { "filename" });
370 CheckRegionParams(requestData, responseData);
371  
372 Scene scene = null;
373 GetSceneFromRegionParams(requestData, responseData, out scene);
374  
375 if (scene != null)
376 {
377 string file = (string)requestData["filename"];
378 m_log.InfoFormat("[RADMIN]: Terrain Saving: {0}", file);
379  
380 responseData["accepted"] = true;
381  
382 ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
383 if (null == terrainModule) throw new Exception("terrain module not available");
384  
385 terrainModule.SaveToFile(file);
386  
387 responseData["success"] = true;
388 }
389 else
390 {
391 responseData["success"] = false;
392 }
393  
394 m_log.Info("[RADMIN]: Save height maps request complete");
395 }
396  
397 private void XmlRpcShutdownMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
398 {
399 m_log.Info("[RADMIN]: Received Shutdown Administrator Request");
400  
401 Hashtable responseData = (Hashtable)response.Value;
402 Hashtable requestData = (Hashtable)request.Params[0];
403  
404 responseData["accepted"] = true;
405 response.Value = responseData;
406  
407 int timeout = 2000;
408 string message;
409  
410 if (requestData.ContainsKey("shutdown")
411 && ((string) requestData["shutdown"] == "delayed")
412 && requestData.ContainsKey("milliseconds"))
413 {
414 timeout = Int32.Parse(requestData["milliseconds"].ToString());
415  
416 message
417 = "Region is going down in " + ((int) (timeout/1000)).ToString()
418 + " second(s). Please save what you are doing and log out.";
419 }
420 else
421 {
422 message = "Region is going down now.";
423 }
424  
425 m_application.SceneManager.ForEachScene(
426 delegate(Scene scene)
427 {
428 IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
429 if (dialogModule != null)
430 dialogModule.SendGeneralAlert(message);
431 });
432  
433 // Perform shutdown
434 System.Timers.Timer shutdownTimer = new System.Timers.Timer(timeout); // Wait before firing
435 shutdownTimer.AutoReset = false;
436 shutdownTimer.Elapsed += new ElapsedEventHandler(shutdownTimer_Elapsed);
437 lock (shutdownTimer)
438 {
439 shutdownTimer.Start();
440 }
441  
442 responseData["success"] = true;
443  
444 m_log.Info("[RADMIN]: Shutdown Administrator Request complete");
445 }
446  
447 private void shutdownTimer_Elapsed(object sender, ElapsedEventArgs e)
448 {
449 m_application.Shutdown();
450 }
451  
452 /// <summary>
453 /// Create a new region.
454 /// <summary>
455 /// <param name="request">incoming XML RPC request</param>
456 /// <remarks>
457 /// XmlRpcCreateRegionMethod takes the following XMLRPC
458 /// parameters
459 /// <list type="table">
460 /// <listheader><term>parameter name</term><description>description</description></listheader>
461 /// <item><term>password</term>
462 /// <description>admin password as set in OpenSim.ini</description></item>
463 /// <item><term>region_name</term>
464 /// <description>desired region name</description></item>
465 /// <item><term>region_id</term>
466 /// <description>(optional) desired region UUID</description></item>
467 /// <item><term>region_x</term>
468 /// <description>desired region X coordinate (integer)</description></item>
469 /// <item><term>region_y</term>
470 /// <description>desired region Y coordinate (integer)</description></item>
471 /// <item><term>estate_owner_first</term>
472 /// <description>firstname of estate owner (formerly region master)
473 /// (required if new estate is being created, optional otherwise)</description></item>
474 /// <item><term>estate_owner_last</term>
475 /// <description>lastname of estate owner (formerly region master)
476 /// (required if new estate is being created, optional otherwise)</description></item>
477 /// <item><term>estate_owner_uuid</term>
478 /// <description>explicit UUID to use for estate owner (optional)</description></item>
479 /// <item><term>listen_ip</term>
480 /// <description>internal IP address (dotted quad)</description></item>
481 /// <item><term>listen_port</term>
482 /// <description>internal port (integer)</description></item>
483 /// <item><term>external_address</term>
484 /// <description>external IP address</description></item>
485 /// <item><term>persist</term>
486 /// <description>if true, persist the region info
487 /// ('true' or 'false')</description></item>
488 /// <item><term>public</term>
489 /// <description>if true, the region is public
490 /// ('true' or 'false') (optional, default: true)</description></item>
491 /// <item><term>enable_voice</term>
492 /// <description>if true, enable voice on all parcels,
493 /// ('true' or 'false') (optional, default: false)</description></item>
494 /// <item><term>estate_name</term>
495 /// <description>the name of the estate to join (or to create if it doesn't
496 /// already exist)</description></item>
497 /// <item><term>region_file</term>
498 /// <description>The name of the file to persist the region specifications to.
499 /// If omitted, the region_file_template setting from OpenSim.ini will be used. (optional)</description></item>
500 /// </list>
501 ///
502 /// XmlRpcCreateRegionMethod returns
503 /// <list type="table">
504 /// <listheader><term>name</term><description>description</description></listheader>
505 /// <item><term>success</term>
506 /// <description>true or false</description></item>
507 /// <item><term>error</term>
508 /// <description>error message if success is false</description></item>
509 /// <item><term>region_uuid</term>
510 /// <description>UUID of the newly created region</description></item>
511 /// <item><term>region_name</term>
512 /// <description>name of the newly created region</description></item>
513 /// </list>
514 /// </remarks>
515 private void XmlRpcCreateRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
516 {
517 m_log.Info("[RADMIN]: CreateRegion: new request");
518  
519 Hashtable responseData = (Hashtable)response.Value;
520 Hashtable requestData = (Hashtable)request.Params[0];
521  
522 lock (m_requestLock)
523 {
524 int m_regionLimit = m_config.GetInt("region_limit", 0);
525 bool m_enableVoiceForNewRegions = m_config.GetBoolean("create_region_enable_voice", false);
526 bool m_publicAccess = m_config.GetBoolean("create_region_public", true);
527  
528 CheckStringParameters(requestData, responseData, new string[]
529 {
530 "region_name",
531 "listen_ip", "external_address",
532 "estate_name"
533 });
534 CheckIntegerParams(requestData, responseData, new string[] {"region_x", "region_y", "listen_port"});
535  
536 // check whether we still have space left (iff we are using limits)
537 if (m_regionLimit != 0 && m_application.SceneManager.Scenes.Count >= m_regionLimit)
538 throw new Exception(String.Format("cannot instantiate new region, server capacity {0} already reached; delete regions first",
539 m_regionLimit));
540 // extract or generate region ID now
541 Scene scene = null;
542 UUID regionID = UUID.Zero;
543 if (requestData.ContainsKey("region_id") &&
544 !String.IsNullOrEmpty((string) requestData["region_id"]))
545 {
546 regionID = (UUID) (string) requestData["region_id"];
547 if (m_application.SceneManager.TryGetScene(regionID, out scene))
548 throw new Exception(
549 String.Format("region UUID already in use by region {0}, UUID {1}, <{2},{3}>",
550 scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
551 scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
552 }
553 else
554 {
555 regionID = UUID.Random();
556 m_log.DebugFormat("[RADMIN] CreateRegion: new region UUID {0}", regionID);
557 }
558  
559 // create volatile or persistent region info
560 RegionInfo region = new RegionInfo();
561  
562 region.RegionID = regionID;
563 region.originRegionID = regionID;
564 region.RegionName = (string) requestData["region_name"];
565 region.RegionLocX = Convert.ToUInt32(requestData["region_x"]);
566 region.RegionLocY = Convert.ToUInt32(requestData["region_y"]);
567  
568 // check for collisions: region name, region UUID,
569 // region location
570 if (m_application.SceneManager.TryGetScene(region.RegionName, out scene))
571 throw new Exception(
572 String.Format("region name already in use by region {0}, UUID {1}, <{2},{3}>",
573 scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
574 scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
575  
576 if (m_application.SceneManager.TryGetScene(region.RegionLocX, region.RegionLocY, out scene))
577 throw new Exception(
578 String.Format("region location <{0},{1}> already in use by region {2}, UUID {3}, <{4},{5}>",
579 region.RegionLocX, region.RegionLocY,
580 scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
581 scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
582  
583 region.InternalEndPoint =
584 new IPEndPoint(IPAddress.Parse((string) requestData["listen_ip"]), 0);
585  
586 region.InternalEndPoint.Port = Convert.ToInt32(requestData["listen_port"]);
587 if (0 == region.InternalEndPoint.Port) throw new Exception("listen_port is 0");
588 if (m_application.SceneManager.TryGetScene(region.InternalEndPoint, out scene))
589 throw new Exception(
590 String.Format(
591 "region internal IP {0} and port {1} already in use by region {2}, UUID {3}, <{4},{5}>",
592 region.InternalEndPoint.Address,
593 region.InternalEndPoint.Port,
594 scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
595 scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
596  
597 region.ExternalHostName = (string) requestData["external_address"];
598  
599 bool persist = Convert.ToBoolean(requestData["persist"]);
600 if (persist)
601 {
602 // default place for region configuration files is in the
603 // Regions directory of the config dir (aka /bin)
604 string regionConfigPath = Path.Combine(Util.configDir(), "Regions");
605 try
606 {
607 // OpenSim.ini can specify a different regions dir
608 IConfig startupConfig = (IConfig) m_configSource.Configs["Startup"];
609 regionConfigPath = startupConfig.GetString("regionload_regionsdir", regionConfigPath).Trim();
610 }
611 catch (Exception)
612 {
613 // No INI setting recorded.
614 }
615  
616 string regionIniPath;
617  
618 if (requestData.Contains("region_file"))
619 {
620 // Make sure that the file to be created is in a subdirectory of the region storage directory.
621 string requestedFilePath = Path.Combine(regionConfigPath, (string) requestData["region_file"]);
622 string requestedDirectory = Path.GetDirectoryName(Path.GetFullPath(requestedFilePath));
623 if (requestedDirectory.StartsWith(Path.GetFullPath(regionConfigPath)))
624 regionIniPath = requestedFilePath;
625 else
626 throw new Exception("Invalid location for region file.");
627 }
628 else
629 {
630 regionIniPath = Path.Combine(regionConfigPath,
631 String.Format(
632 m_config.GetString("region_file_template",
633 "{0}x{1}-{2}.ini"),
634 region.RegionLocX.ToString(),
635 region.RegionLocY.ToString(),
636 regionID.ToString(),
637 region.InternalEndPoint.Port.ToString(),
638 region.RegionName.Replace(" ", "_").Replace(":", "_").
639 Replace("/", "_")));
640 }
641  
642 m_log.DebugFormat("[RADMIN] CreateRegion: persisting region {0} to {1}",
643 region.RegionID, regionIniPath);
644 region.SaveRegionToFile("dynamic region", regionIniPath);
645 }
646 else
647 {
648 region.Persistent = false;
649 }
650  
651 // Set the estate
652  
653 // Check for an existing estate
654 List<int> estateIDs = m_application.EstateDataService.GetEstates((string) requestData["estate_name"]);
655 if (estateIDs.Count < 1)
656 {
657 UUID userID = UUID.Zero;
658 if (requestData.ContainsKey("estate_owner_uuid"))
659 {
660 // ok, client wants us to use an explicit UUID
661 // regardless of what the avatar name provided
662 userID = new UUID((string) requestData["estate_owner_uuid"]);
663  
664 // Check that the specified user exists
665 Scene currentOrFirst = m_application.SceneManager.CurrentOrFirstScene;
666 IUserAccountService accountService = currentOrFirst.UserAccountService;
667 UserAccount user = accountService.GetUserAccount(currentOrFirst.RegionInfo.ScopeID, userID);
668  
669 if (user == null)
670 throw new Exception("Specified user was not found.");
671 }
672 else if (requestData.ContainsKey("estate_owner_first") & requestData.ContainsKey("estate_owner_last"))
673 {
674 // We need to look up the UUID for the avatar with the provided name.
675 string ownerFirst = (string) requestData["estate_owner_first"];
676 string ownerLast = (string) requestData["estate_owner_last"];
677  
678 Scene currentOrFirst = m_application.SceneManager.CurrentOrFirstScene;
679 IUserAccountService accountService = currentOrFirst.UserAccountService;
680 UserAccount user = accountService.GetUserAccount(currentOrFirst.RegionInfo.ScopeID,
681 ownerFirst, ownerLast);
682  
683 // Check that the specified user exists
684 if (user == null)
685 throw new Exception("Specified user was not found.");
686  
687 userID = user.PrincipalID;
688 }
689 else
690 {
691 throw new Exception("Estate owner details not provided.");
692 }
693  
694 // Create a new estate with the name provided
695 region.EstateSettings = m_application.EstateDataService.CreateNewEstate();
696  
697 region.EstateSettings.EstateName = (string) requestData["estate_name"];
698 region.EstateSettings.EstateOwner = userID;
699 // Persistence does not seem to effect the need to save a new estate
700 m_application.EstateDataService.StoreEstateSettings(region.EstateSettings);
701  
702 if (!m_application.EstateDataService.LinkRegion(region.RegionID, (int) region.EstateSettings.EstateID))
703 throw new Exception("Failed to join estate.");
704 }
705 else
706 {
707 int estateID = estateIDs[0];
708  
709 region.EstateSettings = m_application.EstateDataService.LoadEstateSettings(region.RegionID, false);
710  
711 if (region.EstateSettings.EstateID != estateID)
712 {
713 // The region is already part of an estate, but not the one we want.
714 region.EstateSettings = m_application.EstateDataService.LoadEstateSettings(estateID);
715  
716 if (!m_application.EstateDataService.LinkRegion(region.RegionID, estateID))
717 throw new Exception("Failed to join estate.");
718 }
719 }
720  
721 // Create the region and perform any initial initialization
722  
723 IScene newScene;
724 m_application.CreateRegion(region, out newScene);
725 newScene.Start();
726  
727 // If an access specification was provided, use it.
728 // Otherwise accept the default.
729 newScene.RegionInfo.EstateSettings.PublicAccess = GetBoolean(requestData, "public", m_publicAccess);
730 m_application.EstateDataService.StoreEstateSettings(newScene.RegionInfo.EstateSettings);
731  
732 // enable voice on newly created region if
733 // requested by either the XmlRpc request or the
734 // configuration
735 if (GetBoolean(requestData, "enable_voice", m_enableVoiceForNewRegions))
736 {
737 List<ILandObject> parcels = ((Scene)newScene).LandChannel.AllParcels();
738  
739 foreach (ILandObject parcel in parcels)
740 {
741 parcel.LandData.Flags |= (uint) ParcelFlags.AllowVoiceChat;
742 parcel.LandData.Flags |= (uint) ParcelFlags.UseEstateVoiceChan;
743 ((Scene)newScene).LandChannel.UpdateLandObject(parcel.LandData.LocalID, parcel.LandData);
744 }
745 }
746  
747 //Load Heightmap if specified to new region
748 if (requestData.Contains("heightmap_file"))
749 {
750 LoadHeightmap((string)requestData["heightmap_file"], region.RegionID);
751 }
752  
753 responseData["success"] = true;
754 responseData["region_name"] = region.RegionName;
755 responseData["region_id"] = region.RegionID.ToString();
756  
757 m_log.Info("[RADMIN]: CreateRegion: request complete");
758 }
759 }
760  
761 /// <summary>
762 /// Delete a new region.
763 /// <summary>
764 /// <param name="request">incoming XML RPC request</param>
765 /// <remarks>
766 /// XmlRpcDeleteRegionMethod takes the following XMLRPC
767 /// parameters
768 /// <list type="table">
769 /// <listheader><term>parameter name</term><description>description</description></listheader>
770 /// <item><term>password</term>
771 /// <description>admin password as set in OpenSim.ini</description></item>
772 /// <item><term>region_name</term>
773 /// <description>desired region name</description></item>
774 /// <item><term>region_id</term>
775 /// <description>(optional) desired region UUID</description></item>
776 /// </list>
777 ///
778 /// XmlRpcDeleteRegionMethod returns
779 /// <list type="table">
780 /// <listheader><term>name</term><description>description</description></listheader>
781 /// <item><term>success</term>
782 /// <description>true or false</description></item>
783 /// <item><term>error</term>
784 /// <description>error message if success is false</description></item>
785 /// </list>
786 /// </remarks>
787 private void XmlRpcDeleteRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
788 {
789 m_log.Info("[RADMIN]: DeleteRegion: new request");
790  
791 Hashtable responseData = (Hashtable)response.Value;
792 Hashtable requestData = (Hashtable)request.Params[0];
793  
794 lock (m_requestLock)
795 {
796 CheckStringParameters(requestData, responseData, new string[] {"region_name"});
797 CheckRegionParams(requestData, responseData);
798  
799 Scene scene = null;
800 GetSceneFromRegionParams(requestData, responseData, out scene);
801  
802 m_application.RemoveRegion(scene, true);
803  
804 responseData["success"] = true;
805 responseData["region_name"] = scene.RegionInfo.RegionName;
806 responseData["region_id"] = scene.RegionInfo.RegionID;
807  
808 m_log.Info("[RADMIN]: DeleteRegion: request complete");
809 }
810 }
811  
812 /// <summary>
813 /// Close a region.
814 /// <summary>
815 /// <param name="request">incoming XML RPC request</param>
816 /// <remarks>
817 /// XmlRpcCloseRegionMethod takes the following XMLRPC
818 /// parameters
819 /// <list type="table">
820 /// <listheader><term>parameter name</term><description>description</description></listheader>
821 /// <item><term>password</term>
822 /// <description>admin password as set in OpenSim.ini</description></item>
823 /// <item><term>region_name</term>
824 /// <description>desired region name</description></item>
825 /// <item><term>region_id</term>
826 /// <description>(optional) desired region UUID</description></item>
827 /// </list>
828 ///
829 /// XmlRpcShutdownRegionMethod returns
830 /// <list type="table">
831 /// <listheader><term>name</term><description>description</description></listheader>
832 /// <item><term>success</term>
833 /// <description>true or false</description></item>
834 /// <item><term>region_name</term>
835 /// <description>the region name if success is true</description></item>
836 /// <item><term>error</term>
837 /// <description>error message if success is false</description></item>
838 /// </list>
839 /// </remarks>
840 private void XmlRpcCloseRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
841 {
842 m_log.Info("[RADMIN]: CloseRegion: new request");
843  
844 Hashtable responseData = (Hashtable)response.Value;
845 Hashtable requestData = (Hashtable)request.Params[0];
846  
847 lock (m_requestLock)
848 {
849 CheckRegionParams(requestData, responseData);
850  
851 Scene scene = null;
852 GetSceneFromRegionParams(requestData, responseData, out scene);
853  
854 m_application.CloseRegion(scene);
855  
856 responseData["success"] = true;
857 responseData["region_name"] = scene.RegionInfo.RegionName;
858 responseData["region_id"] = scene.RegionInfo.RegionID;
859  
860 response.Value = responseData;
861  
862 m_log.Info("[RADMIN]: CloseRegion: request complete");
863 }
864 }
865  
866 /// <summary>
867 /// Change characteristics of an existing region.
868 /// <summary>
869 /// <param name="request">incoming XML RPC request</param>
870 /// <remarks>
871 /// XmlRpcModifyRegionMethod takes the following XMLRPC
872 /// parameters
873 /// <list type="table">
874 /// <listheader><term>parameter name</term><description>description</description></listheader>
875 /// <item><term>password</term>
876 /// <description>admin password as set in OpenSim.ini</description></item>
877 /// <item><term>region_name</term>
878 /// <description>desired region name</description></item>
879 /// <item><term>region_id</term>
880 /// <description>(optional) desired region UUID</description></item>
881 /// <item><term>public</term>
882 /// <description>if true, set the region to public
883 /// ('true' or 'false'), else to private</description></item>
884 /// <item><term>enable_voice</term>
885 /// <description>if true, enable voice on all parcels of
886 /// the region, else disable</description></item>
887 /// </list>
888 ///
889 /// XmlRpcModifyRegionMethod returns
890 /// <list type="table">
891 /// <listheader><term>name</term><description>description</description></listheader>
892 /// <item><term>success</term>
893 /// <description>true or false</description></item>
894 /// <item><term>error</term>
895 /// <description>error message if success is false</description></item>
896 /// </list>
897 /// </remarks>
898 private void XmlRpcModifyRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
899 {
900 m_log.Info("[RADMIN]: ModifyRegion: new request");
901  
902 Hashtable responseData = (Hashtable)response.Value;
903 Hashtable requestData = (Hashtable)request.Params[0];
904  
905 lock (m_requestLock)
906 {
907 CheckRegionParams(requestData, responseData);
908  
909 Scene scene = null;
910 GetSceneFromRegionParams(requestData, responseData, out scene);
911  
912 // Modify access
913 scene.RegionInfo.EstateSettings.PublicAccess =
914 GetBoolean(requestData,"public", scene.RegionInfo.EstateSettings.PublicAccess);
915 if (scene.RegionInfo.Persistent)
916 m_application.EstateDataService.StoreEstateSettings(scene.RegionInfo.EstateSettings);
917  
918 if (requestData.ContainsKey("enable_voice"))
919 {
920 bool enableVoice = GetBoolean(requestData, "enable_voice", true);
921 List<ILandObject> parcels = ((Scene)scene).LandChannel.AllParcels();
922  
923 foreach (ILandObject parcel in parcels)
924 {
925 if (enableVoice)
926 {
927 parcel.LandData.Flags |= (uint)ParcelFlags.AllowVoiceChat;
928 parcel.LandData.Flags |= (uint)ParcelFlags.UseEstateVoiceChan;
929 }
930 else
931 {
932 parcel.LandData.Flags &= ~(uint)ParcelFlags.AllowVoiceChat;
933 parcel.LandData.Flags &= ~(uint)ParcelFlags.UseEstateVoiceChan;
934 }
935 scene.LandChannel.UpdateLandObject(parcel.LandData.LocalID, parcel.LandData);
936 }
937 }
938  
939 responseData["success"] = true;
940 responseData["region_name"] = scene.RegionInfo.RegionName;
941 responseData["region_id"] = scene.RegionInfo.RegionID;
942  
943 m_log.Info("[RADMIN]: ModifyRegion: request complete");
944 }
945 }
946  
947 /// <summary>
948 /// Create a new user account.
949 /// <summary>
950 /// <param name="request">incoming XML RPC request</param>
951 /// <remarks>
952 /// XmlRpcCreateUserMethod takes the following XMLRPC
953 /// parameters
954 /// <list type="table">
955 /// <listheader><term>parameter name</term><description>description</description></listheader>
956 /// <item><term>password</term>
957 /// <description>admin password as set in OpenSim.ini</description></item>
958 /// <item><term>user_firstname</term>
959 /// <description>avatar's first name</description></item>
960 /// <item><term>user_lastname</term>
961 /// <description>avatar's last name</description></item>
962 /// <item><term>user_password</term>
963 /// <description>avatar's password</description></item>
964 /// <item><term>user_email</term>
965 /// <description>email of the avatar's owner (optional)</description></item>
966 /// <item><term>start_region_x</term>
967 /// <description>avatar's start region coordinates, X value</description></item>
968 /// <item><term>start_region_y</term>
969 /// <description>avatar's start region coordinates, Y value</description></item>
970 /// </list>
971 ///
972 /// XmlRpcCreateUserMethod returns
973 /// <list type="table">
974 /// <listheader><term>name</term><description>description</description></listheader>
975 /// <item><term>success</term>
976 /// <description>true or false</description></item>
977 /// <item><term>error</term>
978 /// <description>error message if success is false</description></item>
979 /// <item><term>avatar_uuid</term>
980 /// <description>UUID of the newly created avatar
981 /// account; UUID.Zero if failed.
982 /// </description></item>
983 /// </list>
984 /// </remarks>
985 private void XmlRpcCreateUserMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
986 {
987 m_log.Info("[RADMIN]: CreateUser: new request");
988  
989 Hashtable responseData = (Hashtable)response.Value;
990 Hashtable requestData = (Hashtable)request.Params[0];
991  
992 lock (m_requestLock)
993 {
994 try
995 {
996 // check completeness
997 CheckStringParameters(requestData, responseData, new string[]
998 {
999 "user_firstname",
1000 "user_lastname", "user_password",
1001 });
1002 CheckIntegerParams(requestData, responseData, new string[] {"start_region_x", "start_region_y"});
1003  
1004 // do the job
1005 string firstName = (string) requestData["user_firstname"];
1006 string lastName = (string) requestData["user_lastname"];
1007 string password = (string) requestData["user_password"];
1008  
1009 uint regionXLocation = Convert.ToUInt32(requestData["start_region_x"]);
1010 uint regionYLocation = Convert.ToUInt32(requestData["start_region_y"]);
1011  
1012 string email = ""; // empty string for email
1013 if (requestData.Contains("user_email"))
1014 email = (string)requestData["user_email"];
1015  
1016 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
1017 UUID scopeID = scene.RegionInfo.ScopeID;
1018  
1019 UserAccount account = CreateUser(scopeID, firstName, lastName, password, email);
1020  
1021 if (null == account)
1022 throw new Exception(String.Format("failed to create new user {0} {1}",
1023 firstName, lastName));
1024  
1025 // Set home position
1026  
1027 GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
1028 (int)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
1029 if (null == home)
1030 {
1031 m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", firstName, lastName);
1032 }
1033 else
1034 {
1035 scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
1036 m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, firstName, lastName);
1037 }
1038  
1039 // Establish the avatar's initial appearance
1040  
1041 UpdateUserAppearance(responseData, requestData, account.PrincipalID);
1042  
1043 responseData["success"] = true;
1044 responseData["avatar_uuid"] = account.PrincipalID.ToString();
1045  
1046 m_log.InfoFormat("[RADMIN]: CreateUser: User {0} {1} created, UUID {2}", firstName, lastName, account.PrincipalID);
1047 }
1048 catch (Exception e)
1049 {
1050 responseData["avatar_uuid"] = UUID.Zero.ToString();
1051  
1052 throw e;
1053 }
1054  
1055 m_log.Info("[RADMIN]: CreateUser: request complete");
1056 }
1057 }
1058  
1059 /// <summary>
1060 /// Check whether a certain user account exists.
1061 /// <summary>
1062 /// <param name="request">incoming XML RPC request</param>
1063 /// <remarks>
1064 /// XmlRpcUserExistsMethod takes the following XMLRPC
1065 /// parameters
1066 /// <list type="table">
1067 /// <listheader><term>parameter name</term><description>description</description></listheader>
1068 /// <item><term>password</term>
1069 /// <description>admin password as set in OpenSim.ini</description></item>
1070 /// <item><term>user_firstname</term>
1071 /// <description>avatar's first name</description></item>
1072 /// <item><term>user_lastname</term>
1073 /// <description>avatar's last name</description></item>
1074 /// </list>
1075 ///
1076 /// XmlRpcCreateUserMethod returns
1077 /// <list type="table">
1078 /// <listheader><term>name</term><description>description</description></listheader>
1079 /// <item><term>user_firstname</term>
1080 /// <description>avatar's first name</description></item>
1081 /// <item><term>user_lastname</term>
1082 /// <description>avatar's last name</description></item>
1083 /// <item><term>user_lastlogin</term>
1084 /// <description>avatar's last login time (secs since UNIX epoch)</description></item>
1085 /// <item><term>success</term>
1086 /// <description>true or false</description></item>
1087 /// <item><term>error</term>
1088 /// <description>error message if success is false</description></item>
1089 /// </list>
1090 /// </remarks>
1091 private void XmlRpcUserExistsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1092 {
1093 m_log.Info("[RADMIN]: UserExists: new request");
1094  
1095 Hashtable responseData = (Hashtable)response.Value;
1096 Hashtable requestData = (Hashtable)request.Params[0];
1097  
1098 // check completeness
1099 CheckStringParameters(requestData, responseData, new string[] {"user_firstname", "user_lastname"});
1100  
1101 string firstName = (string) requestData["user_firstname"];
1102 string lastName = (string) requestData["user_lastname"];
1103  
1104 responseData["user_firstname"] = firstName;
1105 responseData["user_lastname"] = lastName;
1106  
1107 UUID scopeID = m_application.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
1108  
1109 UserAccount account = m_application.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);
1110  
1111 if (null == account)
1112 {
1113 responseData["success"] = false;
1114 responseData["lastlogin"] = 0;
1115 }
1116 else
1117 {
1118 GridUserInfo userInfo = m_application.SceneManager.CurrentOrFirstScene.GridUserService.GetGridUserInfo(account.PrincipalID.ToString());
1119 if (userInfo != null)
1120 responseData["lastlogin"] = Util.ToUnixTime(userInfo.Login);
1121 else
1122 responseData["lastlogin"] = 0;
1123  
1124 responseData["success"] = true;
1125 }
1126  
1127 m_log.Info("[RADMIN]: UserExists: request complete");
1128 }
1129  
1130 /// <summary>
1131 /// Update a user account.
1132 /// <summary>
1133 /// <param name="request">incoming XML RPC request</param>
1134 /// <remarks>
1135 /// XmlRpcUpdateUserAccountMethod takes the following XMLRPC
1136 /// parameters (changeable ones are optional)
1137 /// <list type="table">
1138 /// <listheader><term>parameter name</term><description>description</description></listheader>
1139 /// <item><term>password</term>
1140 /// <description>admin password as set in OpenSim.ini</description></item>
1141 /// <item><term>user_firstname</term>
1142 /// <description>avatar's first name (cannot be changed)</description></item>
1143 /// <item><term>user_lastname</term>
1144 /// <description>avatar's last name (cannot be changed)</description></item>
1145 /// <item><term>user_password</term>
1146 /// <description>avatar's password (changeable)</description></item>
1147 /// <item><term>start_region_x</term>
1148 /// <description>avatar's start region coordinates, X
1149 /// value (changeable)</description></item>
1150 /// <item><term>start_region_y</term>
1151 /// <description>avatar's start region coordinates, Y
1152 /// value (changeable)</description></item>
1153 /// <item><term>about_real_world (not implemented yet)</term>
1154 /// <description>"about" text of avatar owner (changeable)</description></item>
1155 /// <item><term>about_virtual_world (not implemented yet)</term>
1156 /// <description>"about" text of avatar (changeable)</description></item>
1157 /// </list>
1158 ///
1159 /// XmlRpcCreateUserMethod returns
1160 /// <list type="table">
1161 /// <listheader><term>name</term><description>description</description></listheader>
1162 /// <item><term>success</term>
1163 /// <description>true or false</description></item>
1164 /// <item><term>error</term>
1165 /// <description>error message if success is false</description></item>
1166 /// <item><term>avatar_uuid</term>
1167 /// <description>UUID of the updated avatar
1168 /// account; UUID.Zero if failed.
1169 /// </description></item>
1170 /// </list>
1171 /// </remarks>
1172 private void XmlRpcUpdateUserAccountMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1173 {
1174 m_log.Info("[RADMIN]: UpdateUserAccount: new request");
1175 m_log.Warn("[RADMIN]: This method needs update for 0.7");
1176  
1177 Hashtable responseData = (Hashtable)response.Value;
1178 Hashtable requestData = (Hashtable)request.Params[0];
1179  
1180 lock (m_requestLock)
1181 {
1182 try
1183 {
1184 // check completeness
1185 CheckStringParameters(requestData, responseData, new string[] {
1186 "user_firstname",
1187 "user_lastname"});
1188  
1189 // do the job
1190 string firstName = (string) requestData["user_firstname"];
1191 string lastName = (string) requestData["user_lastname"];
1192  
1193 string password = String.Empty;
1194 uint? regionXLocation = null;
1195 uint? regionYLocation = null;
1196 // uint? ulaX = null;
1197 // uint? ulaY = null;
1198 // uint? ulaZ = null;
1199 // uint? usaX = null;
1200 // uint? usaY = null;
1201 // uint? usaZ = null;
1202 // string aboutFirstLive = String.Empty;
1203 // string aboutAvatar = String.Empty;
1204  
1205 if (requestData.ContainsKey("user_password")) password = (string) requestData["user_password"];
1206 if (requestData.ContainsKey("start_region_x"))
1207 regionXLocation = Convert.ToUInt32(requestData["start_region_x"]);
1208 if (requestData.ContainsKey("start_region_y"))
1209 regionYLocation = Convert.ToUInt32(requestData["start_region_y"]);
1210  
1211 // if (requestData.ContainsKey("start_lookat_x"))
1212 // ulaX = Convert.ToUInt32((Int32) requestData["start_lookat_x"]);
1213 // if (requestData.ContainsKey("start_lookat_y"))
1214 // ulaY = Convert.ToUInt32((Int32) requestData["start_lookat_y"]);
1215 // if (requestData.ContainsKey("start_lookat_z"))
1216 // ulaZ = Convert.ToUInt32((Int32) requestData["start_lookat_z"]);
1217  
1218 // if (requestData.ContainsKey("start_standat_x"))
1219 // usaX = Convert.ToUInt32((Int32) requestData["start_standat_x"]);
1220 // if (requestData.ContainsKey("start_standat_y"))
1221 // usaY = Convert.ToUInt32((Int32) requestData["start_standat_y"]);
1222 // if (requestData.ContainsKey("start_standat_z"))
1223 // usaZ = Convert.ToUInt32((Int32) requestData["start_standat_z"]);
1224 // if (requestData.ContainsKey("about_real_world"))
1225 // aboutFirstLive = (string)requestData["about_real_world"];
1226 // if (requestData.ContainsKey("about_virtual_world"))
1227 // aboutAvatar = (string)requestData["about_virtual_world"];
1228  
1229 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
1230 UUID scopeID = scene.RegionInfo.ScopeID;
1231 UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);
1232  
1233 if (null == account)
1234 throw new Exception(String.Format("avatar {0} {1} does not exist", firstName, lastName));
1235  
1236 if (!String.IsNullOrEmpty(password))
1237 {
1238 m_log.DebugFormat("[RADMIN]: UpdateUserAccount: updating password for avatar {0} {1}", firstName, lastName);
1239 ChangeUserPassword(firstName, lastName, password);
1240 }
1241  
1242 // if (null != usaX) userProfile.HomeLocationX = (uint) usaX;
1243 // if (null != usaY) userProfile.HomeLocationY = (uint) usaY;
1244 // if (null != usaZ) userProfile.HomeLocationZ = (uint) usaZ;
1245  
1246 // if (null != ulaX) userProfile.HomeLookAtX = (uint) ulaX;
1247 // if (null != ulaY) userProfile.HomeLookAtY = (uint) ulaY;
1248 // if (null != ulaZ) userProfile.HomeLookAtZ = (uint) ulaZ;
1249  
1250 // if (String.Empty != aboutFirstLive) userProfile.FirstLifeAboutText = aboutFirstLive;
1251 // if (String.Empty != aboutAvatar) userProfile.AboutText = aboutAvatar;
1252  
1253 // Set home position
1254  
1255 if ((null != regionXLocation) && (null != regionYLocation))
1256 {
1257 GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
1258 (int)Util.RegionToWorldLoc((uint)regionXLocation), (int)Util.RegionToWorldLoc((uint)regionYLocation));
1259 if (null == home) {
1260 m_log.WarnFormat("[RADMIN]: Unable to set home region for updated user account {0} {1}", firstName, lastName);
1261 } else {
1262 scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
1263 m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, firstName, lastName);
1264 }
1265 }
1266  
1267 // User has been created. Now establish gender and appearance.
1268  
1269 UpdateUserAppearance(responseData, requestData, account.PrincipalID);
1270  
1271 responseData["success"] = true;
1272 responseData["avatar_uuid"] = account.PrincipalID.ToString();
1273  
1274 m_log.InfoFormat("[RADMIN]: UpdateUserAccount: account for user {0} {1} updated, UUID {2}",
1275 firstName, lastName,
1276 account.PrincipalID);
1277 }
1278 catch (Exception e)
1279 {
1280 responseData["avatar_uuid"] = UUID.Zero.ToString();
1281  
1282 throw e;
1283 }
1284  
1285 m_log.Info("[RADMIN]: UpdateUserAccount: request complete");
1286 }
1287 }
1288  
1289 /// <summary>
1290 /// Authenticate an user.
1291 /// <summary>
1292 /// <param name="request">incoming XML RPC request</param>
1293 /// <remarks>
1294 /// XmlRpcAuthenticateUserMethod takes the following XMLRPC
1295 /// parameters
1296 /// <list type="table">
1297 /// <listheader><term>parameter name</term><description>description</description></listheader>
1298 /// <item><term>password</term>
1299 /// <description>admin password as set in OpenSim.ini</description></item>
1300 /// <item><term>user_firstname</term>
1301 /// <description>avatar's first name</description></item>
1302 /// <item><term>user_lastname</term>
1303 /// <description>avatar's last name</description></item>
1304 /// <item><term>user_password</term>
1305 /// <description>MD5 hash of avatar's password</description></item>
1306 /// <item><term>token_lifetime</term>
1307 /// <description>the lifetime of the returned token (upper bounded to 30s)</description></item>
1308 /// </list>
1309 ///
1310 /// XmlRpcAuthenticateUserMethod returns
1311 /// <list type="table">
1312 /// <listheader><term>name</term><description>description</description></listheader>
1313 /// <item><term>success</term>
1314 /// <description>true or false</description></item>
1315 /// <item><term>token</term>
1316 /// <description>the authentication token sent by OpenSim</description></item>
1317 /// <item><term>error</term>
1318 /// <description>error message if success is false</description></item>
1319 /// </list>
1320 /// </remarks>
1321 private void XmlRpcAuthenticateUserMethod(XmlRpcRequest request, XmlRpcResponse response,
1322 IPEndPoint remoteClient)
1323 {
1324 m_log.Info("[RADMIN]: AuthenticateUser: new request");
1325  
1326 var responseData = (Hashtable)response.Value;
1327 var requestData = (Hashtable)request.Params[0];
1328  
1329 lock (m_requestLock)
1330 {
1331 try
1332 {
1333 CheckStringParameters(requestData, responseData, new[]
1334 {
1335 "user_firstname",
1336 "user_lastname",
1337 "user_password",
1338 "token_lifetime"
1339 });
1340  
1341 var firstName = (string)requestData["user_firstname"];
1342 var lastName = (string)requestData["user_lastname"];
1343 var password = (string)requestData["user_password"];
1344  
1345 var scene = m_application.SceneManager.CurrentOrFirstScene;
1346  
1347 if (scene.Equals(null))
1348 {
1349 m_log.Debug("scene does not exist");
1350 throw new Exception("Scene does not exist.");
1351 }
1352  
1353 var scopeID = scene.RegionInfo.ScopeID;
1354 var account = scene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);
1355  
1356 if (account.Equals(null) || account.PrincipalID.Equals(UUID.Zero))
1357 {
1358 m_log.DebugFormat("avatar {0} {1} does not exist", firstName, lastName);
1359 throw new Exception(String.Format("avatar {0} {1} does not exist", firstName, lastName));
1360 }
1361  
1362 if (String.IsNullOrEmpty(password))
1363 {
1364 m_log.DebugFormat("[RADMIN]: AuthenticateUser: no password provided for {0} {1}", firstName,
1365 lastName);
1366 throw new Exception(String.Format("no password provided for {0} {1}", firstName,
1367 lastName));
1368 }
1369  
1370 int lifetime;
1371 if (int.TryParse((string)requestData["token_lifetime"], NumberStyles.Integer, CultureInfo.InvariantCulture, out lifetime) == false)
1372 {
1373 m_log.DebugFormat("[RADMIN]: AuthenticateUser: no token lifetime provided for {0} {1}", firstName,
1374 lastName);
1375 throw new Exception(String.Format("no token lifetime provided for {0} {1}", firstName,
1376 lastName));
1377 }
1378  
1379 // Upper bound on lifetime set to 30s.
1380 if (lifetime > 30)
1381 {
1382 m_log.DebugFormat("[RADMIN]: AuthenticateUser: token lifetime longer than 30s for {0} {1}", firstName,
1383 lastName);
1384 throw new Exception(String.Format("token lifetime longer than 30s for {0} {1}", firstName,
1385 lastName));
1386 }
1387  
1388 var authModule = scene.RequestModuleInterface<IAuthenticationService>();
1389 if (authModule == null)
1390 {
1391 m_log.Debug("[RADMIN]: AuthenticateUser: no authentication module loded");
1392 throw new Exception("no authentication module loaded");
1393 }
1394  
1395 var token = authModule.Authenticate(account.PrincipalID, password, lifetime);
1396 if (String.IsNullOrEmpty(token))
1397 {
1398 m_log.DebugFormat("[RADMIN]: AuthenticateUser: authentication failed for {0} {1}", firstName,
1399 lastName);
1400 throw new Exception(String.Format("authentication failed for {0} {1}", firstName,
1401 lastName));
1402 }
1403  
1404 m_log.DebugFormat("[RADMIN]: AuthenticateUser: account for user {0} {1} identified with token {2}",
1405 firstName, lastName, token);
1406  
1407 responseData["token"] = token;
1408 responseData["success"] = true;
1409  
1410 }
1411 catch (Exception e)
1412 {
1413 responseData["success"] = false;
1414 responseData["error"] = e.Message;
1415 throw e;
1416 }
1417  
1418 m_log.Info("[RADMIN]: AuthenticateUser: request complete");
1419 }
1420 }
1421  
1422 /// <summary>
1423 /// Load an OAR file into a region..
1424 /// <summary>
1425 /// <param name="request">incoming XML RPC request</param>
1426 /// <remarks>
1427 /// XmlRpcLoadOARMethod takes the following XMLRPC
1428 /// parameters
1429 /// <list type="table">
1430 /// <listheader><term>parameter name</term><description>description</description></listheader>
1431 /// <item><term>password</term>
1432 /// <description>admin password as set in OpenSim.ini</description></item>
1433 /// <item><term>filename</term>
1434 /// <description>file name of the OAR file</description></item>
1435 /// <item><term>region_uuid</term>
1436 /// <description>UUID of the region</description></item>
1437 /// <item><term>region_name</term>
1438 /// <description>region name</description></item>
1439 /// <item><term>merge</term>
1440 /// <description>true if oar should be merged</description></item>
1441 /// <item><term>skip-assets</term>
1442 /// <description>true if assets should be skiped</description></item>
1443 /// </list>
1444 ///
1445 /// <code>region_uuid</code> takes precedence over
1446 /// <code>region_name</code> if both are present; one of both
1447 /// must be present.
1448 ///
1449 /// XmlRpcLoadOARMethod returns
1450 /// <list type="table">
1451 /// <listheader><term>name</term><description>description</description></listheader>
1452 /// <item><term>success</term>
1453 /// <description>true or false</description></item>
1454 /// <item><term>error</term>
1455 /// <description>error message if success is false</description></item>
1456 /// </list>
1457 /// </remarks>
1458 private void XmlRpcLoadOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1459 {
1460 m_log.Info("[RADMIN]: Received Load OAR Administrator Request");
1461  
1462 Hashtable responseData = (Hashtable)response.Value;
1463 Hashtable requestData = (Hashtable)request.Params[0];
1464  
1465 lock (m_requestLock)
1466 {
1467 try
1468 {
1469 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1470 CheckRegionParams(requestData, responseData);
1471  
1472 Scene scene = null;
1473 GetSceneFromRegionParams(requestData, responseData, out scene);
1474  
1475 string filename = (string) requestData["filename"];
1476  
1477 bool mergeOar = false;
1478 bool skipAssets = false;
1479  
1480 if ((string)requestData["merge"] == "true")
1481 {
1482 mergeOar = true;
1483 }
1484 if ((string)requestData["skip-assets"] == "true")
1485 {
1486 skipAssets = true;
1487 }
1488  
1489 IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
1490 Dictionary<string, object> archiveOptions = new Dictionary<string,object>();
1491 if (mergeOar) archiveOptions.Add("merge", null);
1492 if (skipAssets) archiveOptions.Add("skipAssets", null);
1493 if (archiver != null)
1494 archiver.DearchiveRegion(filename, Guid.Empty, archiveOptions);
1495 else
1496 throw new Exception("Archiver module not present for scene");
1497  
1498 responseData["loaded"] = true;
1499 }
1500 catch (Exception e)
1501 {
1502 responseData["loaded"] = false;
1503  
1504 throw e;
1505 }
1506  
1507 m_log.Info("[RADMIN]: Load OAR Administrator Request complete");
1508 }
1509 }
1510  
1511 /// <summary>
1512 /// Save a region to an OAR file
1513 /// <summary>
1514 /// <param name="request">incoming XML RPC request</param>
1515 /// <remarks>
1516 /// XmlRpcSaveOARMethod takes the following XMLRPC
1517 /// parameters
1518 /// <list type="table">
1519 /// <listheader><term>parameter name</term><description>description</description></listheader>
1520 /// <item><term>password</term>
1521 /// <description>admin password as set in OpenSim.ini</description></item>
1522 /// <item><term>filename</term>
1523 /// <description>file name for the OAR file</description></item>
1524 /// <item><term>region_uuid</term>
1525 /// <description>UUID of the region</description></item>
1526 /// <item><term>region_name</term>
1527 /// <description>region name</description></item>
1528 /// <item><term>profile</term>
1529 /// <description>profile url</description></item>
1530 /// <item><term>noassets</term>
1531 /// <description>true if no assets should be saved</description></item>
1532 /// <item><term>all</term>
1533 /// <description>true to save all the regions in the simulator</description></item>
1534 /// <item><term>perm</term>
1535 /// <description>C and/or T</description></item>
1536 /// </list>
1537 ///
1538 /// <code>region_uuid</code> takes precedence over
1539 /// <code>region_name</code> if both are present; one of both
1540 /// must be present.
1541 ///
1542 /// XmlRpcLoadOARMethod returns
1543 /// <list type="table">
1544 /// <listheader><term>name</term><description>description</description></listheader>
1545 /// <item><term>success</term>
1546 /// <description>true or false</description></item>
1547 /// <item><term>error</term>
1548 /// <description>error message if success is false</description></item>
1549 /// </list>
1550 /// </remarks>
1551 private void XmlRpcSaveOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1552 {
1553 m_log.Info("[RADMIN]: Received Save OAR Request");
1554  
1555 Hashtable responseData = (Hashtable)response.Value;
1556 Hashtable requestData = (Hashtable)request.Params[0];
1557  
1558 try
1559 {
1560 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1561 CheckRegionParams(requestData, responseData);
1562  
1563 Scene scene = null;
1564 GetSceneFromRegionParams(requestData, responseData, out scene);
1565  
1566 string filename = (string)requestData["filename"];
1567  
1568 Dictionary<string, object> options = new Dictionary<string, object>();
1569  
1570 //if (requestData.Contains("version"))
1571 //{
1572 // options["version"] = (string)requestData["version"];
1573 //}
1574  
1575 if (requestData.Contains("home"))
1576 {
1577 options["home"] = (string)requestData["home"];
1578 }
1579  
1580 if ((string)requestData["noassets"] == "true")
1581 {
1582 options["noassets"] = (string)requestData["noassets"] ;
1583 }
1584  
1585 if (requestData.Contains("perm"))
1586 {
1587 options["checkPermissions"] = (string)requestData["perm"];
1588 }
1589  
1590 if ((string)requestData["all"] == "true")
1591 {
1592 options["all"] = (string)requestData["all"];
1593 }
1594  
1595 IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
1596  
1597 if (archiver != null)
1598 {
1599 Guid requestId = Guid.NewGuid();
1600 scene.EventManager.OnOarFileSaved += RemoteAdminOarSaveCompleted;
1601  
1602 m_log.InfoFormat(
1603 "[RADMIN]: Submitting save OAR request for {0} to file {1}, request ID {2}",
1604 scene.Name, filename, requestId);
1605  
1606 archiver.ArchiveRegion(filename, requestId, options);
1607  
1608 lock (m_saveOarLock)
1609 Monitor.Wait(m_saveOarLock,5000);
1610  
1611 scene.EventManager.OnOarFileSaved -= RemoteAdminOarSaveCompleted;
1612 }
1613 else
1614 {
1615 throw new Exception("Archiver module not present for scene");
1616 }
1617  
1618 responseData["saved"] = true;
1619 }
1620 catch (Exception e)
1621 {
1622 responseData["saved"] = false;
1623  
1624 throw e;
1625 }
1626  
1627 m_log.Info("[RADMIN]: Save OAR Request complete");
1628 }
1629  
1630 private void RemoteAdminOarSaveCompleted(Guid uuid, string name)
1631 {
1632 if (name != "")
1633 m_log.ErrorFormat("[RADMIN]: Saving of OAR file with request ID {0} failed with message {1}", uuid, name);
1634 else
1635 m_log.DebugFormat("[RADMIN]: Saved OAR file for request {0}", uuid);
1636  
1637 lock (m_saveOarLock)
1638 Monitor.Pulse(m_saveOarLock);
1639 }
1640  
1641 private void XmlRpcLoadXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1642 {
1643 m_log.Info("[RADMIN]: Received Load XML Administrator Request");
1644  
1645 Hashtable responseData = (Hashtable)response.Value;
1646 Hashtable requestData = (Hashtable)request.Params[0];
1647  
1648 lock (m_requestLock)
1649 {
1650 try
1651 {
1652 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1653 CheckRegionParams(requestData, responseData);
1654  
1655 Scene scene = null;
1656 GetSceneFromRegionParams(requestData, responseData, out scene);
1657  
1658 string filename = (string) requestData["filename"];
1659  
1660 responseData["switched"] = true;
1661  
1662 string xml_version = "1";
1663 if (requestData.Contains("xml_version"))
1664 {
1665 xml_version = (string) requestData["xml_version"];
1666 }
1667  
1668 switch (xml_version)
1669 {
1670 case "1":
1671 m_application.SceneManager.LoadCurrentSceneFromXml(filename, true, new Vector3(0, 0, 0));
1672 break;
1673  
1674 case "2":
1675 m_application.SceneManager.LoadCurrentSceneFromXml2(filename);
1676 break;
1677  
1678 default:
1679 throw new Exception(String.Format("unknown Xml{0} format", xml_version));
1680 }
1681  
1682 responseData["loaded"] = true;
1683 }
1684 catch (Exception e)
1685 {
1686 responseData["loaded"] = false;
1687 responseData["switched"] = false;
1688  
1689 throw e;
1690 }
1691  
1692 m_log.Info("[RADMIN]: Load XML Administrator Request complete");
1693 }
1694 }
1695  
1696 private void XmlRpcSaveXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1697 {
1698 m_log.Info("[RADMIN]: Received Save XML Administrator Request");
1699  
1700 Hashtable responseData = (Hashtable)response.Value;
1701 Hashtable requestData = (Hashtable)request.Params[0];
1702  
1703 try
1704 {
1705 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1706 CheckRegionParams(requestData, responseData);
1707  
1708 Scene scene = null;
1709 GetSceneFromRegionParams(requestData, responseData, out scene);
1710  
1711 string filename = (string) requestData["filename"];
1712  
1713 responseData["switched"] = true;
1714  
1715 string xml_version = "1";
1716 if (requestData.Contains("xml_version"))
1717 {
1718 xml_version = (string) requestData["xml_version"];
1719 }
1720  
1721 switch (xml_version)
1722 {
1723 case "1":
1724 m_application.SceneManager.SaveCurrentSceneToXml(filename);
1725 break;
1726  
1727 case "2":
1728 m_application.SceneManager.SaveCurrentSceneToXml2(filename);
1729 break;
1730  
1731 default:
1732 throw new Exception(String.Format("unknown Xml{0} format", xml_version));
1733 }
1734  
1735 responseData["saved"] = true;
1736 }
1737 catch (Exception e)
1738 {
1739 responseData["saved"] = false;
1740 responseData["switched"] = false;
1741  
1742 throw e;
1743 }
1744  
1745 m_log.Info("[RADMIN]: Save XML Administrator Request complete");
1746 }
1747  
1748 private void XmlRpcRegionQueryMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1749 {
1750 m_log.Info("[RADMIN]: Received Query XML Administrator Request");
1751  
1752 Hashtable responseData = (Hashtable)response.Value;
1753 Hashtable requestData = (Hashtable)request.Params[0];
1754  
1755 CheckRegionParams(requestData, responseData);
1756  
1757 Scene scene = null;
1758 GetSceneFromRegionParams(requestData, responseData, out scene);
1759  
1760 int health = scene.GetHealth();
1761 responseData["health"] = health;
1762  
1763 responseData["success"] = true;
1764 m_log.Info("[RADMIN]: Query XML Administrator Request complete");
1765 }
1766  
1767 private void XmlRpcConsoleCommandMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1768 {
1769 m_log.Info("[RADMIN]: Received Command XML Administrator Request");
1770  
1771 Hashtable responseData = (Hashtable)response.Value;
1772 Hashtable requestData = (Hashtable)request.Params[0];
1773  
1774 CheckStringParameters(requestData, responseData, new string[] {"command"});
1775  
1776 MainConsole.Instance.RunCommand(requestData["command"].ToString());
1777  
1778 m_log.Info("[RADMIN]: Command XML Administrator Request complete");
1779 }
1780  
1781 private void XmlRpcAccessListClear(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1782 {
1783 m_log.Info("[RADMIN]: Received Access List Clear Request");
1784  
1785 Hashtable responseData = (Hashtable)response.Value;
1786 Hashtable requestData = (Hashtable)request.Params[0];
1787  
1788 responseData["success"] = true;
1789  
1790 CheckRegionParams(requestData, responseData);
1791  
1792 Scene scene = null;
1793 GetSceneFromRegionParams(requestData, responseData, out scene);
1794  
1795 scene.RegionInfo.EstateSettings.EstateAccess = new UUID[]{};
1796  
1797 if (scene.RegionInfo.Persistent)
1798 m_application.EstateDataService.StoreEstateSettings(scene.RegionInfo.EstateSettings);
1799  
1800 m_log.Info("[RADMIN]: Access List Clear Request complete");
1801 }
1802  
1803 private void XmlRpcAccessListAdd(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1804 {
1805 m_log.Info("[RADMIN]: Received Access List Add Request");
1806  
1807 Hashtable responseData = (Hashtable)response.Value;
1808 Hashtable requestData = (Hashtable)request.Params[0];
1809  
1810 CheckRegionParams(requestData, responseData);
1811  
1812 Scene scene = null;
1813 GetSceneFromRegionParams(requestData, responseData, out scene);
1814  
1815 int addedUsers = 0;
1816  
1817 if (requestData.Contains("users"))
1818 {
1819 UUID scopeID = scene.RegionInfo.ScopeID;
1820 IUserAccountService userService = scene.UserAccountService;
1821 Hashtable users = (Hashtable) requestData["users"];
1822 List<UUID> uuids = new List<UUID>();
1823 foreach (string name in users.Values)
1824 {
1825 string[] parts = name.Split();
1826 UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
1827 if (account != null)
1828 {
1829 uuids.Add(account.PrincipalID);
1830 m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
1831 }
1832 }
1833 List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
1834 foreach (UUID uuid in uuids)
1835 {
1836 if (!accessControlList.Contains(uuid))
1837 {
1838 accessControlList.Add(uuid);
1839 addedUsers++;
1840 }
1841 }
1842 scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
1843 if (scene.RegionInfo.Persistent)
1844 m_application.EstateDataService.StoreEstateSettings(scene.RegionInfo.EstateSettings);
1845 }
1846  
1847 responseData["added"] = addedUsers;
1848  
1849 m_log.Info("[RADMIN]: Access List Add Request complete");
1850 }
1851  
1852 private void XmlRpcAccessListRemove(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1853 {
1854 m_log.Info("[RADMIN]: Received Access List Remove Request");
1855  
1856 Hashtable responseData = (Hashtable)response.Value;
1857 Hashtable requestData = (Hashtable)request.Params[0];
1858  
1859 CheckRegionParams(requestData, responseData);
1860  
1861 Scene scene = null;
1862 GetSceneFromRegionParams(requestData, responseData, out scene);
1863  
1864 int removedUsers = 0;
1865  
1866 if (requestData.Contains("users"))
1867 {
1868 UUID scopeID = scene.RegionInfo.ScopeID;
1869 IUserAccountService userService = scene.UserAccountService;
1870 //UserProfileCacheService ups = m_application.CommunicationsManager.UserProfileCacheService;
1871 Hashtable users = (Hashtable) requestData["users"];
1872 List<UUID> uuids = new List<UUID>();
1873 foreach (string name in users.Values)
1874 {
1875 string[] parts = name.Split();
1876 UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
1877 if (account != null)
1878 {
1879 uuids.Add(account.PrincipalID);
1880 }
1881 }
1882 List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
1883 foreach (UUID uuid in uuids)
1884 {
1885 if (accessControlList.Contains(uuid))
1886 {
1887 accessControlList.Remove(uuid);
1888 removedUsers++;
1889 }
1890 }
1891 scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
1892 if (scene.RegionInfo.Persistent)
1893 m_application.EstateDataService.StoreEstateSettings(scene.RegionInfo.EstateSettings);
1894 }
1895  
1896 responseData["removed"] = removedUsers;
1897 responseData["success"] = true;
1898  
1899 m_log.Info("[RADMIN]: Access List Remove Request complete");
1900 }
1901  
1902 private void XmlRpcAccessListList(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1903 {
1904 m_log.Info("[RADMIN]: Received Access List List Request");
1905  
1906 Hashtable responseData = (Hashtable)response.Value;
1907 Hashtable requestData = (Hashtable)request.Params[0];
1908  
1909 CheckRegionParams(requestData, responseData);
1910  
1911 Scene scene = null;
1912 GetSceneFromRegionParams(requestData, responseData, out scene);
1913  
1914 UUID[] accessControlList = scene.RegionInfo.EstateSettings.EstateAccess;
1915 Hashtable users = new Hashtable();
1916  
1917 foreach (UUID user in accessControlList)
1918 {
1919 UUID scopeID = scene.RegionInfo.ScopeID;
1920 UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, user);
1921 if (account != null)
1922 {
1923 users[user.ToString()] = account.FirstName + " " + account.LastName;
1924 }
1925 }
1926  
1927 responseData["users"] = users;
1928 responseData["success"] = true;
1929  
1930 m_log.Info("[RADMIN]: Access List List Request complete");
1931 }
1932  
1933 private void XmlRpcEstateReload(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1934 {
1935 m_log.Info("[RADMIN]: Received Estate Reload Request");
1936  
1937 Hashtable responseData = (Hashtable)response.Value;
1938 // Hashtable requestData = (Hashtable)request.Params[0];
1939  
1940 m_application.SceneManager.ForEachScene(s =>
1941 s.RegionInfo.EstateSettings = m_application.EstateDataService.LoadEstateSettings(s.RegionInfo.RegionID, false)
1942 );
1943  
1944 responseData["success"] = true;
1945  
1946 m_log.Info("[RADMIN]: Estate Reload Request complete");
1947 }
1948  
1949 private void XmlRpcGetAgentsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1950 {
1951 Hashtable responseData = (Hashtable)response.Value;
1952 Hashtable requestData = (Hashtable)request.Params[0];
1953  
1954 bool includeChildren = false;
1955  
1956 if (requestData.Contains("include_children"))
1957 bool.TryParse((string)requestData["include_children"], out includeChildren);
1958  
1959 Scene scene;
1960 GetSceneFromRegionParams(requestData, responseData, out scene);
1961  
1962 ArrayList xmlRpcRegions = new ArrayList();
1963 responseData["regions"] = xmlRpcRegions;
1964  
1965 Hashtable xmlRpcRegion = new Hashtable();
1966 xmlRpcRegions.Add(xmlRpcRegion);
1967  
1968 xmlRpcRegion["name"] = scene.Name;
1969 xmlRpcRegion["id"] = scene.RegionInfo.RegionID.ToString();
1970  
1971 List<ScenePresence> agents = scene.GetScenePresences();
1972 ArrayList xmlrpcAgents = new ArrayList();
1973  
1974 foreach (ScenePresence agent in agents)
1975 {
1976 if (agent.IsChildAgent && !includeChildren)
1977 continue;
1978  
1979 Hashtable xmlRpcAgent = new Hashtable();
1980 xmlRpcAgent.Add("name", agent.Name);
1981 xmlRpcAgent.Add("id", agent.UUID.ToString());
1982 xmlRpcAgent.Add("type", agent.PresenceType.ToString());
1983 xmlRpcAgent.Add("current_parcel_id", agent.currentParcelUUID.ToString());
1984  
1985 Vector3 pos = agent.AbsolutePosition;
1986 xmlRpcAgent.Add("pos_x", pos.X.ToString());
1987 xmlRpcAgent.Add("pos_y", pos.Y.ToString());
1988 xmlRpcAgent.Add("pos_z", pos.Z.ToString());
1989  
1990 Vector3 lookAt = agent.Lookat;
1991 xmlRpcAgent.Add("lookat_x", lookAt.X.ToString());
1992 xmlRpcAgent.Add("lookat_y", lookAt.Y.ToString());
1993 xmlRpcAgent.Add("lookat_z", lookAt.Z.ToString());
1994  
1995 Vector3 vel = agent.Velocity;
1996 xmlRpcAgent.Add("vel_x", vel.X.ToString());
1997 xmlRpcAgent.Add("vel_y", vel.Y.ToString());
1998 xmlRpcAgent.Add("vel_z", vel.Z.ToString());
1999  
2000 xmlRpcAgent.Add("is_flying", agent.Flying.ToString());
2001 xmlRpcAgent.Add("is_sat_on_ground", agent.SitGround.ToString());
2002 xmlRpcAgent.Add("is_sat_on_object", agent.IsSatOnObject.ToString());
2003  
2004 xmlrpcAgents.Add(xmlRpcAgent);
2005 }
2006  
2007 m_log.DebugFormat(
2008 "[REMOTE ADMIN]: XmlRpcGetAgents found {0} agents in {1}", xmlrpcAgents.Count, scene.Name);
2009  
2010 xmlRpcRegion["agents"] = xmlrpcAgents;
2011 responseData["success"] = true;
2012 }
2013  
2014 private void XmlRpcTeleportAgentMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
2015 {
2016 Hashtable responseData = (Hashtable)response.Value;
2017 Hashtable requestData = (Hashtable)request.Params[0];
2018  
2019 UUID agentId;
2020 string regionName = null;
2021 Vector3 pos, lookAt;
2022 ScenePresence sp = null;
2023  
2024 if (requestData.Contains("agent_first_name") && requestData.Contains("agent_last_name"))
2025 {
2026 string firstName = requestData["agent_first_name"].ToString();
2027 string lastName = requestData["agent_last_name"].ToString();
2028 m_application.SceneManager.TryGetRootScenePresenceByName(firstName, lastName, out sp);
2029  
2030 if (sp == null)
2031 throw new Exception(
2032 string.Format(
2033 "No agent found with agent_first_name {0} and agent_last_name {1}", firstName, lastName));
2034 }
2035 else if (requestData.Contains("agent_id"))
2036 {
2037 string rawAgentId = (string)requestData["agent_id"];
2038  
2039 if (!UUID.TryParse(rawAgentId, out agentId))
2040 throw new Exception(string.Format("agent_id {0} does not have the correct id format", rawAgentId));
2041  
2042 m_application.SceneManager.TryGetRootScenePresence(agentId, out sp);
2043  
2044 if (sp == null)
2045 throw new Exception(string.Format("No agent with agent_id {0} found in this simulator", agentId));
2046 }
2047 else
2048 {
2049 throw new Exception("No agent_id or agent_first_name and agent_last_name parameters specified");
2050 }
2051  
2052 if (requestData.Contains("region_name"))
2053 regionName = (string)requestData["region_name"];
2054  
2055 pos.X = ParseFloat(requestData, "pos_x", sp.AbsolutePosition.X);
2056 pos.Y = ParseFloat(requestData, "pos_y", sp.AbsolutePosition.Y);
2057 pos.Z = ParseFloat(requestData, "pos_z", sp.AbsolutePosition.Z);
2058 lookAt.X = ParseFloat(requestData, "lookat_x", sp.Lookat.X);
2059 lookAt.Y = ParseFloat(requestData, "lookat_y", sp.Lookat.Y);
2060 lookAt.Z = ParseFloat(requestData, "lookat_z", sp.Lookat.Z);
2061  
2062 sp.Scene.RequestTeleportLocation(
2063 sp.ControllingClient, regionName, pos, lookAt, (uint)Constants.TeleportFlags.ViaLocation);
2064  
2065 // We have no way of telling the failure of the actual teleport
2066 responseData["success"] = true;
2067 }
2068  
2069 private void XmlRpcResetLand(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
2070 {
2071 Hashtable requestData = (Hashtable)request.Params[0];
2072 Hashtable responseData = (Hashtable)response.Value;
2073  
2074 string musicURL = string.Empty;
2075 UUID groupID = UUID.Zero;
2076 uint flags = 0;
2077 bool set_group = false, set_music = false, set_flags = false;
2078  
2079 if (requestData.Contains("group") && requestData["group"] != null)
2080 set_group = UUID.TryParse(requestData["group"].ToString(), out groupID);
2081 if (requestData.Contains("music") && requestData["music"] != null)
2082 {
2083 musicURL = requestData["music"].ToString();
2084 set_music = true;
2085 }
2086 if (requestData.Contains("flags") && requestData["flags"] != null)
2087 set_flags = UInt32.TryParse(requestData["flags"].ToString(), out flags);
2088  
2089 m_log.InfoFormat("[RADMIN]: Received Reset Land Request group={0} musicURL={1} flags={2}",
2090 (set_group ? groupID.ToString() : "unchanged"),
2091 (set_music ? musicURL : "unchanged"),
2092 (set_flags ? flags.ToString() : "unchanged"));
2093  
2094 m_application.SceneManager.ForEachScene(delegate(Scene s)
2095 {
2096 List<ILandObject> parcels = s.LandChannel.AllParcels();
2097 foreach (ILandObject p in parcels)
2098 {
2099 if (set_music)
2100 p.LandData.MusicURL = musicURL;
2101  
2102 if (set_group)
2103 p.LandData.GroupID = groupID;
2104  
2105 if (set_flags)
2106 p.LandData.Flags = flags;
2107  
2108 s.LandChannel.UpdateLandObject(p.LandData.LocalID, p.LandData);
2109 }
2110 }
2111 );
2112  
2113 responseData["success"] = true;
2114  
2115 m_log.Info("[RADMIN]: Reset Land Request complete");
2116 }
2117  
2118  
2119 /// <summary>
2120 /// Parse a float with the given parameter name from a request data hash table.
2121 /// </summary>
2122 /// <remarks>
2123 /// Will throw an exception if parameter is not a float.
2124 /// Will not throw if parameter is not found, passes back default value instead.
2125 /// </remarks>
2126 /// <param name="requestData"></param>
2127 /// <param name="paramName"></param>
2128 /// <param name="defaultVal"></param>
2129 /// <returns></returns>
2130 private static float ParseFloat(Hashtable requestData, string paramName, float defaultVal)
2131 {
2132 if (requestData.Contains(paramName))
2133 {
2134 string rawVal = (string)requestData[paramName];
2135 float val;
2136  
2137 if (!float.TryParse(rawVal, out val))
2138 throw new Exception(string.Format("{0} {1} is not a valid float", paramName, rawVal));
2139 else
2140 return val;
2141 }
2142 else
2143 {
2144 return defaultVal;
2145 }
2146 }
2147  
2148 private static void CheckStringParameters(Hashtable requestData, Hashtable responseData, string[] param)
2149 {
2150 foreach (string parameter in param)
2151 {
2152 if (!requestData.Contains(parameter))
2153 {
2154 responseData["accepted"] = false;
2155 throw new Exception(String.Format("missing string parameter {0}", parameter));
2156 }
2157 if (String.IsNullOrEmpty((string) requestData[parameter]))
2158 {
2159 responseData["accepted"] = false;
2160 throw new Exception(String.Format("parameter {0} is empty", parameter));
2161 }
2162 }
2163 }
2164  
2165 private static void CheckIntegerParams(Hashtable requestData, Hashtable responseData, string[] param)
2166 {
2167 foreach (string parameter in param)
2168 {
2169 if (!requestData.Contains(parameter))
2170 {
2171 responseData["accepted"] = false;
2172 throw new Exception(String.Format("missing integer parameter {0}", parameter));
2173 }
2174 }
2175 }
2176  
2177 private void CheckRegionParams(Hashtable requestData, Hashtable responseData)
2178 {
2179 //Checks if region parameters exist and gives exeption if no parameters are given
2180 if ((requestData.ContainsKey("region_id") && !String.IsNullOrEmpty((string)requestData["region_id"])) ||
2181 (requestData.ContainsKey("region_name") && !String.IsNullOrEmpty((string)requestData["region_name"])))
2182 {
2183 return;
2184 }
2185 else
2186 {
2187 responseData["accepted"] = false;
2188 throw new Exception("no region_name or region_id given");
2189 }
2190 }
2191  
2192 private void GetSceneFromRegionParams(Hashtable requestData, Hashtable responseData, out Scene scene)
2193 {
2194 scene = null;
2195  
2196 if (requestData.ContainsKey("region_id") &&
2197 !String.IsNullOrEmpty((string)requestData["region_id"]))
2198 {
2199 UUID regionID = (UUID)(string)requestData["region_id"];
2200 if (!m_application.SceneManager.TryGetScene(regionID, out scene))
2201 {
2202 responseData["error"] = String.Format("Region ID {0} not found", regionID);
2203 throw new Exception(String.Format("Region ID {0} not found", regionID));
2204 }
2205 }
2206 else if (requestData.ContainsKey("region_name") &&
2207 !String.IsNullOrEmpty((string)requestData["region_name"]))
2208 {
2209 string regionName = (string)requestData["region_name"];
2210 if (!m_application.SceneManager.TryGetScene(regionName, out scene))
2211 {
2212 responseData["error"] = String.Format("Region {0} not found", regionName);
2213 throw new Exception(String.Format("Region {0} not found", regionName));
2214 }
2215 }
2216 else
2217 {
2218 responseData["error"] = "no region_name or region_id given";
2219 throw new Exception("no region_name or region_id given");
2220 }
2221 return;
2222 }
2223  
2224 private bool GetBoolean(Hashtable requestData, string tag, bool defaultValue)
2225 {
2226 // If an access value has been provided, apply it.
2227 if (requestData.Contains(tag))
2228 {
2229 switch (((string)requestData[tag]).ToLower())
2230 {
2231 case "true" :
2232 case "t" :
2233 case "1" :
2234 return true;
2235 case "false" :
2236 case "f" :
2237 case "0" :
2238 return false;
2239 default :
2240 return defaultValue;
2241 }
2242 }
2243 else
2244 return defaultValue;
2245 }
2246  
2247 private int GetIntegerAttribute(XmlNode node, string attribute, int defaultValue)
2248 {
2249 try { return Convert.ToInt32(node.Attributes[attribute].Value); } catch{}
2250 return defaultValue;
2251 }
2252  
2253 private uint GetUnsignedAttribute(XmlNode node, string attribute, uint defaultValue)
2254 {
2255 try { return Convert.ToUInt32(node.Attributes[attribute].Value); } catch{}
2256 return defaultValue;
2257 }
2258  
2259 private string GetStringAttribute(XmlNode node, string attribute, string defaultValue)
2260 {
2261 try { return node.Attributes[attribute].Value; } catch{}
2262 return defaultValue;
2263 }
2264  
2265 public void Dispose()
2266 {
2267 }
2268  
2269 /// <summary>
2270 /// Create a user
2271 /// </summary>
2272 /// <param name="scopeID"></param>
2273 /// <param name="firstName"></param>
2274 /// <param name="lastName"></param>
2275 /// <param name="password"></param>
2276 /// <param name="email"></param>
2277 private UserAccount CreateUser(UUID scopeID, string firstName, string lastName, string password, string email)
2278 {
2279 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2280 IUserAccountService userAccountService = scene.UserAccountService;
2281 IGridService gridService = scene.GridService;
2282 IAuthenticationService authenticationService = scene.AuthenticationService;
2283 IGridUserService gridUserService = scene.GridUserService;
2284 IInventoryService inventoryService = scene.InventoryService;
2285  
2286 UserAccount account = userAccountService.GetUserAccount(scopeID, firstName, lastName);
2287 if (null == account)
2288 {
2289 account = new UserAccount(scopeID, UUID.Random(), firstName, lastName, email);
2290 if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
2291 {
2292 account.ServiceURLs = new Dictionary<string, object>();
2293 account.ServiceURLs["HomeURI"] = string.Empty;
2294 account.ServiceURLs["InventoryServerURI"] = string.Empty;
2295 account.ServiceURLs["AssetServerURI"] = string.Empty;
2296 }
2297  
2298 if (userAccountService.StoreUserAccount(account))
2299 {
2300 bool success;
2301 if (authenticationService != null)
2302 {
2303 success = authenticationService.SetPassword(account.PrincipalID, password);
2304 if (!success)
2305 m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
2306 firstName, lastName);
2307 }
2308  
2309 GridRegion home = null;
2310 if (gridService != null)
2311 {
2312 List<GridRegion> defaultRegions = gridService.GetDefaultRegions(UUID.Zero);
2313 if (defaultRegions != null && defaultRegions.Count >= 1)
2314 home = defaultRegions[0];
2315  
2316 if (gridUserService != null && home != null)
2317 gridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
2318 else
2319 m_log.WarnFormat("[RADMIN]: Unable to set home for account {0} {1}.",
2320 firstName, lastName);
2321 }
2322 else
2323 m_log.WarnFormat("[RADMIN]: Unable to retrieve home region for account {0} {1}.",
2324 firstName, lastName);
2325  
2326 if (inventoryService != null)
2327 {
2328 success = inventoryService.CreateUserInventory(account.PrincipalID);
2329 if (!success)
2330 m_log.WarnFormat("[RADMIN]: Unable to create inventory for account {0} {1}.",
2331 firstName, lastName);
2332 }
2333  
2334 m_log.InfoFormat("[RADMIN]: Account {0} {1} created successfully", firstName, lastName);
2335 return account;
2336 } else {
2337 m_log.ErrorFormat("[RADMIN]: Account creation failed for account {0} {1}", firstName, lastName);
2338 }
2339 }
2340 else
2341 {
2342 m_log.ErrorFormat("[RADMIN]: A user with the name {0} {1} already exists!", firstName, lastName);
2343 }
2344 return null;
2345 }
2346  
2347 /// <summary>
2348 /// Change password
2349 /// </summary>
2350 /// <param name="firstName"></param>
2351 /// <param name="lastName"></param>
2352 /// <param name="password"></param>
2353 private bool ChangeUserPassword(string firstName, string lastName, string password)
2354 {
2355 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2356 IUserAccountService userAccountService = scene.UserAccountService;
2357 IAuthenticationService authenticationService = scene.AuthenticationService;
2358  
2359 UserAccount account = userAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
2360 if (null != account)
2361 {
2362 bool success = false;
2363 if (authenticationService != null)
2364 success = authenticationService.SetPassword(account.PrincipalID, password);
2365  
2366 if (!success)
2367 {
2368 m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
2369 firstName, lastName);
2370 return false;
2371 }
2372 return true;
2373 }
2374 else
2375 {
2376 m_log.ErrorFormat("[RADMIN]: No such user");
2377 return false;
2378 }
2379 }
2380  
2381 private bool LoadHeightmap(string file, UUID regionID)
2382 {
2383 m_log.InfoFormat("[RADMIN]: Terrain Loading: {0}", file);
2384  
2385 Scene region = null;
2386  
2387 if (!m_application.SceneManager.TryGetScene(regionID, out region))
2388 {
2389 m_log.InfoFormat("[RADMIN]: unable to get a scene with that name: {0}", regionID.ToString());
2390 return false;
2391 }
2392  
2393 ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
2394 if (null == terrainModule) throw new Exception("terrain module not available");
2395 if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
2396 {
2397 m_log.Info("[RADMIN]: Terrain path is URL");
2398 Uri result;
2399 if (Uri.TryCreate(file, UriKind.RelativeOrAbsolute, out result))
2400 {
2401 // the url is valid
2402 string fileType = file.Substring(file.LastIndexOf('/') + 1);
2403 terrainModule.LoadFromStream(fileType, result);
2404 }
2405 }
2406 else
2407 {
2408 terrainModule.LoadFromFile(file);
2409 }
2410  
2411 m_log.Info("[RADMIN]: Load height maps request complete");
2412  
2413 return true;
2414 }
2415  
2416  
2417 /// <summary>
2418 /// This method is called by the user-create and user-modify methods to establish
2419 /// or change, the user's appearance. Default avatar names can be specified via
2420 /// the config file, but must correspond to avatars in the default appearance
2421 /// file, or pre-existing in the user database.
2422 /// This should probably get moved into somewhere more core eventually.
2423 /// </summary>
2424 private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
2425 {
2426 m_log.DebugFormat("[RADMIN]: updateUserAppearance");
2427  
2428 string defaultMale = m_config.GetString("default_male", "Default Male");
2429 string defaultFemale = m_config.GetString("default_female", "Default Female");
2430 string defaultNeutral = m_config.GetString("default_female", "Default Default");
2431 string model = String.Empty;
2432  
2433 // Has a gender preference been supplied?
2434  
2435 if (requestData.Contains("gender"))
2436 {
2437 switch ((string)requestData["gender"])
2438 {
2439 case "m" :
2440 case "male" :
2441 model = defaultMale;
2442 break;
2443 case "f" :
2444 case "female" :
2445 model = defaultFemale;
2446 break;
2447 case "n" :
2448 case "neutral" :
2449 default :
2450 model = defaultNeutral;
2451 break;
2452 }
2453 }
2454  
2455 // Has an explicit model been specified?
2456  
2457 if (requestData.Contains("model") && (String.IsNullOrEmpty((string)requestData["gender"])))
2458 {
2459 model = (string)requestData["model"];
2460 }
2461  
2462 // No appearance attributes were set
2463  
2464 if (String.IsNullOrEmpty(model))
2465 {
2466 m_log.DebugFormat("[RADMIN]: Appearance update not requested");
2467 return;
2468 }
2469  
2470 m_log.DebugFormat("[RADMIN]: Setting appearance for avatar {0}, using model <{1}>", userid, model);
2471  
2472 string[] modelSpecifiers = model.Split();
2473 if (modelSpecifiers.Length != 2)
2474 {
2475 m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
2476 // modelSpecifiers = dmodel.Split();
2477 return;
2478 }
2479  
2480 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2481 UUID scopeID = scene.RegionInfo.ScopeID;
2482 UserAccount modelProfile = scene.UserAccountService.GetUserAccount(scopeID, modelSpecifiers[0], modelSpecifiers[1]);
2483  
2484 if (modelProfile == null)
2485 {
2486 m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model);
2487 return;
2488 }
2489  
2490 // Set current user's appearance. This bit is easy. The appearance structure is populated with
2491 // actual asset ids, however to complete the magic we need to populate the inventory with the
2492 // assets in question.
2493  
2494 EstablishAppearance(userid, modelProfile.PrincipalID);
2495  
2496 m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}",
2497 userid, model);
2498 }
2499  
2500 /// <summary>
2501 /// This method is called by updateAvatarAppearance once any specified model has been
2502 /// ratified, or an appropriate default value has been adopted. The intended prototype
2503 /// is known to exist, as is the target avatar.
2504 /// </summary>
2505 private void EstablishAppearance(UUID destination, UUID source)
2506 {
2507 m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source);
2508 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2509  
2510 // If the model has no associated appearance we're done.
2511 AvatarAppearance avatarAppearance = scene.AvatarService.GetAppearance(source);
2512 if (avatarAppearance == null)
2513 return;
2514  
2515 // Simple appearance copy or copy Clothing and Bodyparts folders?
2516 bool copyFolders = m_config.GetBoolean("copy_folders", false);
2517  
2518 if (!copyFolders)
2519 {
2520 // Simple copy of wearables and appearance update
2521 try
2522 {
2523 CopyWearablesAndAttachments(destination, source, avatarAppearance);
2524  
2525 scene.AvatarService.SetAppearance(destination, avatarAppearance);
2526 }
2527 catch (Exception e)
2528 {
2529 m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
2530 destination, e.Message);
2531 }
2532  
2533 return;
2534 }
2535  
2536 // Copy Clothing and Bodypart folders and appearance update
2537 try
2538 {
2539 Dictionary<UUID,UUID> inventoryMap = new Dictionary<UUID,UUID>();
2540 CopyInventoryFolders(destination, source, AssetType.Clothing, inventoryMap, avatarAppearance);
2541 CopyInventoryFolders(destination, source, AssetType.Bodypart, inventoryMap, avatarAppearance);
2542  
2543 AvatarWearable[] wearables = avatarAppearance.Wearables;
2544  
2545 for (int i=0; i<wearables.Length; i++)
2546 {
2547 if (inventoryMap.ContainsKey(wearables[i][0].ItemID))
2548 {
2549 AvatarWearable wearable = new AvatarWearable();
2550 wearable.Wear(inventoryMap[wearables[i][0].ItemID],
2551 wearables[i][0].AssetID);
2552 avatarAppearance.SetWearable(i, wearable);
2553 }
2554 }
2555  
2556 scene.AvatarService.SetAppearance(destination, avatarAppearance);
2557 }
2558 catch (Exception e)
2559 {
2560 m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
2561 destination, e.Message);
2562 }
2563  
2564 return;
2565 }
2566  
2567 /// <summary>
2568 /// This method is called by establishAppearance to do a copy all inventory items
2569 /// worn or attached to the Clothing inventory folder of the receiving avatar.
2570 /// In parallel the avatar wearables and attachments are updated.
2571 /// </summary>
2572 private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance)
2573 {
2574 IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
2575  
2576 // Get Clothing folder of receiver
2577 InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, AssetType.Clothing);
2578  
2579 if (destinationFolder == null)
2580 throw new Exception("Cannot locate folder(s)");
2581  
2582 // Missing destination folder? This should *never* be the case
2583 if (destinationFolder.Type != (short)AssetType.Clothing)
2584 {
2585 destinationFolder = new InventoryFolderBase();
2586  
2587 destinationFolder.ID = UUID.Random();
2588 destinationFolder.Name = "Clothing";
2589 destinationFolder.Owner = destination;
2590 destinationFolder.Type = (short)AssetType.Clothing;
2591 destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
2592 destinationFolder.Version = 1;
2593 inventoryService.AddFolder(destinationFolder); // store base record
2594 m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
2595 }
2596  
2597 // Wearables
2598 AvatarWearable[] wearables = avatarAppearance.Wearables;
2599 AvatarWearable wearable;
2600  
2601 for (int i = 0; i<wearables.Length; i++)
2602 {
2603 wearable = wearables[i];
2604 if (wearable[0].ItemID != UUID.Zero)
2605 {
2606 // Get inventory item and copy it
2607 InventoryItemBase item = new InventoryItemBase(wearable[0].ItemID, source);
2608 item = inventoryService.GetItem(item);
2609  
2610 if (item != null)
2611 {
2612 InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
2613 destinationItem.Name = item.Name;
2614 destinationItem.Owner = destination;
2615 destinationItem.Description = item.Description;
2616 destinationItem.InvType = item.InvType;
2617 destinationItem.CreatorId = item.CreatorId;
2618 destinationItem.CreatorData = item.CreatorData;
2619 destinationItem.NextPermissions = item.NextPermissions;
2620 destinationItem.CurrentPermissions = item.CurrentPermissions;
2621 destinationItem.BasePermissions = item.BasePermissions;
2622 destinationItem.EveryOnePermissions = item.EveryOnePermissions;
2623 destinationItem.GroupPermissions = item.GroupPermissions;
2624 destinationItem.AssetType = item.AssetType;
2625 destinationItem.AssetID = item.AssetID;
2626 destinationItem.GroupID = item.GroupID;
2627 destinationItem.GroupOwned = item.GroupOwned;
2628 destinationItem.SalePrice = item.SalePrice;
2629 destinationItem.SaleType = item.SaleType;
2630 destinationItem.Flags = item.Flags;
2631 destinationItem.CreationDate = item.CreationDate;
2632 destinationItem.Folder = destinationFolder.ID;
2633 ApplyNextOwnerPermissions(destinationItem);
2634  
2635 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
2636 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
2637  
2638 // Wear item
2639 AvatarWearable newWearable = new AvatarWearable();
2640 newWearable.Wear(destinationItem.ID, wearable[0].AssetID);
2641 avatarAppearance.SetWearable(i, newWearable);
2642 }
2643 else
2644 {
2645 m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", wearable[0].ItemID, destinationFolder.ID);
2646 }
2647 }
2648 }
2649  
2650 // Attachments
2651 List<AvatarAttachment> attachments = avatarAppearance.GetAttachments();
2652  
2653 foreach (AvatarAttachment attachment in attachments)
2654 {
2655 int attachpoint = attachment.AttachPoint;
2656 UUID itemID = attachment.ItemID;
2657  
2658 if (itemID != UUID.Zero)
2659 {
2660 // Get inventory item and copy it
2661 InventoryItemBase item = new InventoryItemBase(itemID, source);
2662 item = inventoryService.GetItem(item);
2663  
2664 if (item != null)
2665 {
2666 InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
2667 destinationItem.Name = item.Name;
2668 destinationItem.Owner = destination;
2669 destinationItem.Description = item.Description;
2670 destinationItem.InvType = item.InvType;
2671 destinationItem.CreatorId = item.CreatorId;
2672 destinationItem.CreatorData = item.CreatorData;
2673 destinationItem.NextPermissions = item.NextPermissions;
2674 destinationItem.CurrentPermissions = item.CurrentPermissions;
2675 destinationItem.BasePermissions = item.BasePermissions;
2676 destinationItem.EveryOnePermissions = item.EveryOnePermissions;
2677 destinationItem.GroupPermissions = item.GroupPermissions;
2678 destinationItem.AssetType = item.AssetType;
2679 destinationItem.AssetID = item.AssetID;
2680 destinationItem.GroupID = item.GroupID;
2681 destinationItem.GroupOwned = item.GroupOwned;
2682 destinationItem.SalePrice = item.SalePrice;
2683 destinationItem.SaleType = item.SaleType;
2684 destinationItem.Flags = item.Flags;
2685 destinationItem.CreationDate = item.CreationDate;
2686 destinationItem.Folder = destinationFolder.ID;
2687 ApplyNextOwnerPermissions(destinationItem);
2688  
2689 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
2690 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
2691  
2692 // Attach item
2693 avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
2694 m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
2695 }
2696 else
2697 {
2698 m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", itemID, destinationFolder.ID);
2699 }
2700 }
2701 }
2702 }
2703  
2704 /// <summary>
2705 /// This method is called by establishAppearance to copy inventory folders to make
2706 /// copies of Clothing and Bodyparts inventory folders and attaches worn attachments
2707 /// </summary>
2708 private void CopyInventoryFolders(UUID destination, UUID source, AssetType assetType, Dictionary<UUID,UUID> inventoryMap,
2709 AvatarAppearance avatarAppearance)
2710 {
2711 IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
2712  
2713 InventoryFolderBase sourceFolder = inventoryService.GetFolderForType(source, assetType);
2714 InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, assetType);
2715  
2716 if (sourceFolder == null || destinationFolder == null)
2717 throw new Exception("Cannot locate folder(s)");
2718  
2719 // Missing source folder? This should *never* be the case
2720 if (sourceFolder.Type != (short)assetType)
2721 {
2722 sourceFolder = new InventoryFolderBase();
2723 sourceFolder.ID = UUID.Random();
2724 if (assetType == AssetType.Clothing) {
2725 sourceFolder.Name = "Clothing";
2726 } else {
2727 sourceFolder.Name = "Body Parts";
2728 }
2729 sourceFolder.Owner = source;
2730 sourceFolder.Type = (short)assetType;
2731 sourceFolder.ParentID = inventoryService.GetRootFolder(source).ID;
2732 sourceFolder.Version = 1;
2733 inventoryService.AddFolder(sourceFolder); // store base record
2734 m_log.ErrorFormat("[RADMIN] Created folder for source {0}", source);
2735 }
2736  
2737 // Missing destination folder? This should *never* be the case
2738 if (destinationFolder.Type != (short)assetType)
2739 {
2740 destinationFolder = new InventoryFolderBase();
2741 destinationFolder.ID = UUID.Random();
2742 if (assetType == AssetType.Clothing)
2743 {
2744 destinationFolder.Name = "Clothing";
2745 }
2746 else
2747 {
2748 destinationFolder.Name = "Body Parts";
2749 }
2750 destinationFolder.Owner = destination;
2751 destinationFolder.Type = (short)assetType;
2752 destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
2753 destinationFolder.Version = 1;
2754 inventoryService.AddFolder(destinationFolder); // store base record
2755 m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
2756 }
2757  
2758 InventoryFolderBase extraFolder;
2759 List<InventoryFolderBase> folders = inventoryService.GetFolderContent(source, sourceFolder.ID).Folders;
2760  
2761 foreach (InventoryFolderBase folder in folders)
2762 {
2763 extraFolder = new InventoryFolderBase();
2764 extraFolder.ID = UUID.Random();
2765 extraFolder.Name = folder.Name;
2766 extraFolder.Owner = destination;
2767 extraFolder.Type = folder.Type;
2768 extraFolder.Version = folder.Version;
2769 extraFolder.ParentID = destinationFolder.ID;
2770 inventoryService.AddFolder(extraFolder);
2771  
2772 m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);
2773  
2774 List<InventoryItemBase> items = inventoryService.GetFolderContent(source, folder.ID).Items;
2775  
2776 foreach (InventoryItemBase item in items)
2777 {
2778 InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
2779 destinationItem.Name = item.Name;
2780 destinationItem.Owner = destination;
2781 destinationItem.Description = item.Description;
2782 destinationItem.InvType = item.InvType;
2783 destinationItem.CreatorId = item.CreatorId;
2784 destinationItem.CreatorData = item.CreatorData;
2785 destinationItem.NextPermissions = item.NextPermissions;
2786 destinationItem.CurrentPermissions = item.CurrentPermissions;
2787 destinationItem.BasePermissions = item.BasePermissions;
2788 destinationItem.EveryOnePermissions = item.EveryOnePermissions;
2789 destinationItem.GroupPermissions = item.GroupPermissions;
2790 destinationItem.AssetType = item.AssetType;
2791 destinationItem.AssetID = item.AssetID;
2792 destinationItem.GroupID = item.GroupID;
2793 destinationItem.GroupOwned = item.GroupOwned;
2794 destinationItem.SalePrice = item.SalePrice;
2795 destinationItem.SaleType = item.SaleType;
2796 destinationItem.Flags = item.Flags;
2797 destinationItem.CreationDate = item.CreationDate;
2798 destinationItem.Folder = extraFolder.ID;
2799 ApplyNextOwnerPermissions(destinationItem);
2800  
2801 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
2802 inventoryMap.Add(item.ID, destinationItem.ID);
2803 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, extraFolder.ID);
2804  
2805 // Attach item, if original is attached
2806 int attachpoint = avatarAppearance.GetAttachpoint(item.ID);
2807 if (attachpoint != 0)
2808 {
2809 avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
2810 m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
2811 }
2812 }
2813 }
2814 }
2815  
2816 /// <summary>
2817 /// Apply next owner permissions.
2818 /// </summary>
2819 private void ApplyNextOwnerPermissions(InventoryItemBase item)
2820 {
2821 if (item.InvType == (int)InventoryType.Object)
2822 {
2823 uint perms = item.CurrentPermissions;
2824 PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref perms);
2825 item.CurrentPermissions = perms;
2826 }
2827  
2828 item.CurrentPermissions &= item.NextPermissions;
2829 item.BasePermissions &= item.NextPermissions;
2830 item.EveryOnePermissions &= item.NextPermissions;
2831 // item.OwnerChanged = true;
2832 // item.PermsMask = 0;
2833 // item.PermsGranter = UUID.Zero;
2834 }
2835  
2836 /// <summary>
2837 /// This method is called if a given model avatar name can not be found. If the external
2838 /// file has already been loaded once, then control returns immediately. If not, then it
2839 /// looks for a default appearance file. This file contains XML definitions of zero or more named
2840 /// avatars, each avatar can specify zero or more "outfits". Each outfit is a collection
2841 /// of items that together, define a particular ensemble for the avatar. Each avatar should
2842 /// indicate which outfit is the default, and this outfit will be automatically worn. The
2843 /// other outfits are provided to allow "real" avatars a way to easily change their outfits.
2844 /// </summary>
2845 private bool CreateDefaultAvatars()
2846 {
2847 // Only load once
2848 if (m_defaultAvatarsLoaded)
2849 {
2850 return false;
2851 }
2852  
2853 m_log.DebugFormat("[RADMIN]: Creating default avatar entries");
2854  
2855 m_defaultAvatarsLoaded = true;
2856  
2857 // Load processing starts here...
2858  
2859 try
2860 {
2861 string defaultAppearanceFileName = null;
2862  
2863 //m_config may be null if RemoteAdmin configuration secition is missing or disabled in OpenSim.ini
2864 if (m_config != null)
2865 {
2866 defaultAppearanceFileName = m_config.GetString("default_appearance", "default_appearance.xml");
2867 }
2868  
2869 if (File.Exists(defaultAppearanceFileName))
2870 {
2871 XmlDocument doc = new XmlDocument();
2872 string name = "*unknown*";
2873 string email = "anon@anon";
2874 uint regionXLocation = 1000;
2875 uint regionYLocation = 1000;
2876 string password = UUID.Random().ToString(); // No requirement to sign-in.
2877 UUID ID = UUID.Zero;
2878 AvatarAppearance avatarAppearance;
2879 XmlNodeList avatars;
2880 XmlNodeList assets;
2881 XmlNode perms = null;
2882 bool include = false;
2883 bool select = false;
2884  
2885 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2886 IInventoryService inventoryService = scene.InventoryService;
2887 IAssetService assetService = scene.AssetService;
2888  
2889 doc.LoadXml(File.ReadAllText(defaultAppearanceFileName));
2890  
2891 // Load up any included assets. Duplicates will be ignored
2892 assets = doc.GetElementsByTagName("RequiredAsset");
2893 foreach (XmlNode assetNode in assets)
2894 {
2895 AssetBase asset = new AssetBase(UUID.Random(), GetStringAttribute(assetNode, "name", ""), SByte.Parse(GetStringAttribute(assetNode, "type", "")), UUID.Zero.ToString());
2896 asset.Description = GetStringAttribute(assetNode,"desc","");
2897 asset.Local = Boolean.Parse(GetStringAttribute(assetNode,"local",""));
2898 asset.Temporary = Boolean.Parse(GetStringAttribute(assetNode,"temporary",""));
2899 asset.Data = Convert.FromBase64String(assetNode.InnerText);
2900 assetService.Store(asset);
2901 }
2902  
2903 avatars = doc.GetElementsByTagName("Avatar");
2904  
2905 // The document may contain multiple avatars
2906  
2907 foreach (XmlElement avatar in avatars)
2908 {
2909 m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}",
2910 GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?"));
2911  
2912 // Create the user identified by the avatar entry
2913  
2914 try
2915 {
2916 // Only the name value is mandatory
2917 name = GetStringAttribute(avatar,"name",name);
2918 email = GetStringAttribute(avatar,"email",email);
2919 regionXLocation = GetUnsignedAttribute(avatar,"regx",regionXLocation);
2920 regionYLocation = GetUnsignedAttribute(avatar,"regy",regionYLocation);
2921 password = GetStringAttribute(avatar,"password",password);
2922  
2923 string[] names = name.Split();
2924 UUID scopeID = scene.RegionInfo.ScopeID;
2925 UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, names[0], names[1]);
2926 if (null == account)
2927 {
2928 account = CreateUser(scopeID, names[0], names[1], password, email);
2929 if (null == account)
2930 {
2931 m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]);
2932 return false;
2933 }
2934 }
2935  
2936 // Set home position
2937  
2938 GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
2939 (int)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
2940 if (null == home) {
2941 m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", names[0], names[1]);
2942 } else {
2943 scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
2944 m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, names[0], names[1]);
2945 }
2946  
2947 ID = account.PrincipalID;
2948  
2949 m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID);
2950 include = true;
2951 }
2952 catch (Exception e)
2953 {
2954 m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message);
2955 include = false;
2956 }
2957  
2958 // OK, User has been created OK, now we can install the inventory.
2959 // First retrieve the current inventory (the user may already exist)
2960 // Note that althought he inventory is retrieved, the hierarchy has
2961 // not been interpreted at all.
2962  
2963 if (include)
2964 {
2965 // Setup for appearance processing
2966 avatarAppearance = scene.AvatarService.GetAppearance(ID);
2967 if (avatarAppearance == null)
2968 avatarAppearance = new AvatarAppearance();
2969  
2970 AvatarWearable[] wearables = avatarAppearance.Wearables;
2971 for (int i=0; i<wearables.Length; i++)
2972 {
2973 wearables[i] = new AvatarWearable();
2974 }
2975  
2976 try
2977 {
2978 // m_log.DebugFormat("[RADMIN] {0} folders, {1} items in inventory",
2979 // uic.folders.Count, uic.items.Count);
2980  
2981 InventoryFolderBase clothingFolder = inventoryService.GetFolderForType(ID, AssetType.Clothing);
2982  
2983 // This should *never* be the case
2984 if (clothingFolder == null || clothingFolder.Type != (short)AssetType.Clothing)
2985 {
2986 clothingFolder = new InventoryFolderBase();
2987 clothingFolder.ID = UUID.Random();
2988 clothingFolder.Name = "Clothing";
2989 clothingFolder.Owner = ID;
2990 clothingFolder.Type = (short)AssetType.Clothing;
2991 clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID;
2992 clothingFolder.Version = 1;
2993 inventoryService.AddFolder(clothingFolder); // store base record
2994 m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID);
2995 }
2996  
2997 // OK, now we have an inventory for the user, read in the outfits from the
2998 // default appearance XMl file.
2999  
3000 XmlNodeList outfits = avatar.GetElementsByTagName("Ensemble");
3001 InventoryFolderBase extraFolder;
3002 string outfitName;
3003 UUID assetid;
3004  
3005 foreach (XmlElement outfit in outfits)
3006 {
3007 m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}",
3008 GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?"));
3009  
3010 outfitName = GetStringAttribute(outfit,"name","");
3011 select = (GetStringAttribute(outfit,"default","no") == "yes");
3012  
3013 // If the folder already exists, re-use it. The defaults may
3014 // change over time. Augment only.
3015  
3016 List<InventoryFolderBase> folders = inventoryService.GetFolderContent(ID, clothingFolder.ID).Folders;
3017 extraFolder = null;
3018  
3019 foreach (InventoryFolderBase folder in folders)
3020 {
3021 if (folder.Name == outfitName)
3022 {
3023 extraFolder = folder;
3024 break;
3025 }
3026 }
3027  
3028 // Otherwise, we must create the folder.
3029 if (extraFolder == null)
3030 {
3031 m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name);
3032 extraFolder = new InventoryFolderBase();
3033 extraFolder.ID = UUID.Random();
3034 extraFolder.Name = outfitName;
3035 extraFolder.Owner = ID;
3036 extraFolder.Type = (short)AssetType.Clothing;
3037 extraFolder.Version = 1;
3038 extraFolder.ParentID = clothingFolder.ID;
3039 inventoryService.AddFolder(extraFolder);
3040 m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
3041 }
3042  
3043 // Now get the pieces that make up the outfit
3044 XmlNodeList items = outfit.GetElementsByTagName("Item");
3045  
3046 foreach (XmlElement item in items)
3047 {
3048 assetid = UUID.Zero;
3049 XmlNodeList children = item.ChildNodes;
3050 foreach (XmlNode child in children)
3051 {
3052 switch (child.Name)
3053 {
3054 case "Permissions" :
3055 m_log.DebugFormat("[RADMIN]: Permissions specified");
3056 perms = child;
3057 break;
3058 case "Asset" :
3059 assetid = new UUID(child.InnerText);
3060 break;
3061 }
3062 }
3063  
3064 InventoryItemBase inventoryItem = null;
3065  
3066 // Check if asset is in inventory already
3067 inventoryItem = null;
3068 List<InventoryItemBase> inventoryItems = inventoryService.GetFolderContent(ID, extraFolder.ID).Items;
3069  
3070 foreach (InventoryItemBase listItem in inventoryItems)
3071 {
3072 if (listItem.AssetID == assetid)
3073 {
3074 inventoryItem = listItem;
3075 break;
3076 }
3077 }
3078  
3079 // Create inventory item
3080 if (inventoryItem == null)
3081 {
3082 inventoryItem = new InventoryItemBase(UUID.Random(), ID);
3083 inventoryItem.Name = GetStringAttribute(item,"name","");
3084 inventoryItem.Description = GetStringAttribute(item,"desc","");
3085 inventoryItem.InvType = GetIntegerAttribute(item,"invtype",-1);
3086 inventoryItem.CreatorId = GetStringAttribute(item,"creatorid","");
3087 inventoryItem.CreatorData = GetStringAttribute(item, "creatordata", "");
3088 inventoryItem.NextPermissions = GetUnsignedAttribute(perms, "next", 0x7fffffff);
3089 inventoryItem.CurrentPermissions = GetUnsignedAttribute(perms,"current",0x7fffffff);
3090 inventoryItem.BasePermissions = GetUnsignedAttribute(perms,"base",0x7fffffff);
3091 inventoryItem.EveryOnePermissions = GetUnsignedAttribute(perms,"everyone",0x7fffffff);
3092 inventoryItem.GroupPermissions = GetUnsignedAttribute(perms,"group",0x7fffffff);
3093 inventoryItem.AssetType = GetIntegerAttribute(item,"assettype",-1);
3094 inventoryItem.AssetID = assetid; // associated asset
3095 inventoryItem.GroupID = (UUID)GetStringAttribute(item,"groupid","");
3096 inventoryItem.GroupOwned = (GetStringAttribute(item,"groupowned","false") == "true");
3097 inventoryItem.SalePrice = GetIntegerAttribute(item,"saleprice",0);
3098 inventoryItem.SaleType = (byte)GetIntegerAttribute(item,"saletype",0);
3099 inventoryItem.Flags = GetUnsignedAttribute(item,"flags",0);
3100 inventoryItem.CreationDate = GetIntegerAttribute(item,"creationdate",Util.UnixTimeSinceEpoch());
3101 inventoryItem.Folder = extraFolder.ID; // Parent folder
3102  
3103 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem);
3104 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
3105 }
3106  
3107 // Attach item, if attachpoint is specified
3108 int attachpoint = GetIntegerAttribute(item,"attachpoint",0);
3109 if (attachpoint != 0)
3110 {
3111 avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID);
3112 m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID);
3113 }
3114  
3115 // Record whether or not the item is to be initially worn
3116 try
3117 {
3118 if (select && (GetStringAttribute(item, "wear", "false") == "true"))
3119 {
3120 avatarAppearance.Wearables[inventoryItem.Flags].Wear(inventoryItem.ID, inventoryItem.AssetID);
3121 }
3122 }
3123 catch (Exception e)
3124 {
3125 m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
3126 }
3127 } // foreach item in outfit
3128 m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName);
3129 } // foreach outfit
3130 m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name);
3131 scene.AvatarService.SetAppearance(ID, avatarAppearance);
3132 }
3133 catch (Exception e)
3134 {
3135 m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}",
3136 name, e.Message);
3137 }
3138 } // End of include
3139 }
3140 m_log.DebugFormat("[RADMIN]: Default avatar loading complete");
3141 }
3142 else
3143 {
3144 m_log.DebugFormat("[RADMIN]: No default avatar information available");
3145 return false;
3146 }
3147 }
3148 catch (Exception e)
3149 {
3150 m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message);
3151 return false;
3152 }
3153  
3154 return true;
3155 }
3156 }
3157 }