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