opensim-development – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 eva 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)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
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)Util.RegionToWorldLoc((uint)regionXLocation), (int)Util.RegionToWorldLoc((uint)regionYLocation));
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 Dictionary<string, object> archiveOptions = new Dictionary<string,object>();
1488 if (mergeOar) archiveOptions.Add("merge", null);
1489 if (skipAssets) archiveOptions.Add("skipAssets", null);
1490 if (archiver != null)
1491 archiver.DearchiveRegion(filename, Guid.Empty, archiveOptions);
1492 else
1493 throw new Exception("Archiver module not present for scene");
1494  
1495 responseData["loaded"] = true;
1496 }
1497 catch (Exception e)
1498 {
1499 responseData["loaded"] = false;
1500  
1501 throw e;
1502 }
1503  
1504 m_log.Info("[RADMIN]: Load OAR Administrator Request complete");
1505 }
1506 }
1507  
1508 /// <summary>
1509 /// Save a region to an OAR file
1510 /// <summary>
1511 /// <param name="request">incoming XML RPC request</param>
1512 /// <remarks>
1513 /// XmlRpcSaveOARMethod takes the following XMLRPC
1514 /// parameters
1515 /// <list type="table">
1516 /// <listheader><term>parameter name</term><description>description</description></listheader>
1517 /// <item><term>password</term>
1518 /// <description>admin password as set in OpenSim.ini</description></item>
1519 /// <item><term>filename</term>
1520 /// <description>file name for the OAR file</description></item>
1521 /// <item><term>region_uuid</term>
1522 /// <description>UUID of the region</description></item>
1523 /// <item><term>region_name</term>
1524 /// <description>region name</description></item>
1525 /// <item><term>profile</term>
1526 /// <description>profile url</description></item>
1527 /// <item><term>noassets</term>
1528 /// <description>true if no assets should be saved</description></item>
1529 /// <item><term>all</term>
1530 /// <description>true to save all the regions in the simulator</description></item>
1531 /// <item><term>perm</term>
1532 /// <description>C and/or T</description></item>
1533 /// </list>
1534 ///
1535 /// <code>region_uuid</code> takes precedence over
1536 /// <code>region_name</code> if both are present; one of both
1537 /// must be present.
1538 ///
1539 /// XmlRpcLoadOARMethod returns
1540 /// <list type="table">
1541 /// <listheader><term>name</term><description>description</description></listheader>
1542 /// <item><term>success</term>
1543 /// <description>true or false</description></item>
1544 /// <item><term>error</term>
1545 /// <description>error message if success is false</description></item>
1546 /// </list>
1547 /// </remarks>
1548 private void XmlRpcSaveOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1549 {
1550 m_log.Info("[RADMIN]: Received Save OAR Request");
1551  
1552 Hashtable responseData = (Hashtable)response.Value;
1553 Hashtable requestData = (Hashtable)request.Params[0];
1554  
1555 try
1556 {
1557 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1558 CheckRegionParams(requestData, responseData);
1559  
1560 Scene scene = null;
1561 GetSceneFromRegionParams(requestData, responseData, out scene);
1562  
1563 string filename = (string)requestData["filename"];
1564  
1565 Dictionary<string, object> options = new Dictionary<string, object>();
1566  
1567 //if (requestData.Contains("version"))
1568 //{
1569 // options["version"] = (string)requestData["version"];
1570 //}
1571  
1572 if (requestData.Contains("home"))
1573 {
1574 options["home"] = (string)requestData["home"];
1575 }
1576  
1577 if ((string)requestData["noassets"] == "true")
1578 {
1579 options["noassets"] = (string)requestData["noassets"] ;
1580 }
1581  
1582 if (requestData.Contains("perm"))
1583 {
1584 options["checkPermissions"] = (string)requestData["perm"];
1585 }
1586  
1587 if ((string)requestData["all"] == "true")
1588 {
1589 options["all"] = (string)requestData["all"];
1590 }
1591  
1592 IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
1593  
1594 if (archiver != null)
1595 {
1596 Guid requestId = Guid.NewGuid();
1597 scene.EventManager.OnOarFileSaved += RemoteAdminOarSaveCompleted;
1598  
1599 m_log.InfoFormat(
1600 "[RADMIN]: Submitting save OAR request for {0} to file {1}, request ID {2}",
1601 scene.Name, filename, requestId);
1602  
1603 archiver.ArchiveRegion(filename, requestId, options);
1604  
1605 lock (m_saveOarLock)
1606 Monitor.Wait(m_saveOarLock,5000);
1607  
1608 scene.EventManager.OnOarFileSaved -= RemoteAdminOarSaveCompleted;
1609 }
1610 else
1611 {
1612 throw new Exception("Archiver module not present for scene");
1613 }
1614  
1615 responseData["saved"] = true;
1616 }
1617 catch (Exception e)
1618 {
1619 responseData["saved"] = false;
1620  
1621 throw e;
1622 }
1623  
1624 m_log.Info("[RADMIN]: Save OAR Request complete");
1625 }
1626  
1627 private void RemoteAdminOarSaveCompleted(Guid uuid, string name)
1628 {
1629 if (name != "")
1630 m_log.ErrorFormat("[RADMIN]: Saving of OAR file with request ID {0} failed with message {1}", uuid, name);
1631 else
1632 m_log.DebugFormat("[RADMIN]: Saved OAR file for request {0}", uuid);
1633  
1634 lock (m_saveOarLock)
1635 Monitor.Pulse(m_saveOarLock);
1636 }
1637  
1638 private void XmlRpcLoadXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1639 {
1640 m_log.Info("[RADMIN]: Received Load XML Administrator Request");
1641  
1642 Hashtable responseData = (Hashtable)response.Value;
1643 Hashtable requestData = (Hashtable)request.Params[0];
1644  
1645 lock (m_requestLock)
1646 {
1647 try
1648 {
1649 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1650 CheckRegionParams(requestData, responseData);
1651  
1652 Scene scene = null;
1653 GetSceneFromRegionParams(requestData, responseData, out scene);
1654  
1655 string filename = (string) requestData["filename"];
1656  
1657 responseData["switched"] = true;
1658  
1659 string xml_version = "1";
1660 if (requestData.Contains("xml_version"))
1661 {
1662 xml_version = (string) requestData["xml_version"];
1663 }
1664  
1665 switch (xml_version)
1666 {
1667 case "1":
1668 m_application.SceneManager.LoadCurrentSceneFromXml(filename, true, new Vector3(0, 0, 0));
1669 break;
1670  
1671 case "2":
1672 m_application.SceneManager.LoadCurrentSceneFromXml2(filename);
1673 break;
1674  
1675 default:
1676 throw new Exception(String.Format("unknown Xml{0} format", xml_version));
1677 }
1678  
1679 responseData["loaded"] = true;
1680 }
1681 catch (Exception e)
1682 {
1683 responseData["loaded"] = false;
1684 responseData["switched"] = false;
1685  
1686 throw e;
1687 }
1688  
1689 m_log.Info("[RADMIN]: Load XML Administrator Request complete");
1690 }
1691 }
1692  
1693 private void XmlRpcSaveXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1694 {
1695 m_log.Info("[RADMIN]: Received Save XML Administrator Request");
1696  
1697 Hashtable responseData = (Hashtable)response.Value;
1698 Hashtable requestData = (Hashtable)request.Params[0];
1699  
1700 try
1701 {
1702 CheckStringParameters(requestData, responseData, new string[] {"filename"});
1703 CheckRegionParams(requestData, responseData);
1704  
1705 Scene scene = null;
1706 GetSceneFromRegionParams(requestData, responseData, out scene);
1707  
1708 string filename = (string) requestData["filename"];
1709  
1710 responseData["switched"] = true;
1711  
1712 string xml_version = "1";
1713 if (requestData.Contains("xml_version"))
1714 {
1715 xml_version = (string) requestData["xml_version"];
1716 }
1717  
1718 switch (xml_version)
1719 {
1720 case "1":
1721 m_application.SceneManager.SaveCurrentSceneToXml(filename);
1722 break;
1723  
1724 case "2":
1725 m_application.SceneManager.SaveCurrentSceneToXml2(filename);
1726 break;
1727  
1728 default:
1729 throw new Exception(String.Format("unknown Xml{0} format", xml_version));
1730 }
1731  
1732 responseData["saved"] = true;
1733 }
1734 catch (Exception e)
1735 {
1736 responseData["saved"] = false;
1737 responseData["switched"] = false;
1738  
1739 throw e;
1740 }
1741  
1742 m_log.Info("[RADMIN]: Save XML Administrator Request complete");
1743 }
1744  
1745 private void XmlRpcRegionQueryMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1746 {
1747 m_log.Info("[RADMIN]: Received Query XML Administrator Request");
1748  
1749 Hashtable responseData = (Hashtable)response.Value;
1750 Hashtable requestData = (Hashtable)request.Params[0];
1751  
1752 CheckRegionParams(requestData, responseData);
1753  
1754 Scene scene = null;
1755 GetSceneFromRegionParams(requestData, responseData, out scene);
1756  
1757 int health = scene.GetHealth();
1758 responseData["health"] = health;
1759  
1760 responseData["success"] = true;
1761 m_log.Info("[RADMIN]: Query XML Administrator Request complete");
1762 }
1763  
1764 private void XmlRpcConsoleCommandMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1765 {
1766 m_log.Info("[RADMIN]: Received Command XML Administrator Request");
1767  
1768 Hashtable responseData = (Hashtable)response.Value;
1769 Hashtable requestData = (Hashtable)request.Params[0];
1770  
1771 CheckStringParameters(requestData, responseData, new string[] {"command"});
1772  
1773 MainConsole.Instance.RunCommand(requestData["command"].ToString());
1774  
1775 m_log.Info("[RADMIN]: Command XML Administrator Request complete");
1776 }
1777  
1778 private void XmlRpcAccessListClear(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1779 {
1780 m_log.Info("[RADMIN]: Received Access List Clear Request");
1781  
1782 Hashtable responseData = (Hashtable)response.Value;
1783 Hashtable requestData = (Hashtable)request.Params[0];
1784  
1785 responseData["success"] = true;
1786  
1787 CheckRegionParams(requestData, responseData);
1788  
1789 Scene scene = null;
1790 GetSceneFromRegionParams(requestData, responseData, out scene);
1791  
1792 scene.RegionInfo.EstateSettings.EstateAccess = new UUID[]{};
1793  
1794 if (scene.RegionInfo.Persistent)
1795 scene.RegionInfo.EstateSettings.Save();
1796  
1797 m_log.Info("[RADMIN]: Access List Clear Request complete");
1798 }
1799  
1800 private void XmlRpcAccessListAdd(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1801 {
1802 m_log.Info("[RADMIN]: Received Access List Add Request");
1803  
1804 Hashtable responseData = (Hashtable)response.Value;
1805 Hashtable requestData = (Hashtable)request.Params[0];
1806  
1807 CheckRegionParams(requestData, responseData);
1808  
1809 Scene scene = null;
1810 GetSceneFromRegionParams(requestData, responseData, out scene);
1811  
1812 int addedUsers = 0;
1813  
1814 if (requestData.Contains("users"))
1815 {
1816 UUID scopeID = scene.RegionInfo.ScopeID;
1817 IUserAccountService userService = scene.UserAccountService;
1818 Hashtable users = (Hashtable) requestData["users"];
1819 List<UUID> uuids = new List<UUID>();
1820 foreach (string name in users.Values)
1821 {
1822 string[] parts = name.Split();
1823 UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
1824 if (account != null)
1825 {
1826 uuids.Add(account.PrincipalID);
1827 m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
1828 }
1829 }
1830 List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
1831 foreach (UUID uuid in uuids)
1832 {
1833 if (!accessControlList.Contains(uuid))
1834 {
1835 accessControlList.Add(uuid);
1836 addedUsers++;
1837 }
1838 }
1839 scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
1840 if (scene.RegionInfo.Persistent)
1841 scene.RegionInfo.EstateSettings.Save();
1842 }
1843  
1844 responseData["added"] = addedUsers;
1845  
1846 m_log.Info("[RADMIN]: Access List Add Request complete");
1847 }
1848  
1849 private void XmlRpcAccessListRemove(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1850 {
1851 m_log.Info("[RADMIN]: Received Access List Remove Request");
1852  
1853 Hashtable responseData = (Hashtable)response.Value;
1854 Hashtable requestData = (Hashtable)request.Params[0];
1855  
1856 CheckRegionParams(requestData, responseData);
1857  
1858 Scene scene = null;
1859 GetSceneFromRegionParams(requestData, responseData, out scene);
1860  
1861 int removedUsers = 0;
1862  
1863 if (requestData.Contains("users"))
1864 {
1865 UUID scopeID = scene.RegionInfo.ScopeID;
1866 IUserAccountService userService = scene.UserAccountService;
1867 //UserProfileCacheService ups = m_application.CommunicationsManager.UserProfileCacheService;
1868 Hashtable users = (Hashtable) requestData["users"];
1869 List<UUID> uuids = new List<UUID>();
1870 foreach (string name in users.Values)
1871 {
1872 string[] parts = name.Split();
1873 UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
1874 if (account != null)
1875 {
1876 uuids.Add(account.PrincipalID);
1877 }
1878 }
1879 List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
1880 foreach (UUID uuid in uuids)
1881 {
1882 if (accessControlList.Contains(uuid))
1883 {
1884 accessControlList.Remove(uuid);
1885 removedUsers++;
1886 }
1887 }
1888 scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
1889 if (scene.RegionInfo.Persistent)
1890 scene.RegionInfo.EstateSettings.Save();
1891 }
1892  
1893 responseData["removed"] = removedUsers;
1894 responseData["success"] = true;
1895  
1896 m_log.Info("[RADMIN]: Access List Remove Request complete");
1897 }
1898  
1899 private void XmlRpcAccessListList(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1900 {
1901 m_log.Info("[RADMIN]: Received Access List List Request");
1902  
1903 Hashtable responseData = (Hashtable)response.Value;
1904 Hashtable requestData = (Hashtable)request.Params[0];
1905  
1906 CheckRegionParams(requestData, responseData);
1907  
1908 Scene scene = null;
1909 GetSceneFromRegionParams(requestData, responseData, out scene);
1910  
1911 UUID[] accessControlList = scene.RegionInfo.EstateSettings.EstateAccess;
1912 Hashtable users = new Hashtable();
1913  
1914 foreach (UUID user in accessControlList)
1915 {
1916 UUID scopeID = scene.RegionInfo.ScopeID;
1917 UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, user);
1918 if (account != null)
1919 {
1920 users[user.ToString()] = account.FirstName + " " + account.LastName;
1921 }
1922 }
1923  
1924 responseData["users"] = users;
1925 responseData["success"] = true;
1926  
1927 m_log.Info("[RADMIN]: Access List List Request complete");
1928 }
1929  
1930 private void XmlRpcEstateReload(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1931 {
1932 m_log.Info("[RADMIN]: Received Estate Reload Request");
1933  
1934 Hashtable responseData = (Hashtable)response.Value;
1935 // Hashtable requestData = (Hashtable)request.Params[0];
1936  
1937 m_application.SceneManager.ForEachScene(s =>
1938 s.RegionInfo.EstateSettings = m_application.EstateDataService.LoadEstateSettings(s.RegionInfo.RegionID, false)
1939 );
1940  
1941 responseData["success"] = true;
1942  
1943 m_log.Info("[RADMIN]: Estate Reload Request complete");
1944 }
1945  
1946 private void XmlRpcGetAgentsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
1947 {
1948 Hashtable responseData = (Hashtable)response.Value;
1949 Hashtable requestData = (Hashtable)request.Params[0];
1950  
1951 bool includeChildren = false;
1952  
1953 if (requestData.Contains("include_children"))
1954 bool.TryParse((string)requestData["include_children"], out includeChildren);
1955  
1956 Scene scene;
1957 GetSceneFromRegionParams(requestData, responseData, out scene);
1958  
1959 ArrayList xmlRpcRegions = new ArrayList();
1960 responseData["regions"] = xmlRpcRegions;
1961  
1962 Hashtable xmlRpcRegion = new Hashtable();
1963 xmlRpcRegions.Add(xmlRpcRegion);
1964  
1965 xmlRpcRegion["name"] = scene.Name;
1966 xmlRpcRegion["id"] = scene.RegionInfo.RegionID.ToString();
1967  
1968 List<ScenePresence> agents = scene.GetScenePresences();
1969 ArrayList xmlrpcAgents = new ArrayList();
1970  
1971 foreach (ScenePresence agent in agents)
1972 {
1973 if (agent.IsChildAgent && !includeChildren)
1974 continue;
1975  
1976 Hashtable xmlRpcAgent = new Hashtable();
1977 xmlRpcAgent.Add("name", agent.Name);
1978 xmlRpcAgent.Add("id", agent.UUID.ToString());
1979 xmlRpcAgent.Add("type", agent.PresenceType.ToString());
1980 xmlRpcAgent.Add("current_parcel_id", agent.currentParcelUUID.ToString());
1981  
1982 Vector3 pos = agent.AbsolutePosition;
1983 xmlRpcAgent.Add("pos_x", pos.X.ToString());
1984 xmlRpcAgent.Add("pos_y", pos.Y.ToString());
1985 xmlRpcAgent.Add("pos_z", pos.Z.ToString());
1986  
1987 Vector3 lookAt = agent.Lookat;
1988 xmlRpcAgent.Add("lookat_x", lookAt.X.ToString());
1989 xmlRpcAgent.Add("lookat_y", lookAt.Y.ToString());
1990 xmlRpcAgent.Add("lookat_z", lookAt.Z.ToString());
1991  
1992 Vector3 vel = agent.Velocity;
1993 xmlRpcAgent.Add("vel_x", vel.X.ToString());
1994 xmlRpcAgent.Add("vel_y", vel.Y.ToString());
1995 xmlRpcAgent.Add("vel_z", vel.Z.ToString());
1996  
1997 xmlRpcAgent.Add("is_flying", agent.Flying.ToString());
1998 xmlRpcAgent.Add("is_sat_on_ground", agent.SitGround.ToString());
1999 xmlRpcAgent.Add("is_sat_on_object", agent.IsSatOnObject.ToString());
2000  
2001 xmlrpcAgents.Add(xmlRpcAgent);
2002 }
2003  
2004 m_log.DebugFormat(
2005 "[REMOTE ADMIN]: XmlRpcGetAgents found {0} agents in {1}", xmlrpcAgents.Count, scene.Name);
2006  
2007 xmlRpcRegion["agents"] = xmlrpcAgents;
2008 responseData["success"] = true;
2009 }
2010  
2011 private void XmlRpcTeleportAgentMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
2012 {
2013 Hashtable responseData = (Hashtable)response.Value;
2014 Hashtable requestData = (Hashtable)request.Params[0];
2015  
2016 UUID agentId;
2017 string regionName = null;
2018 Vector3 pos, lookAt;
2019 ScenePresence sp = null;
2020  
2021 if (requestData.Contains("agent_first_name") && requestData.Contains("agent_last_name"))
2022 {
2023 string firstName = requestData["agent_first_name"].ToString();
2024 string lastName = requestData["agent_last_name"].ToString();
2025 m_application.SceneManager.TryGetRootScenePresenceByName(firstName, lastName, out sp);
2026  
2027 if (sp == null)
2028 throw new Exception(
2029 string.Format(
2030 "No agent found with agent_first_name {0} and agent_last_name {1}", firstName, lastName));
2031 }
2032 else if (requestData.Contains("agent_id"))
2033 {
2034 string rawAgentId = (string)requestData["agent_id"];
2035  
2036 if (!UUID.TryParse(rawAgentId, out agentId))
2037 throw new Exception(string.Format("agent_id {0} does not have the correct id format", rawAgentId));
2038  
2039 m_application.SceneManager.TryGetRootScenePresence(agentId, out sp);
2040  
2041 if (sp == null)
2042 throw new Exception(string.Format("No agent with agent_id {0} found in this simulator", agentId));
2043 }
2044 else
2045 {
2046 throw new Exception("No agent_id or agent_first_name and agent_last_name parameters specified");
2047 }
2048  
2049 if (requestData.Contains("region_name"))
2050 regionName = (string)requestData["region_name"];
2051  
2052 pos.X = ParseFloat(requestData, "pos_x", sp.AbsolutePosition.X);
2053 pos.Y = ParseFloat(requestData, "pos_y", sp.AbsolutePosition.Y);
2054 pos.Z = ParseFloat(requestData, "pos_z", sp.AbsolutePosition.Z);
2055 lookAt.X = ParseFloat(requestData, "lookat_x", sp.Lookat.X);
2056 lookAt.Y = ParseFloat(requestData, "lookat_y", sp.Lookat.Y);
2057 lookAt.Z = ParseFloat(requestData, "lookat_z", sp.Lookat.Z);
2058  
2059 sp.Scene.RequestTeleportLocation(
2060 sp.ControllingClient, regionName, pos, lookAt, (uint)Constants.TeleportFlags.ViaLocation);
2061  
2062 // We have no way of telling the failure of the actual teleport
2063 responseData["success"] = true;
2064 }
2065  
2066 /// <summary>
2067 /// Parse a float with the given parameter name from a request data hash table.
2068 /// </summary>
2069 /// <remarks>
2070 /// Will throw an exception if parameter is not a float.
2071 /// Will not throw if parameter is not found, passes back default value instead.
2072 /// </remarks>
2073 /// <param name="requestData"></param>
2074 /// <param name="paramName"></param>
2075 /// <param name="defaultVal"></param>
2076 /// <returns></returns>
2077 private static float ParseFloat(Hashtable requestData, string paramName, float defaultVal)
2078 {
2079 if (requestData.Contains(paramName))
2080 {
2081 string rawVal = (string)requestData[paramName];
2082 float val;
2083  
2084 if (!float.TryParse(rawVal, out val))
2085 throw new Exception(string.Format("{0} {1} is not a valid float", paramName, rawVal));
2086 else
2087 return val;
2088 }
2089 else
2090 {
2091 return defaultVal;
2092 }
2093 }
2094  
2095 private static void CheckStringParameters(Hashtable requestData, Hashtable responseData, string[] param)
2096 {
2097 foreach (string parameter in param)
2098 {
2099 if (!requestData.Contains(parameter))
2100 {
2101 responseData["accepted"] = false;
2102 throw new Exception(String.Format("missing string parameter {0}", parameter));
2103 }
2104 if (String.IsNullOrEmpty((string) requestData[parameter]))
2105 {
2106 responseData["accepted"] = false;
2107 throw new Exception(String.Format("parameter {0} is empty", parameter));
2108 }
2109 }
2110 }
2111  
2112 private static void CheckIntegerParams(Hashtable requestData, Hashtable responseData, string[] param)
2113 {
2114 foreach (string parameter in param)
2115 {
2116 if (!requestData.Contains(parameter))
2117 {
2118 responseData["accepted"] = false;
2119 throw new Exception(String.Format("missing integer parameter {0}", parameter));
2120 }
2121 }
2122 }
2123  
2124 private void CheckRegionParams(Hashtable requestData, Hashtable responseData)
2125 {
2126 //Checks if region parameters exist and gives exeption if no parameters are given
2127 if ((requestData.ContainsKey("region_id") && !String.IsNullOrEmpty((string)requestData["region_id"])) ||
2128 (requestData.ContainsKey("region_name") && !String.IsNullOrEmpty((string)requestData["region_name"])))
2129 {
2130 return;
2131 }
2132 else
2133 {
2134 responseData["accepted"] = false;
2135 throw new Exception("no region_name or region_id given");
2136 }
2137 }
2138  
2139 private void GetSceneFromRegionParams(Hashtable requestData, Hashtable responseData, out Scene scene)
2140 {
2141 scene = null;
2142  
2143 if (requestData.ContainsKey("region_id") &&
2144 !String.IsNullOrEmpty((string)requestData["region_id"]))
2145 {
2146 UUID regionID = (UUID)(string)requestData["region_id"];
2147 if (!m_application.SceneManager.TryGetScene(regionID, out scene))
2148 {
2149 responseData["error"] = String.Format("Region ID {0} not found", regionID);
2150 throw new Exception(String.Format("Region ID {0} not found", regionID));
2151 }
2152 }
2153 else if (requestData.ContainsKey("region_name") &&
2154 !String.IsNullOrEmpty((string)requestData["region_name"]))
2155 {
2156 string regionName = (string)requestData["region_name"];
2157 if (!m_application.SceneManager.TryGetScene(regionName, out scene))
2158 {
2159 responseData["error"] = String.Format("Region {0} not found", regionName);
2160 throw new Exception(String.Format("Region {0} not found", regionName));
2161 }
2162 }
2163 else
2164 {
2165 responseData["error"] = "no region_name or region_id given";
2166 throw new Exception("no region_name or region_id given");
2167 }
2168 return;
2169 }
2170  
2171 private bool GetBoolean(Hashtable requestData, string tag, bool defaultValue)
2172 {
2173 // If an access value has been provided, apply it.
2174 if (requestData.Contains(tag))
2175 {
2176 switch (((string)requestData[tag]).ToLower())
2177 {
2178 case "true" :
2179 case "t" :
2180 case "1" :
2181 return true;
2182 case "false" :
2183 case "f" :
2184 case "0" :
2185 return false;
2186 default :
2187 return defaultValue;
2188 }
2189 }
2190 else
2191 return defaultValue;
2192 }
2193  
2194 private int GetIntegerAttribute(XmlNode node, string attribute, int defaultValue)
2195 {
2196 try { return Convert.ToInt32(node.Attributes[attribute].Value); } catch{}
2197 return defaultValue;
2198 }
2199  
2200 private uint GetUnsignedAttribute(XmlNode node, string attribute, uint defaultValue)
2201 {
2202 try { return Convert.ToUInt32(node.Attributes[attribute].Value); } catch{}
2203 return defaultValue;
2204 }
2205  
2206 private string GetStringAttribute(XmlNode node, string attribute, string defaultValue)
2207 {
2208 try { return node.Attributes[attribute].Value; } catch{}
2209 return defaultValue;
2210 }
2211  
2212 public void Dispose()
2213 {
2214 }
2215  
2216 /// <summary>
2217 /// Create a user
2218 /// </summary>
2219 /// <param name="scopeID"></param>
2220 /// <param name="firstName"></param>
2221 /// <param name="lastName"></param>
2222 /// <param name="password"></param>
2223 /// <param name="email"></param>
2224 private UserAccount CreateUser(UUID scopeID, string firstName, string lastName, string password, string email)
2225 {
2226 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2227 IUserAccountService userAccountService = scene.UserAccountService;
2228 IGridService gridService = scene.GridService;
2229 IAuthenticationService authenticationService = scene.AuthenticationService;
2230 IGridUserService gridUserService = scene.GridUserService;
2231 IInventoryService inventoryService = scene.InventoryService;
2232  
2233 UserAccount account = userAccountService.GetUserAccount(scopeID, firstName, lastName);
2234 if (null == account)
2235 {
2236 account = new UserAccount(scopeID, UUID.Random(), firstName, lastName, email);
2237 if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
2238 {
2239 account.ServiceURLs = new Dictionary<string, object>();
2240 account.ServiceURLs["HomeURI"] = string.Empty;
2241 account.ServiceURLs["GatekeeperURI"] = string.Empty;
2242 account.ServiceURLs["InventoryServerURI"] = string.Empty;
2243 account.ServiceURLs["AssetServerURI"] = string.Empty;
2244 }
2245  
2246 if (userAccountService.StoreUserAccount(account))
2247 {
2248 bool success;
2249 if (authenticationService != null)
2250 {
2251 success = authenticationService.SetPassword(account.PrincipalID, password);
2252 if (!success)
2253 m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
2254 firstName, lastName);
2255 }
2256  
2257 GridRegion home = null;
2258 if (gridService != null)
2259 {
2260 List<GridRegion> defaultRegions = gridService.GetDefaultRegions(UUID.Zero);
2261 if (defaultRegions != null && defaultRegions.Count >= 1)
2262 home = defaultRegions[0];
2263  
2264 if (gridUserService != null && home != null)
2265 gridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
2266 else
2267 m_log.WarnFormat("[RADMIN]: Unable to set home for account {0} {1}.",
2268 firstName, lastName);
2269 }
2270 else
2271 m_log.WarnFormat("[RADMIN]: Unable to retrieve home region for account {0} {1}.",
2272 firstName, lastName);
2273  
2274 if (inventoryService != null)
2275 {
2276 success = inventoryService.CreateUserInventory(account.PrincipalID);
2277 if (!success)
2278 m_log.WarnFormat("[RADMIN]: Unable to create inventory for account {0} {1}.",
2279 firstName, lastName);
2280 }
2281  
2282 m_log.InfoFormat("[RADMIN]: Account {0} {1} created successfully", firstName, lastName);
2283 return account;
2284 } else {
2285 m_log.ErrorFormat("[RADMIN]: Account creation failed for account {0} {1}", firstName, lastName);
2286 }
2287 }
2288 else
2289 {
2290 m_log.ErrorFormat("[RADMIN]: A user with the name {0} {1} already exists!", firstName, lastName);
2291 }
2292 return null;
2293 }
2294  
2295 /// <summary>
2296 /// Change password
2297 /// </summary>
2298 /// <param name="firstName"></param>
2299 /// <param name="lastName"></param>
2300 /// <param name="password"></param>
2301 private bool ChangeUserPassword(string firstName, string lastName, string password)
2302 {
2303 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2304 IUserAccountService userAccountService = scene.UserAccountService;
2305 IAuthenticationService authenticationService = scene.AuthenticationService;
2306  
2307 UserAccount account = userAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
2308 if (null != account)
2309 {
2310 bool success = false;
2311 if (authenticationService != null)
2312 success = authenticationService.SetPassword(account.PrincipalID, password);
2313  
2314 if (!success)
2315 {
2316 m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
2317 firstName, lastName);
2318 return false;
2319 }
2320 return true;
2321 }
2322 else
2323 {
2324 m_log.ErrorFormat("[RADMIN]: No such user");
2325 return false;
2326 }
2327 }
2328  
2329 private bool LoadHeightmap(string file, UUID regionID)
2330 {
2331 m_log.InfoFormat("[RADMIN]: Terrain Loading: {0}", file);
2332  
2333 Scene region = null;
2334  
2335 if (!m_application.SceneManager.TryGetScene(regionID, out region))
2336 {
2337 m_log.InfoFormat("[RADMIN]: unable to get a scene with that name: {0}", regionID.ToString());
2338 return false;
2339 }
2340  
2341 ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
2342 if (null == terrainModule) throw new Exception("terrain module not available");
2343 if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
2344 {
2345 m_log.Info("[RADMIN]: Terrain path is URL");
2346 Uri result;
2347 if (Uri.TryCreate(file, UriKind.RelativeOrAbsolute, out result))
2348 {
2349 // the url is valid
2350 string fileType = file.Substring(file.LastIndexOf('/') + 1);
2351 terrainModule.LoadFromStream(fileType, result);
2352 }
2353 }
2354 else
2355 {
2356 terrainModule.LoadFromFile(file);
2357 }
2358  
2359 m_log.Info("[RADMIN]: Load height maps request complete");
2360  
2361 return true;
2362 }
2363  
2364  
2365 /// <summary>
2366 /// This method is called by the user-create and user-modify methods to establish
2367 /// or change, the user's appearance. Default avatar names can be specified via
2368 /// the config file, but must correspond to avatars in the default appearance
2369 /// file, or pre-existing in the user database.
2370 /// This should probably get moved into somewhere more core eventually.
2371 /// </summary>
2372 private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
2373 {
2374 m_log.DebugFormat("[RADMIN]: updateUserAppearance");
2375  
2376 string defaultMale = m_config.GetString("default_male", "Default Male");
2377 string defaultFemale = m_config.GetString("default_female", "Default Female");
2378 string defaultNeutral = m_config.GetString("default_female", "Default Default");
2379 string model = String.Empty;
2380  
2381 // Has a gender preference been supplied?
2382  
2383 if (requestData.Contains("gender"))
2384 {
2385 switch ((string)requestData["gender"])
2386 {
2387 case "m" :
2388 case "male" :
2389 model = defaultMale;
2390 break;
2391 case "f" :
2392 case "female" :
2393 model = defaultFemale;
2394 break;
2395 case "n" :
2396 case "neutral" :
2397 default :
2398 model = defaultNeutral;
2399 break;
2400 }
2401 }
2402  
2403 // Has an explicit model been specified?
2404  
2405 if (requestData.Contains("model") && (String.IsNullOrEmpty((string)requestData["gender"])))
2406 {
2407 model = (string)requestData["model"];
2408 }
2409  
2410 // No appearance attributes were set
2411  
2412 if (String.IsNullOrEmpty(model))
2413 {
2414 m_log.DebugFormat("[RADMIN]: Appearance update not requested");
2415 return;
2416 }
2417  
2418 m_log.DebugFormat("[RADMIN]: Setting appearance for avatar {0}, using model <{1}>", userid, model);
2419  
2420 string[] modelSpecifiers = model.Split();
2421 if (modelSpecifiers.Length != 2)
2422 {
2423 m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
2424 // modelSpecifiers = dmodel.Split();
2425 return;
2426 }
2427  
2428 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2429 UUID scopeID = scene.RegionInfo.ScopeID;
2430 UserAccount modelProfile = scene.UserAccountService.GetUserAccount(scopeID, modelSpecifiers[0], modelSpecifiers[1]);
2431  
2432 if (modelProfile == null)
2433 {
2434 m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model);
2435 return;
2436 }
2437  
2438 // Set current user's appearance. This bit is easy. The appearance structure is populated with
2439 // actual asset ids, however to complete the magic we need to populate the inventory with the
2440 // assets in question.
2441  
2442 EstablishAppearance(userid, modelProfile.PrincipalID);
2443  
2444 m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}",
2445 userid, model);
2446 }
2447  
2448 /// <summary>
2449 /// This method is called by updateAvatarAppearance once any specified model has been
2450 /// ratified, or an appropriate default value has been adopted. The intended prototype
2451 /// is known to exist, as is the target avatar.
2452 /// </summary>
2453 private void EstablishAppearance(UUID destination, UUID source)
2454 {
2455 m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source);
2456 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2457  
2458 // If the model has no associated appearance we're done.
2459 AvatarAppearance avatarAppearance = scene.AvatarService.GetAppearance(source);
2460 if (avatarAppearance == null)
2461 return;
2462  
2463 // Simple appearance copy or copy Clothing and Bodyparts folders?
2464 bool copyFolders = m_config.GetBoolean("copy_folders", false);
2465  
2466 if (!copyFolders)
2467 {
2468 // Simple copy of wearables and appearance update
2469 try
2470 {
2471 CopyWearablesAndAttachments(destination, source, avatarAppearance);
2472  
2473 scene.AvatarService.SetAppearance(destination, avatarAppearance);
2474 }
2475 catch (Exception e)
2476 {
2477 m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
2478 destination, e.Message);
2479 }
2480  
2481 return;
2482 }
2483  
2484 // Copy Clothing and Bodypart folders and appearance update
2485 try
2486 {
2487 Dictionary<UUID,UUID> inventoryMap = new Dictionary<UUID,UUID>();
2488 CopyInventoryFolders(destination, source, AssetType.Clothing, inventoryMap, avatarAppearance);
2489 CopyInventoryFolders(destination, source, AssetType.Bodypart, inventoryMap, avatarAppearance);
2490  
2491 AvatarWearable[] wearables = avatarAppearance.Wearables;
2492  
2493 for (int i=0; i<wearables.Length; i++)
2494 {
2495 if (inventoryMap.ContainsKey(wearables[i][0].ItemID))
2496 {
2497 AvatarWearable wearable = new AvatarWearable();
2498 wearable.Wear(inventoryMap[wearables[i][0].ItemID],
2499 wearables[i][0].AssetID);
2500 avatarAppearance.SetWearable(i, wearable);
2501 }
2502 }
2503  
2504 scene.AvatarService.SetAppearance(destination, avatarAppearance);
2505 }
2506 catch (Exception e)
2507 {
2508 m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
2509 destination, e.Message);
2510 }
2511  
2512 return;
2513 }
2514  
2515 /// <summary>
2516 /// This method is called by establishAppearance to do a copy all inventory items
2517 /// worn or attached to the Clothing inventory folder of the receiving avatar.
2518 /// In parallel the avatar wearables and attachments are updated.
2519 /// </summary>
2520 private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance)
2521 {
2522 IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
2523  
2524 // Get Clothing folder of receiver
2525 InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, AssetType.Clothing);
2526  
2527 if (destinationFolder == null)
2528 throw new Exception("Cannot locate folder(s)");
2529  
2530 // Missing destination folder? This should *never* be the case
2531 if (destinationFolder.Type != (short)AssetType.Clothing)
2532 {
2533 destinationFolder = new InventoryFolderBase();
2534  
2535 destinationFolder.ID = UUID.Random();
2536 destinationFolder.Name = "Clothing";
2537 destinationFolder.Owner = destination;
2538 destinationFolder.Type = (short)AssetType.Clothing;
2539 destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
2540 destinationFolder.Version = 1;
2541 inventoryService.AddFolder(destinationFolder); // store base record
2542 m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
2543 }
2544  
2545 // Wearables
2546 AvatarWearable[] wearables = avatarAppearance.Wearables;
2547 AvatarWearable wearable;
2548  
2549 for (int i = 0; i<wearables.Length; i++)
2550 {
2551 wearable = wearables[i];
2552 if (wearable[0].ItemID != UUID.Zero)
2553 {
2554 // Get inventory item and copy it
2555 InventoryItemBase item = new InventoryItemBase(wearable[0].ItemID, source);
2556 item = inventoryService.GetItem(item);
2557  
2558 if (item != null)
2559 {
2560 InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
2561 destinationItem.Name = item.Name;
2562 destinationItem.Owner = destination;
2563 destinationItem.Description = item.Description;
2564 destinationItem.InvType = item.InvType;
2565 destinationItem.CreatorId = item.CreatorId;
2566 destinationItem.CreatorData = item.CreatorData;
2567 destinationItem.NextPermissions = item.NextPermissions;
2568 destinationItem.CurrentPermissions = item.CurrentPermissions;
2569 destinationItem.BasePermissions = item.BasePermissions;
2570 destinationItem.EveryOnePermissions = item.EveryOnePermissions;
2571 destinationItem.GroupPermissions = item.GroupPermissions;
2572 destinationItem.AssetType = item.AssetType;
2573 destinationItem.AssetID = item.AssetID;
2574 destinationItem.GroupID = item.GroupID;
2575 destinationItem.GroupOwned = item.GroupOwned;
2576 destinationItem.SalePrice = item.SalePrice;
2577 destinationItem.SaleType = item.SaleType;
2578 destinationItem.Flags = item.Flags;
2579 destinationItem.CreationDate = item.CreationDate;
2580 destinationItem.Folder = destinationFolder.ID;
2581 ApplyNextOwnerPermissions(destinationItem);
2582  
2583 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
2584 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
2585  
2586 // Wear item
2587 AvatarWearable newWearable = new AvatarWearable();
2588 newWearable.Wear(destinationItem.ID, wearable[0].AssetID);
2589 avatarAppearance.SetWearable(i, newWearable);
2590 }
2591 else
2592 {
2593 m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", wearable[0].ItemID, destinationFolder.ID);
2594 }
2595 }
2596 }
2597  
2598 // Attachments
2599 List<AvatarAttachment> attachments = avatarAppearance.GetAttachments();
2600  
2601 foreach (AvatarAttachment attachment in attachments)
2602 {
2603 int attachpoint = attachment.AttachPoint;
2604 UUID itemID = attachment.ItemID;
2605  
2606 if (itemID != UUID.Zero)
2607 {
2608 // Get inventory item and copy it
2609 InventoryItemBase item = new InventoryItemBase(itemID, source);
2610 item = inventoryService.GetItem(item);
2611  
2612 if (item != null)
2613 {
2614 InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
2615 destinationItem.Name = item.Name;
2616 destinationItem.Owner = destination;
2617 destinationItem.Description = item.Description;
2618 destinationItem.InvType = item.InvType;
2619 destinationItem.CreatorId = item.CreatorId;
2620 destinationItem.CreatorData = item.CreatorData;
2621 destinationItem.NextPermissions = item.NextPermissions;
2622 destinationItem.CurrentPermissions = item.CurrentPermissions;
2623 destinationItem.BasePermissions = item.BasePermissions;
2624 destinationItem.EveryOnePermissions = item.EveryOnePermissions;
2625 destinationItem.GroupPermissions = item.GroupPermissions;
2626 destinationItem.AssetType = item.AssetType;
2627 destinationItem.AssetID = item.AssetID;
2628 destinationItem.GroupID = item.GroupID;
2629 destinationItem.GroupOwned = item.GroupOwned;
2630 destinationItem.SalePrice = item.SalePrice;
2631 destinationItem.SaleType = item.SaleType;
2632 destinationItem.Flags = item.Flags;
2633 destinationItem.CreationDate = item.CreationDate;
2634 destinationItem.Folder = destinationFolder.ID;
2635 ApplyNextOwnerPermissions(destinationItem);
2636  
2637 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
2638 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
2639  
2640 // Attach item
2641 avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
2642 m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
2643 }
2644 else
2645 {
2646 m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", itemID, destinationFolder.ID);
2647 }
2648 }
2649 }
2650 }
2651  
2652 /// <summary>
2653 /// This method is called by establishAppearance to copy inventory folders to make
2654 /// copies of Clothing and Bodyparts inventory folders and attaches worn attachments
2655 /// </summary>
2656 private void CopyInventoryFolders(UUID destination, UUID source, AssetType assetType, Dictionary<UUID,UUID> inventoryMap,
2657 AvatarAppearance avatarAppearance)
2658 {
2659 IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
2660  
2661 InventoryFolderBase sourceFolder = inventoryService.GetFolderForType(source, assetType);
2662 InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, assetType);
2663  
2664 if (sourceFolder == null || destinationFolder == null)
2665 throw new Exception("Cannot locate folder(s)");
2666  
2667 // Missing source folder? This should *never* be the case
2668 if (sourceFolder.Type != (short)assetType)
2669 {
2670 sourceFolder = new InventoryFolderBase();
2671 sourceFolder.ID = UUID.Random();
2672 if (assetType == AssetType.Clothing) {
2673 sourceFolder.Name = "Clothing";
2674 } else {
2675 sourceFolder.Name = "Body Parts";
2676 }
2677 sourceFolder.Owner = source;
2678 sourceFolder.Type = (short)assetType;
2679 sourceFolder.ParentID = inventoryService.GetRootFolder(source).ID;
2680 sourceFolder.Version = 1;
2681 inventoryService.AddFolder(sourceFolder); // store base record
2682 m_log.ErrorFormat("[RADMIN] Created folder for source {0}", source);
2683 }
2684  
2685 // Missing destination folder? This should *never* be the case
2686 if (destinationFolder.Type != (short)assetType)
2687 {
2688 destinationFolder = new InventoryFolderBase();
2689 destinationFolder.ID = UUID.Random();
2690 if (assetType == AssetType.Clothing)
2691 {
2692 destinationFolder.Name = "Clothing";
2693 }
2694 else
2695 {
2696 destinationFolder.Name = "Body Parts";
2697 }
2698 destinationFolder.Owner = destination;
2699 destinationFolder.Type = (short)assetType;
2700 destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
2701 destinationFolder.Version = 1;
2702 inventoryService.AddFolder(destinationFolder); // store base record
2703 m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
2704 }
2705  
2706 InventoryFolderBase extraFolder;
2707 List<InventoryFolderBase> folders = inventoryService.GetFolderContent(source, sourceFolder.ID).Folders;
2708  
2709 foreach (InventoryFolderBase folder in folders)
2710 {
2711 extraFolder = new InventoryFolderBase();
2712 extraFolder.ID = UUID.Random();
2713 extraFolder.Name = folder.Name;
2714 extraFolder.Owner = destination;
2715 extraFolder.Type = folder.Type;
2716 extraFolder.Version = folder.Version;
2717 extraFolder.ParentID = destinationFolder.ID;
2718 inventoryService.AddFolder(extraFolder);
2719  
2720 m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);
2721  
2722 List<InventoryItemBase> items = inventoryService.GetFolderContent(source, folder.ID).Items;
2723  
2724 foreach (InventoryItemBase item in items)
2725 {
2726 InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
2727 destinationItem.Name = item.Name;
2728 destinationItem.Owner = destination;
2729 destinationItem.Description = item.Description;
2730 destinationItem.InvType = item.InvType;
2731 destinationItem.CreatorId = item.CreatorId;
2732 destinationItem.CreatorData = item.CreatorData;
2733 destinationItem.NextPermissions = item.NextPermissions;
2734 destinationItem.CurrentPermissions = item.CurrentPermissions;
2735 destinationItem.BasePermissions = item.BasePermissions;
2736 destinationItem.EveryOnePermissions = item.EveryOnePermissions;
2737 destinationItem.GroupPermissions = item.GroupPermissions;
2738 destinationItem.AssetType = item.AssetType;
2739 destinationItem.AssetID = item.AssetID;
2740 destinationItem.GroupID = item.GroupID;
2741 destinationItem.GroupOwned = item.GroupOwned;
2742 destinationItem.SalePrice = item.SalePrice;
2743 destinationItem.SaleType = item.SaleType;
2744 destinationItem.Flags = item.Flags;
2745 destinationItem.CreationDate = item.CreationDate;
2746 destinationItem.Folder = extraFolder.ID;
2747 ApplyNextOwnerPermissions(destinationItem);
2748  
2749 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
2750 inventoryMap.Add(item.ID, destinationItem.ID);
2751 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, extraFolder.ID);
2752  
2753 // Attach item, if original is attached
2754 int attachpoint = avatarAppearance.GetAttachpoint(item.ID);
2755 if (attachpoint != 0)
2756 {
2757 avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
2758 m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
2759 }
2760 }
2761 }
2762 }
2763  
2764 /// <summary>
2765 /// Apply next owner permissions.
2766 /// </summary>
2767 private void ApplyNextOwnerPermissions(InventoryItemBase item)
2768 {
2769 if (item.InvType == (int)InventoryType.Object)
2770 {
2771 uint perms = item.CurrentPermissions;
2772 PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref perms);
2773 item.CurrentPermissions = perms;
2774 }
2775  
2776 item.CurrentPermissions &= item.NextPermissions;
2777 item.BasePermissions &= item.NextPermissions;
2778 item.EveryOnePermissions &= item.NextPermissions;
2779 // item.OwnerChanged = true;
2780 // item.PermsMask = 0;
2781 // item.PermsGranter = UUID.Zero;
2782 }
2783  
2784 /// <summary>
2785 /// This method is called if a given model avatar name can not be found. If the external
2786 /// file has already been loaded once, then control returns immediately. If not, then it
2787 /// looks for a default appearance file. This file contains XML definitions of zero or more named
2788 /// avatars, each avatar can specify zero or more "outfits". Each outfit is a collection
2789 /// of items that together, define a particular ensemble for the avatar. Each avatar should
2790 /// indicate which outfit is the default, and this outfit will be automatically worn. The
2791 /// other outfits are provided to allow "real" avatars a way to easily change their outfits.
2792 /// </summary>
2793 private bool CreateDefaultAvatars()
2794 {
2795 // Only load once
2796 if (m_defaultAvatarsLoaded)
2797 {
2798 return false;
2799 }
2800  
2801 m_log.DebugFormat("[RADMIN]: Creating default avatar entries");
2802  
2803 m_defaultAvatarsLoaded = true;
2804  
2805 // Load processing starts here...
2806  
2807 try
2808 {
2809 string defaultAppearanceFileName = null;
2810  
2811 //m_config may be null if RemoteAdmin configuration secition is missing or disabled in OpenSim.ini
2812 if (m_config != null)
2813 {
2814 defaultAppearanceFileName = m_config.GetString("default_appearance", "default_appearance.xml");
2815 }
2816  
2817 if (File.Exists(defaultAppearanceFileName))
2818 {
2819 XmlDocument doc = new XmlDocument();
2820 string name = "*unknown*";
2821 string email = "anon@anon";
2822 uint regionXLocation = 1000;
2823 uint regionYLocation = 1000;
2824 string password = UUID.Random().ToString(); // No requirement to sign-in.
2825 UUID ID = UUID.Zero;
2826 AvatarAppearance avatarAppearance;
2827 XmlNodeList avatars;
2828 XmlNodeList assets;
2829 XmlNode perms = null;
2830 bool include = false;
2831 bool select = false;
2832  
2833 Scene scene = m_application.SceneManager.CurrentOrFirstScene;
2834 IInventoryService inventoryService = scene.InventoryService;
2835 IAssetService assetService = scene.AssetService;
2836  
2837 doc.LoadXml(File.ReadAllText(defaultAppearanceFileName));
2838  
2839 // Load up any included assets. Duplicates will be ignored
2840 assets = doc.GetElementsByTagName("RequiredAsset");
2841 foreach (XmlNode assetNode in assets)
2842 {
2843 AssetBase asset = new AssetBase(UUID.Random(), GetStringAttribute(assetNode, "name", ""), SByte.Parse(GetStringAttribute(assetNode, "type", "")), UUID.Zero.ToString());
2844 asset.Description = GetStringAttribute(assetNode,"desc","");
2845 asset.Local = Boolean.Parse(GetStringAttribute(assetNode,"local",""));
2846 asset.Temporary = Boolean.Parse(GetStringAttribute(assetNode,"temporary",""));
2847 asset.Data = Convert.FromBase64String(assetNode.InnerText);
2848 assetService.Store(asset);
2849 }
2850  
2851 avatars = doc.GetElementsByTagName("Avatar");
2852  
2853 // The document may contain multiple avatars
2854  
2855 foreach (XmlElement avatar in avatars)
2856 {
2857 m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}",
2858 GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?"));
2859  
2860 // Create the user identified by the avatar entry
2861  
2862 try
2863 {
2864 // Only the name value is mandatory
2865 name = GetStringAttribute(avatar,"name",name);
2866 email = GetStringAttribute(avatar,"email",email);
2867 regionXLocation = GetUnsignedAttribute(avatar,"regx",regionXLocation);
2868 regionYLocation = GetUnsignedAttribute(avatar,"regy",regionYLocation);
2869 password = GetStringAttribute(avatar,"password",password);
2870  
2871 string[] names = name.Split();
2872 UUID scopeID = scene.RegionInfo.ScopeID;
2873 UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, names[0], names[1]);
2874 if (null == account)
2875 {
2876 account = CreateUser(scopeID, names[0], names[1], password, email);
2877 if (null == account)
2878 {
2879 m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]);
2880 return false;
2881 }
2882 }
2883  
2884 // Set home position
2885  
2886 GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
2887 (int)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
2888 if (null == home) {
2889 m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", names[0], names[1]);
2890 } else {
2891 scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
2892 m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, names[0], names[1]);
2893 }
2894  
2895 ID = account.PrincipalID;
2896  
2897 m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID);
2898 include = true;
2899 }
2900 catch (Exception e)
2901 {
2902 m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message);
2903 include = false;
2904 }
2905  
2906 // OK, User has been created OK, now we can install the inventory.
2907 // First retrieve the current inventory (the user may already exist)
2908 // Note that althought he inventory is retrieved, the hierarchy has
2909 // not been interpreted at all.
2910  
2911 if (include)
2912 {
2913 // Setup for appearance processing
2914 avatarAppearance = scene.AvatarService.GetAppearance(ID);
2915 if (avatarAppearance == null)
2916 avatarAppearance = new AvatarAppearance();
2917  
2918 AvatarWearable[] wearables = avatarAppearance.Wearables;
2919 for (int i=0; i<wearables.Length; i++)
2920 {
2921 wearables[i] = new AvatarWearable();
2922 }
2923  
2924 try
2925 {
2926 // m_log.DebugFormat("[RADMIN] {0} folders, {1} items in inventory",
2927 // uic.folders.Count, uic.items.Count);
2928  
2929 InventoryFolderBase clothingFolder = inventoryService.GetFolderForType(ID, AssetType.Clothing);
2930  
2931 // This should *never* be the case
2932 if (clothingFolder == null || clothingFolder.Type != (short)AssetType.Clothing)
2933 {
2934 clothingFolder = new InventoryFolderBase();
2935 clothingFolder.ID = UUID.Random();
2936 clothingFolder.Name = "Clothing";
2937 clothingFolder.Owner = ID;
2938 clothingFolder.Type = (short)AssetType.Clothing;
2939 clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID;
2940 clothingFolder.Version = 1;
2941 inventoryService.AddFolder(clothingFolder); // store base record
2942 m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID);
2943 }
2944  
2945 // OK, now we have an inventory for the user, read in the outfits from the
2946 // default appearance XMl file.
2947  
2948 XmlNodeList outfits = avatar.GetElementsByTagName("Ensemble");
2949 InventoryFolderBase extraFolder;
2950 string outfitName;
2951 UUID assetid;
2952  
2953 foreach (XmlElement outfit in outfits)
2954 {
2955 m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}",
2956 GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?"));
2957  
2958 outfitName = GetStringAttribute(outfit,"name","");
2959 select = (GetStringAttribute(outfit,"default","no") == "yes");
2960  
2961 // If the folder already exists, re-use it. The defaults may
2962 // change over time. Augment only.
2963  
2964 List<InventoryFolderBase> folders = inventoryService.GetFolderContent(ID, clothingFolder.ID).Folders;
2965 extraFolder = null;
2966  
2967 foreach (InventoryFolderBase folder in folders)
2968 {
2969 if (folder.Name == outfitName)
2970 {
2971 extraFolder = folder;
2972 break;
2973 }
2974 }
2975  
2976 // Otherwise, we must create the folder.
2977 if (extraFolder == null)
2978 {
2979 m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name);
2980 extraFolder = new InventoryFolderBase();
2981 extraFolder.ID = UUID.Random();
2982 extraFolder.Name = outfitName;
2983 extraFolder.Owner = ID;
2984 extraFolder.Type = (short)AssetType.Clothing;
2985 extraFolder.Version = 1;
2986 extraFolder.ParentID = clothingFolder.ID;
2987 inventoryService.AddFolder(extraFolder);
2988 m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
2989 }
2990  
2991 // Now get the pieces that make up the outfit
2992 XmlNodeList items = outfit.GetElementsByTagName("Item");
2993  
2994 foreach (XmlElement item in items)
2995 {
2996 assetid = UUID.Zero;
2997 XmlNodeList children = item.ChildNodes;
2998 foreach (XmlNode child in children)
2999 {
3000 switch (child.Name)
3001 {
3002 case "Permissions" :
3003 m_log.DebugFormat("[RADMIN]: Permissions specified");
3004 perms = child;
3005 break;
3006 case "Asset" :
3007 assetid = new UUID(child.InnerText);
3008 break;
3009 }
3010 }
3011  
3012 InventoryItemBase inventoryItem = null;
3013  
3014 // Check if asset is in inventory already
3015 inventoryItem = null;
3016 List<InventoryItemBase> inventoryItems = inventoryService.GetFolderContent(ID, extraFolder.ID).Items;
3017  
3018 foreach (InventoryItemBase listItem in inventoryItems)
3019 {
3020 if (listItem.AssetID == assetid)
3021 {
3022 inventoryItem = listItem;
3023 break;
3024 }
3025 }
3026  
3027 // Create inventory item
3028 if (inventoryItem == null)
3029 {
3030 inventoryItem = new InventoryItemBase(UUID.Random(), ID);
3031 inventoryItem.Name = GetStringAttribute(item,"name","");
3032 inventoryItem.Description = GetStringAttribute(item,"desc","");
3033 inventoryItem.InvType = GetIntegerAttribute(item,"invtype",-1);
3034 inventoryItem.CreatorId = GetStringAttribute(item,"creatorid","");
3035 inventoryItem.CreatorData = GetStringAttribute(item, "creatordata", "");
3036 inventoryItem.NextPermissions = GetUnsignedAttribute(perms, "next", 0x7fffffff);
3037 inventoryItem.CurrentPermissions = GetUnsignedAttribute(perms,"current",0x7fffffff);
3038 inventoryItem.BasePermissions = GetUnsignedAttribute(perms,"base",0x7fffffff);
3039 inventoryItem.EveryOnePermissions = GetUnsignedAttribute(perms,"everyone",0x7fffffff);
3040 inventoryItem.GroupPermissions = GetUnsignedAttribute(perms,"group",0x7fffffff);
3041 inventoryItem.AssetType = GetIntegerAttribute(item,"assettype",-1);
3042 inventoryItem.AssetID = assetid; // associated asset
3043 inventoryItem.GroupID = (UUID)GetStringAttribute(item,"groupid","");
3044 inventoryItem.GroupOwned = (GetStringAttribute(item,"groupowned","false") == "true");
3045 inventoryItem.SalePrice = GetIntegerAttribute(item,"saleprice",0);
3046 inventoryItem.SaleType = (byte)GetIntegerAttribute(item,"saletype",0);
3047 inventoryItem.Flags = GetUnsignedAttribute(item,"flags",0);
3048 inventoryItem.CreationDate = GetIntegerAttribute(item,"creationdate",Util.UnixTimeSinceEpoch());
3049 inventoryItem.Folder = extraFolder.ID; // Parent folder
3050  
3051 m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem);
3052 m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
3053 }
3054  
3055 // Attach item, if attachpoint is specified
3056 int attachpoint = GetIntegerAttribute(item,"attachpoint",0);
3057 if (attachpoint != 0)
3058 {
3059 avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID);
3060 m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID);
3061 }
3062  
3063 // Record whether or not the item is to be initially worn
3064 try
3065 {
3066 if (select && (GetStringAttribute(item, "wear", "false") == "true"))
3067 {
3068 avatarAppearance.Wearables[inventoryItem.Flags].Wear(inventoryItem.ID, inventoryItem.AssetID);
3069 }
3070 }
3071 catch (Exception e)
3072 {
3073 m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
3074 }
3075 } // foreach item in outfit
3076 m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName);
3077 } // foreach outfit
3078 m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name);
3079 scene.AvatarService.SetAppearance(ID, avatarAppearance);
3080 }
3081 catch (Exception e)
3082 {
3083 m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}",
3084 name, e.Message);
3085 }
3086 } // End of include
3087 }
3088 m_log.DebugFormat("[RADMIN]: Default avatar loading complete");
3089 }
3090 else
3091 {
3092 m_log.DebugFormat("[RADMIN]: No default avatar information available");
3093 return false;
3094 }
3095 }
3096 catch (Exception e)
3097 {
3098 m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message);
3099 return false;
3100 }
3101  
3102 return true;
3103 }
3104 }
3105 }