OpenSim.cs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  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. using System;
  28. using System.Threading;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Linq;
  34. using System.Reflection;
  35. using System.Runtime;
  36. using System.Text;
  37. using System.Text.RegularExpressions;
  38. using System.Timers;
  39. using System.Net;
  40. using log4net;
  41. using NDesk.Options;
  42. using Nini.Config;
  43. using OpenMetaverse;
  44. using OpenSim.Framework;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Framework.Servers;
  47. using OpenSim.Framework.Monitoring;
  48. using OpenSim.Region.Framework.Interfaces;
  49. using OpenSim.Region.Framework.Scenes;
  50. using OpenSim.Services.Interfaces;
  51. using OpenSim.Framework.Servers.HttpServer;
  52. namespace OpenSim
  53. {
  54. /// <summary>
  55. /// Interactive OpenSim region server
  56. /// </summary>
  57. public class OpenSim : OpenSimBase
  58. {
  59. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  60. protected string m_startupCommandsFile;
  61. protected string m_shutdownCommandsFile;
  62. protected bool m_gui = false;
  63. protected string m_consoleType = "local";
  64. protected uint m_consolePort = 0;
  65. /// <summary>
  66. /// Prompt to use for simulator command line.
  67. /// </summary>
  68. private string m_consolePrompt;
  69. /// <summary>
  70. /// Regex for parsing out special characters in the prompt.
  71. /// </summary>
  72. private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled);
  73. private string m_timedScript = "disabled";
  74. private int m_timeInterval = 1200;
  75. private System.Timers.Timer m_scriptTimer;
  76. public OpenSim(IConfigSource configSource) : base(configSource)
  77. {
  78. }
  79. protected override void ReadExtraConfigSettings()
  80. {
  81. base.ReadExtraConfigSettings();
  82. IConfig startupConfig = Config.Configs["Startup"];
  83. IConfig networkConfig = Config.Configs["Network"];
  84. int stpMinThreads = 2;
  85. int stpMaxThreads = 15;
  86. if (startupConfig != null)
  87. {
  88. m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt");
  89. m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt");
  90. if (startupConfig.GetString("console", String.Empty) == String.Empty)
  91. m_gui = startupConfig.GetBoolean("gui", false);
  92. else
  93. m_consoleType= startupConfig.GetString("console", String.Empty);
  94. if (networkConfig != null)
  95. m_consolePort = (uint)networkConfig.GetInt("console_port", 0);
  96. m_timedScript = startupConfig.GetString("timer_Script", "disabled");
  97. if (m_timedScript != "disabled")
  98. {
  99. m_timeInterval = startupConfig.GetInt("timer_Interval", 1200);
  100. }
  101. string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty);
  102. FireAndForgetMethod asyncCallMethod;
  103. if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod))
  104. Util.FireAndForgetMethod = asyncCallMethod;
  105. stpMinThreads = startupConfig.GetInt("MinPoolThreads", 2 );
  106. stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 25);
  107. m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) ");
  108. int dnsTimeout = startupConfig.GetInt("DnsTimeout", 30000);
  109. try { ServicePointManager.DnsRefreshTimeout = dnsTimeout; } catch { }
  110. }
  111. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  112. Util.InitThreadPool(stpMinThreads, stpMaxThreads);
  113. m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod);
  114. m_log.InfoFormat("[OPENSIM MAIN] Running GC in {0} mode", GCSettings.IsServerGC ? "server":"workstation");
  115. }
  116. #if (_MONO)
  117. private static Mono.Unix.UnixSignal[] signals;
  118. private Thread signal_thread = new Thread (delegate ()
  119. {
  120. while (true)
  121. {
  122. // Wait for a signal to be delivered
  123. int index = Mono.Unix.UnixSignal.WaitAny (signals, -1);
  124. //Mono.Unix.Native.Signum signal = signals [index].Signum;
  125. MainConsole.Instance.RunCommand("shutdown");
  126. }
  127. });
  128. #endif
  129. /// <summary>
  130. /// Performs initialisation of the scene, such as loading configuration from disk.
  131. /// </summary>
  132. protected override void StartupSpecific()
  133. {
  134. m_log.Info("====================================================================");
  135. m_log.Info("========================= STARTING OPENSIM =========================");
  136. m_log.Info("====================================================================");
  137. #if (_MONO)
  138. if(!Util.IsWindows())
  139. {
  140. try
  141. {
  142. // linux mac os specifics
  143. signals = new Mono.Unix.UnixSignal[]
  144. {
  145. new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM)
  146. };
  147. signal_thread.IsBackground = true;
  148. signal_thread.Start();
  149. }
  150. catch (Exception e)
  151. {
  152. m_log.Info("Could not set up UNIX signal handlers. SIGTERM will not");
  153. m_log.InfoFormat("shut down gracefully: {0}", e.Message);
  154. m_log.Debug("Exception was: ", e);
  155. }
  156. }
  157. #endif
  158. //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
  159. // http://msdn.microsoft.com/en-us/library/bb384202.aspx
  160. //GCSettings.LatencyMode = GCLatencyMode.Batch;
  161. //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString());
  162. if (m_gui) // Driven by external GUI
  163. {
  164. m_console = new CommandConsole("Region");
  165. }
  166. else
  167. {
  168. switch (m_consoleType)
  169. {
  170. case "basic":
  171. m_console = new CommandConsole("Region");
  172. break;
  173. case "rest":
  174. m_console = new RemoteConsole("Region");
  175. break;
  176. default:
  177. m_console = new LocalConsole("Region", Config.Configs["Startup"]);
  178. break;
  179. }
  180. }
  181. m_console.ReadConfig(Config);
  182. MainConsole.Instance = m_console;
  183. LogEnvironmentInformation();
  184. RegisterCommonAppenders(Config.Configs["Startup"]);
  185. RegisterConsoleCommands();
  186. base.StartupSpecific();
  187. MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler());
  188. MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this));
  189. if (userStatsURI != String.Empty)
  190. MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this));
  191. MainServer.Instance.AddStreamHandler(new OpenSim.SimRobotsHandler());
  192. if (managedStatsURI != String.Empty)
  193. {
  194. string urlBase = String.Format("/{0}/", managedStatsURI);
  195. StatsManager.StatsPassword = managedStatsPassword;
  196. MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest);
  197. m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase);
  198. }
  199. MethodInfo mi = m_console.GetType().GetMethod("SetServer", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(BaseHttpServer) }, null);
  200. if (mi != null)
  201. {
  202. if (m_consolePort == 0)
  203. mi.Invoke(m_console, new object[] { m_httpServer });
  204. else
  205. mi.Invoke(m_console, new object[] { MainServer.GetHttpServer(m_consolePort) });
  206. }
  207. // Hook up to the watchdog timer
  208. Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler;
  209. PrintFileToConsole("startuplogo.txt");
  210. // For now, start at the 'root' level by default
  211. if (SceneManager.Scenes.Count == 1) // If there is only one region, select it
  212. ChangeSelectedRegion("region",
  213. new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName});
  214. else
  215. ChangeSelectedRegion("region", new string[] {"change", "region", "root"});
  216. //Run Startup Commands
  217. if (String.IsNullOrEmpty(m_startupCommandsFile))
  218. {
  219. m_log.Info("[STARTUP]: No startup command script specified. Moving on...");
  220. }
  221. else
  222. {
  223. RunCommandScript(m_startupCommandsFile);
  224. }
  225. // Start timer script (run a script every xx seconds)
  226. if (m_timedScript != "disabled")
  227. {
  228. m_scriptTimer = new System.Timers.Timer();
  229. m_scriptTimer.Enabled = true;
  230. m_scriptTimer.Interval = m_timeInterval*1000;
  231. m_scriptTimer.Elapsed += RunAutoTimerScript;
  232. }
  233. }
  234. /// <summary>
  235. /// Register standard set of region console commands
  236. /// </summary>
  237. private void RegisterConsoleCommands()
  238. {
  239. MainServer.RegisterHttpConsoleCommands(m_console);
  240. m_console.Commands.AddCommand("Objects", false, "force update",
  241. "force update",
  242. "Force the update of all objects on clients",
  243. HandleForceUpdate);
  244. m_console.Commands.AddCommand("General", false, "change region",
  245. "change region <region name>",
  246. "Change current console region",
  247. ChangeSelectedRegion);
  248. m_console.Commands.AddCommand("Archiving", false, "save xml",
  249. "save xml [<file name>]",
  250. "Save a region's data in XML format",
  251. SaveXml);
  252. m_console.Commands.AddCommand("Archiving", false, "save xml2",
  253. "save xml2 [<file name>]",
  254. "Save a region's data in XML2 format",
  255. SaveXml2);
  256. m_console.Commands.AddCommand("Archiving", false, "load xml",
  257. "load xml [<file name> [-newUID [<x> <y> <z>]]]",
  258. "Load a region's data from XML format",
  259. LoadXml);
  260. m_console.Commands.AddCommand("Archiving", false, "load xml2",
  261. "load xml2 [<file name>]",
  262. "Load a region's data from XML2 format",
  263. LoadXml2);
  264. m_console.Commands.AddCommand("Archiving", false, "save prims xml2",
  265. "save prims xml2 [<prim name> <file name>]",
  266. "Save named prim to XML2",
  267. SavePrimsXml2);
  268. m_console.Commands.AddCommand("Archiving", false, "load oar",
  269. "load oar [-m|--merge] [-s|--skip-assets]"
  270. + " [--default-user \"User Name\"]"
  271. + " [--force-terrain] [--force-parcels]"
  272. + " [--no-objects]"
  273. + " [--rotation degrees]"
  274. + " [--bounding-origin \"<x,y,z>\"]"
  275. + " [--bounding-size \"<x,y,z>\"]"
  276. + " [--displacement \"<x,y,z>\"]"
  277. + " [-d|--debug]"
  278. + " [<OAR path>]",
  279. "Load a region's data from an OAR archive.",
  280. "--merge will merge the OAR with the existing scene (suppresses terrain and parcel info loading).\n"
  281. + "--skip-assets will load the OAR but ignore the assets it contains.\n"
  282. + "--default-user will use this user for any objects with an owner whose UUID is not found in the grid.\n"
  283. + "--force-terrain forces the loading of terrain from the oar (undoes suppression done by --merge).\n"
  284. + "--force-parcels forces the loading of parcels from the oar (undoes suppression done by --merge).\n"
  285. + "--no-objects suppresses the addition of any objects (good for loading only the terrain).\n"
  286. + "--rotation specified rotation to be applied to the oar. Specified in degrees.\n"
  287. + "--bounding-origin will only place objects that after displacement and rotation fall within the bounding cube who's position starts at <x,y,z>. Defaults to <0,0,0>.\n"
  288. + "--bounding-size specifies the size of the bounding cube. The default is the size of the destination region and cannot be larger than this.\n"
  289. + "--displacement will add this value to the position of every object loaded.\n"
  290. + "--debug forces the archiver to display messages about where each object is being placed.\n\n"
  291. + "The path can be either a filesystem location or a URI.\n"
  292. + " If this is not given then the command looks for an OAR named region.oar in the current directory."
  293. + " [--rotation-center \"<x,y,z>\"] used to be an option, now it does nothing and will be removed soon."
  294. + "When an OAR is being loaded, operations are applied in this order:\n"
  295. + "1: Rotation (around the incoming OARs region center)\n"
  296. + "2: Cropping (a bounding cube with origin and size)\n"
  297. + "3: Displacement (setting offset coordinates within the destination region)",
  298. LoadOar); ;
  299. m_console.Commands.AddCommand("Archiving", false, "save oar",
  300. //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]",
  301. "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]",
  302. "Save a region's data to an OAR archive.",
  303. // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine
  304. "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
  305. + "--noassets stops assets being saved to the OAR.\n"
  306. + "--publish saves an OAR stripped of owner and last owner information.\n"
  307. + " on reload, the estate owner will be the owner of all objects\n"
  308. + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n"
  309. + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n"
  310. + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n"
  311. + "--all saves all the regions in the simulator, instead of just the current region.\n"
  312. + "The OAR path must be a filesystem path."
  313. + " If this is not given then the oar is saved to region.oar in the current directory.",
  314. SaveOar);
  315. m_console.Commands.AddCommand("Objects", false, "edit scale",
  316. "edit scale <name> <x> <y> <z>",
  317. "Change the scale of a named prim",
  318. HandleEditScale);
  319. m_console.Commands.AddCommand("Objects", false, "rotate scene",
  320. "rotate scene <degrees> [centerX, centerY]",
  321. "Rotates all scene objects around centerX, centerY (default 128, 128) (please back up your region before using)",
  322. HandleRotateScene);
  323. m_console.Commands.AddCommand("Objects", false, "scale scene",
  324. "scale scene <factor>",
  325. "Scales the scene objects (please back up your region before using)",
  326. HandleScaleScene);
  327. m_console.Commands.AddCommand("Objects", false, "translate scene",
  328. "translate scene xOffset yOffset zOffset",
  329. "translates the scene objects (please back up your region before using)",
  330. HandleTranslateScene);
  331. m_console.Commands.AddCommand("Users", false, "kick user",
  332. "kick user <first> <last> [--force] [message]",
  333. "Kick a user off the simulator",
  334. "The --force option will kick the user without any checks to see whether it's already in the process of closing\n"
  335. + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them",
  336. KickUserCommand);
  337. m_console.Commands.AddCommand("Users", false, "show users",
  338. "show users [full]",
  339. "Show user data for users currently on the region",
  340. "Without the 'full' option, only users actually on the region are shown."
  341. + " With the 'full' option child agents of users in neighbouring regions are also shown.",
  342. HandleShow);
  343. m_console.Commands.AddCommand("Comms", false, "show connections",
  344. "show connections",
  345. "Show connection data",
  346. HandleShow);
  347. m_console.Commands.AddCommand("Comms", false, "show circuits",
  348. "show circuits",
  349. "Show agent circuit data",
  350. HandleShow);
  351. m_console.Commands.AddCommand("Comms", false, "show pending-objects",
  352. "show pending-objects",
  353. "Show # of objects on the pending queues of all scene viewers",
  354. HandleShow);
  355. m_console.Commands.AddCommand("General", false, "show modules",
  356. "show modules",
  357. "Show module data",
  358. HandleShow);
  359. m_console.Commands.AddCommand("Regions", false, "show regions",
  360. "show regions",
  361. "Show region data",
  362. HandleShow);
  363. m_console.Commands.AddCommand("Regions", false, "show ratings",
  364. "show ratings",
  365. "Show rating data",
  366. HandleShow);
  367. m_console.Commands.AddCommand("Objects", false, "backup",
  368. "backup",
  369. "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.",
  370. RunCommand);
  371. m_console.Commands.AddCommand("Regions", false, "create region",
  372. "create region [\"region name\"] <region_file.ini>",
  373. "Create a new region.",
  374. "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given."
  375. + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine
  376. + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine
  377. + "If <region_file.ini> does not exist, it will be created.",
  378. HandleCreateRegion);
  379. m_console.Commands.AddCommand("Regions", false, "restart",
  380. "restart",
  381. "Restart the currently selected region(s) in this instance",
  382. RunCommand);
  383. m_console.Commands.AddCommand("General", false, "command-script",
  384. "command-script <script>",
  385. "Run a command script from file",
  386. RunCommand);
  387. m_console.Commands.AddCommand("Regions", false, "remove-region",
  388. "remove-region <name>",
  389. "Remove a region from this simulator",
  390. RunCommand);
  391. m_console.Commands.AddCommand("Regions", false, "delete-region",
  392. "delete-region <name>",
  393. "Delete a region from disk",
  394. RunCommand);
  395. m_console.Commands.AddCommand("Estates", false, "estate create",
  396. "estate create <owner UUID> <estate name>",
  397. "Creates a new estate with the specified name, owned by the specified user."
  398. + " Estate name must be unique.",
  399. CreateEstateCommand);
  400. m_console.Commands.AddCommand("Estates", false, "estate set owner",
  401. "estate set owner <estate-id>[ <UUID> | <Firstname> <Lastname> ]",
  402. "Sets the owner of the specified estate to the specified UUID or user. ",
  403. SetEstateOwnerCommand);
  404. m_console.Commands.AddCommand("Estates", false, "estate set name",
  405. "estate set name <estate-id> <new name>",
  406. "Sets the name of the specified estate to the specified value. New name must be unique.",
  407. SetEstateNameCommand);
  408. m_console.Commands.AddCommand("Estates", false, "estate link region",
  409. "estate link region <estate ID> <region ID>",
  410. "Attaches the specified region to the specified estate.",
  411. EstateLinkRegionCommand);
  412. }
  413. protected override void ShutdownSpecific()
  414. {
  415. if (m_shutdownCommandsFile != String.Empty)
  416. {
  417. RunCommandScript(m_shutdownCommandsFile);
  418. }
  419. if (m_timedScript != "disabled")
  420. {
  421. m_scriptTimer.Dispose();
  422. m_timedScript = "disabled";
  423. }
  424. base.ShutdownSpecific();
  425. }
  426. /// <summary>
  427. /// Timer to run a specific text file as console commands. Configured in in the main ini file
  428. /// </summary>
  429. /// <param name="sender"></param>
  430. /// <param name="e"></param>
  431. private void RunAutoTimerScript(object sender, EventArgs e)
  432. {
  433. if (m_timedScript != "disabled")
  434. {
  435. RunCommandScript(m_timedScript);
  436. }
  437. }
  438. private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi)
  439. {
  440. int now = Environment.TickCount & Int32.MaxValue;
  441. m_log.ErrorFormat(
  442. "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}",
  443. twi.Thread.Name,
  444. twi.Thread.ThreadState,
  445. now - twi.LastTick,
  446. twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : "");
  447. }
  448. #region Console Commands
  449. /// <summary>
  450. /// Kicks users off the region
  451. /// </summary>
  452. /// <param name="module"></param>
  453. /// <param name="cmdparams">name of avatar to kick</param>
  454. private void KickUserCommand(string module, string[] cmdparams)
  455. {
  456. bool force = false;
  457. OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; });
  458. List<string> mainParams = options.Parse(cmdparams);
  459. if (mainParams.Count < 4)
  460. return;
  461. string alert = null;
  462. if (mainParams.Count > 4)
  463. alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
  464. IList agents = SceneManager.GetCurrentSceneAvatars();
  465. foreach (ScenePresence presence in agents)
  466. {
  467. RegionInfo regionInfo = presence.Scene.RegionInfo;
  468. if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) &&
  469. presence.Lastname.ToLower().Equals(mainParams[3].ToLower()))
  470. {
  471. MainConsole.Instance.Output(
  472. String.Format(
  473. "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}",
  474. presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName));
  475. // kick client...
  476. if (alert != null)
  477. presence.ControllingClient.Kick(alert);
  478. else
  479. presence.ControllingClient.Kick("\nYou have been logged out by an administrator.\n");
  480. presence.Scene.CloseAgent(presence.UUID, force);
  481. break;
  482. }
  483. }
  484. MainConsole.Instance.Output("");
  485. }
  486. /// <summary>
  487. /// Opens a file and uses it as input to the console command parser.
  488. /// </summary>
  489. /// <param name="fileName">name of file to use as input to the console</param>
  490. private static void PrintFileToConsole(string fileName)
  491. {
  492. if (File.Exists(fileName))
  493. {
  494. StreamReader readFile = File.OpenText(fileName);
  495. string currentLine;
  496. while ((currentLine = readFile.ReadLine()) != null)
  497. {
  498. m_log.Info("[!]" + currentLine);
  499. }
  500. }
  501. }
  502. /// <summary>
  503. /// Force resending of all updates to all clients in active region(s)
  504. /// </summary>
  505. /// <param name="module"></param>
  506. /// <param name="args"></param>
  507. private void HandleForceUpdate(string module, string[] args)
  508. {
  509. MainConsole.Instance.Output("Updating all clients");
  510. SceneManager.ForceCurrentSceneClientUpdate();
  511. }
  512. /// <summary>
  513. /// Edits the scale of a primative with the name specified
  514. /// </summary>
  515. /// <param name="module"></param>
  516. /// <param name="args">0,1, name, x, y, z</param>
  517. private void HandleEditScale(string module, string[] args)
  518. {
  519. if (args.Length == 6)
  520. {
  521. SceneManager.HandleEditCommandOnCurrentScene(args);
  522. }
  523. else
  524. {
  525. MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>");
  526. }
  527. }
  528. private void HandleRotateScene(string module, string[] args)
  529. {
  530. string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2";
  531. float centerX = Constants.RegionSize * 0.5f;
  532. float centerY = Constants.RegionSize * 0.5f;
  533. if (args.Length < 3 || args.Length == 4)
  534. {
  535. MainConsole.Instance.Output(usage);
  536. return;
  537. }
  538. float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI);
  539. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle);
  540. if (args.Length > 4)
  541. {
  542. centerX = Convert.ToSingle(args[3]);
  543. centerY = Convert.ToSingle(args[4]);
  544. }
  545. Vector3 center = new Vector3(centerX, centerY, 0.0f);
  546. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  547. {
  548. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  549. {
  550. if (!sog.IsAttachment)
  551. {
  552. sog.RootPart.UpdateRotation(rot * sog.GroupRotation);
  553. Vector3 offset = sog.AbsolutePosition - center;
  554. offset *= rot;
  555. sog.UpdateGroupPosition(center + offset);
  556. }
  557. });
  558. });
  559. }
  560. private void HandleScaleScene(string module, string[] args)
  561. {
  562. string usage = "Usage: scale scene <factor>";
  563. if (args.Length < 3)
  564. {
  565. MainConsole.Instance.Output(usage);
  566. return;
  567. }
  568. float factor = (float)(Convert.ToSingle(args[2]));
  569. float minZ = float.MaxValue;
  570. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  571. {
  572. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  573. {
  574. if (!sog.IsAttachment)
  575. {
  576. if (sog.RootPart.AbsolutePosition.Z < minZ)
  577. minZ = sog.RootPart.AbsolutePosition.Z;
  578. }
  579. });
  580. });
  581. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  582. {
  583. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  584. {
  585. if (!sog.IsAttachment)
  586. {
  587. Vector3 tmpRootPos = sog.RootPart.AbsolutePosition;
  588. tmpRootPos.Z -= minZ;
  589. tmpRootPos *= factor;
  590. tmpRootPos.Z += minZ;
  591. foreach (SceneObjectPart sop in sog.Parts)
  592. {
  593. if (sop.ParentID != 0)
  594. sop.OffsetPosition *= factor;
  595. sop.Scale *= factor;
  596. }
  597. sog.UpdateGroupPosition(tmpRootPos);
  598. }
  599. });
  600. });
  601. }
  602. private void HandleTranslateScene(string module, string[] args)
  603. {
  604. string usage = "Usage: translate scene <xOffset, yOffset, zOffset>";
  605. if (args.Length < 5)
  606. {
  607. MainConsole.Instance.Output(usage);
  608. return;
  609. }
  610. float xOFfset = (float)Convert.ToSingle(args[2]);
  611. float yOffset = (float)Convert.ToSingle(args[3]);
  612. float zOffset = (float)Convert.ToSingle(args[4]);
  613. Vector3 offset = new Vector3(xOFfset, yOffset, zOffset);
  614. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  615. {
  616. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  617. {
  618. if (!sog.IsAttachment)
  619. sog.UpdateGroupPosition(sog.AbsolutePosition + offset);
  620. });
  621. });
  622. }
  623. /// <summary>
  624. /// Creates a new region based on the parameters specified. This will ask the user questions on the console
  625. /// </summary>
  626. /// <param name="module"></param>
  627. /// <param name="cmd">0,1,region name, region ini or XML file</param>
  628. private void HandleCreateRegion(string module, string[] cmd)
  629. {
  630. string regionName = string.Empty;
  631. string regionFile = string.Empty;
  632. if (cmd.Length == 3)
  633. {
  634. regionFile = cmd[2];
  635. }
  636. else if (cmd.Length > 3)
  637. {
  638. regionName = cmd[2];
  639. regionFile = cmd[3];
  640. }
  641. string extension = Path.GetExtension(regionFile).ToLower();
  642. bool isXml = extension.Equals(".xml");
  643. bool isIni = extension.Equals(".ini");
  644. if (!isXml && !isIni)
  645. {
  646. MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>");
  647. return;
  648. }
  649. if (!Path.IsPathRooted(regionFile))
  650. {
  651. string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim();
  652. regionFile = Path.Combine(regionsDir, regionFile);
  653. }
  654. RegionInfo regInfo;
  655. if (isXml)
  656. {
  657. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source);
  658. }
  659. else
  660. {
  661. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName);
  662. }
  663. Scene existingScene;
  664. if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene))
  665. {
  666. MainConsole.Instance.Output(
  667. "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}",
  668. regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName);
  669. return;
  670. }
  671. bool changed = PopulateRegionEstateInfo(regInfo);
  672. IScene scene;
  673. CreateRegion(regInfo, true, out scene);
  674. if (changed)
  675. m_estateDataService.StoreEstateSettings(regInfo.EstateSettings);
  676. scene.Start();
  677. }
  678. /// <summary>
  679. /// Runs commands issued by the server console from the operator
  680. /// </summary>
  681. /// <param name="command">The first argument of the parameter (the command)</param>
  682. /// <param name="cmdparams">Additional arguments passed to the command</param>
  683. public void RunCommand(string module, string[] cmdparams)
  684. {
  685. List<string> args = new List<string>(cmdparams);
  686. if (args.Count < 1)
  687. return;
  688. string command = args[0];
  689. args.RemoveAt(0);
  690. cmdparams = args.ToArray();
  691. switch (command)
  692. {
  693. case "backup":
  694. MainConsole.Instance.Output("Triggering save of pending object updates to persistent store");
  695. SceneManager.BackupCurrentScene();
  696. break;
  697. case "remove-region":
  698. string regRemoveName = CombineParams(cmdparams, 0);
  699. Scene removeScene;
  700. if (SceneManager.TryGetScene(regRemoveName, out removeScene))
  701. RemoveRegion(removeScene, false);
  702. else
  703. MainConsole.Instance.Output("No region with that name");
  704. break;
  705. case "delete-region":
  706. string regDeleteName = CombineParams(cmdparams, 0);
  707. Scene killScene;
  708. if (SceneManager.TryGetScene(regDeleteName, out killScene))
  709. RemoveRegion(killScene, true);
  710. else
  711. MainConsole.Instance.Output("no region with that name");
  712. break;
  713. case "restart":
  714. SceneManager.RestartCurrentScene();
  715. break;
  716. }
  717. }
  718. /// <summary>
  719. /// Change the currently selected region. The selected region is that operated upon by single region commands.
  720. /// </summary>
  721. /// <param name="cmdParams"></param>
  722. protected void ChangeSelectedRegion(string module, string[] cmdparams)
  723. {
  724. if (cmdparams.Length > 2)
  725. {
  726. string newRegionName = CombineParams(cmdparams, 2);
  727. if (!SceneManager.TrySetCurrentScene(newRegionName))
  728. MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName));
  729. else
  730. RefreshPrompt();
  731. }
  732. else
  733. {
  734. MainConsole.Instance.Output("Usage: change region <region name>");
  735. }
  736. }
  737. /// <summary>
  738. /// Refreshs prompt with the current selection details.
  739. /// </summary>
  740. private void RefreshPrompt()
  741. {
  742. string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName);
  743. MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName));
  744. // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt);
  745. string prompt = m_consolePrompt;
  746. // Replace "\R" with the region name
  747. // Replace "\\" with "\"
  748. prompt = m_consolePromptRegex.Replace(prompt, m =>
  749. {
  750. // m_log.DebugFormat("Matched {0}", m.Groups[2].Value);
  751. if (m.Groups[2].Value == "R")
  752. return m.Groups[1].Value + regionName;
  753. else
  754. return m.Groups[0].Value;
  755. });
  756. m_console.DefaultPrompt = prompt;
  757. m_console.ConsoleScene = SceneManager.CurrentScene;
  758. }
  759. protected override void HandleRestartRegion(RegionInfo whichRegion)
  760. {
  761. base.HandleRestartRegion(whichRegion);
  762. // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the
  763. // m_console.ConsoleScene to null (indicating all scenes).
  764. if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name)
  765. SceneManager.TrySetCurrentScene(whichRegion.RegionName);
  766. RefreshPrompt();
  767. }
  768. // see BaseOpenSimServer
  769. /// <summary>
  770. /// Many commands list objects for debugging. Some of the types are listed here
  771. /// </summary>
  772. /// <param name="mod"></param>
  773. /// <param name="cmd"></param>
  774. public override void HandleShow(string mod, string[] cmd)
  775. {
  776. base.HandleShow(mod, cmd);
  777. List<string> args = new List<string>(cmd);
  778. args.RemoveAt(0);
  779. string[] showParams = args.ToArray();
  780. switch (showParams[0])
  781. {
  782. case "users":
  783. IList agents;
  784. if (showParams.Length > 1 && showParams[1] == "full")
  785. {
  786. agents = SceneManager.GetCurrentScenePresences();
  787. } else
  788. {
  789. agents = SceneManager.GetCurrentSceneAvatars();
  790. }
  791. MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count));
  792. MainConsole.Instance.Output(
  793. String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname",
  794. "Agent ID", "Root/Child", "Region", "Position")
  795. );
  796. foreach (ScenePresence presence in agents)
  797. {
  798. RegionInfo regionInfo = presence.Scene.RegionInfo;
  799. string regionName;
  800. if (regionInfo == null)
  801. {
  802. regionName = "Unresolvable";
  803. } else
  804. {
  805. regionName = regionInfo.RegionName;
  806. }
  807. MainConsole.Instance.Output(
  808. String.Format(
  809. "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}",
  810. presence.Firstname,
  811. presence.Lastname,
  812. presence.UUID,
  813. presence.IsChildAgent ? "Child" : "Root",
  814. regionName,
  815. presence.AbsolutePosition.ToString())
  816. );
  817. }
  818. MainConsole.Instance.Output(String.Empty);
  819. break;
  820. case "connections":
  821. HandleShowConnections();
  822. break;
  823. case "circuits":
  824. HandleShowCircuits();
  825. break;
  826. case "modules":
  827. SceneManager.ForEachSelectedScene(
  828. scene =>
  829. {
  830. MainConsole.Instance.Output("Loaded region modules in {0} are:", scene.Name);
  831. List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>();
  832. List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>();
  833. foreach (IRegionModuleBase module in scene.RegionModules.Values)
  834. {
  835. if (module.GetType().GetInterface("ISharedRegionModule") == null)
  836. nonSharedModules.Add(module);
  837. else
  838. sharedModules.Add(module);
  839. }
  840. foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name))
  841. MainConsole.Instance.Output("New Region Module (Shared): {0}", module.Name);
  842. foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name))
  843. MainConsole.Instance.Output("New Region Module (Non-Shared): {0}", module.Name);
  844. }
  845. );
  846. MainConsole.Instance.Output("");
  847. break;
  848. case "regions":
  849. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  850. cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize);
  851. cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize);
  852. cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize);
  853. cdt.AddColumn("Size", 11);
  854. cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize);
  855. cdt.AddColumn("Ready?", 6);
  856. cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize);
  857. SceneManager.ForEachScene(
  858. scene =>
  859. {
  860. RegionInfo ri = scene.RegionInfo;
  861. cdt.AddRow(
  862. ri.RegionName,
  863. ri.RegionID,
  864. string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY),
  865. string.Format("{0}x{1}", ri.RegionSizeX, ri.RegionSizeY),
  866. ri.InternalEndPoint.Port,
  867. scene.Ready ? "Yes" : "No",
  868. ri.EstateSettings.EstateName);
  869. }
  870. );
  871. MainConsole.Instance.Output(cdt.ToString());
  872. break;
  873. case "ratings":
  874. SceneManager.ForEachScene(
  875. delegate(Scene scene)
  876. {
  877. string rating = "";
  878. if (scene.RegionInfo.RegionSettings.Maturity == 1)
  879. {
  880. rating = "MATURE";
  881. }
  882. else if (scene.RegionInfo.RegionSettings.Maturity == 2)
  883. {
  884. rating = "ADULT";
  885. }
  886. else
  887. {
  888. rating = "PG";
  889. }
  890. MainConsole.Instance.Output(String.Format(
  891. "Region Name: {0}, Region Rating {1}",
  892. scene.RegionInfo.RegionName,
  893. rating));
  894. });
  895. break;
  896. }
  897. }
  898. private void HandleShowCircuits()
  899. {
  900. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  901. cdt.AddColumn("Region", 20);
  902. cdt.AddColumn("Avatar name", 24);
  903. cdt.AddColumn("Type", 5);
  904. cdt.AddColumn("Code", 10);
  905. cdt.AddColumn("IP", 16);
  906. cdt.AddColumn("Viewer Name", 24);
  907. SceneManager.ForEachScene(
  908. s =>
  909. {
  910. foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values)
  911. cdt.AddRow(
  912. s.Name,
  913. aCircuit.Name,
  914. aCircuit.child ? "child" : "root",
  915. aCircuit.circuitcode.ToString(),
  916. aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set",
  917. Util.GetViewerName(aCircuit));
  918. });
  919. MainConsole.Instance.Output(cdt.ToString());
  920. }
  921. private void HandleShowConnections()
  922. {
  923. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  924. cdt.AddColumn("Region", 20);
  925. cdt.AddColumn("Avatar name", 24);
  926. cdt.AddColumn("Circuit code", 12);
  927. cdt.AddColumn("Endpoint", 23);
  928. cdt.AddColumn("Active?", 7);
  929. cdt.AddColumn("ChildAgent?", 7);
  930. cdt.AddColumn("ping(ms)", 8);
  931. SceneManager.ForEachScene(
  932. s => s.ForEachClient(
  933. c =>
  934. {
  935. bool child = false;
  936. if(c.SceneAgent != null && c.SceneAgent.IsChildAgent)
  937. child = true;
  938. cdt.AddRow(
  939. s.Name,
  940. c.Name,
  941. c.CircuitCode.ToString(),
  942. c.RemoteEndPoint.ToString(),
  943. c.IsActive.ToString(),
  944. child.ToString(),
  945. c.PingTimeMS);
  946. }));
  947. MainConsole.Instance.Output(cdt.ToString());
  948. }
  949. /// <summary>
  950. /// Use XML2 format to serialize data to a file
  951. /// </summary>
  952. /// <param name="module"></param>
  953. /// <param name="cmdparams"></param>
  954. protected void SavePrimsXml2(string module, string[] cmdparams)
  955. {
  956. if (cmdparams.Length > 4)
  957. {
  958. SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]);
  959. }
  960. else
  961. {
  962. SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME);
  963. }
  964. }
  965. /// <summary>
  966. /// Use XML format to serialize data to a file
  967. /// </summary>
  968. /// <param name="module"></param>
  969. /// <param name="cmdparams"></param>
  970. protected void SaveXml(string module, string[] cmdparams)
  971. {
  972. MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason.");
  973. if (cmdparams.Length > 2)
  974. {
  975. SceneManager.SaveCurrentSceneToXml(cmdparams[2]);
  976. }
  977. else
  978. {
  979. SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME);
  980. }
  981. }
  982. /// <summary>
  983. /// Loads data and region objects from XML format.
  984. /// </summary>
  985. /// <param name="module"></param>
  986. /// <param name="cmdparams"></param>
  987. protected void LoadXml(string module, string[] cmdparams)
  988. {
  989. MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason.");
  990. Vector3 loadOffset = new Vector3(0, 0, 0);
  991. if (cmdparams.Length > 2)
  992. {
  993. bool generateNewIDS = false;
  994. if (cmdparams.Length > 3)
  995. {
  996. if (cmdparams[3] == "-newUID")
  997. {
  998. generateNewIDS = true;
  999. }
  1000. if (cmdparams.Length > 4)
  1001. {
  1002. loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo);
  1003. if (cmdparams.Length > 5)
  1004. {
  1005. loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo);
  1006. }
  1007. if (cmdparams.Length > 6)
  1008. {
  1009. loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo);
  1010. }
  1011. MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z));
  1012. }
  1013. }
  1014. SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset);
  1015. }
  1016. else
  1017. {
  1018. try
  1019. {
  1020. SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset);
  1021. }
  1022. catch (FileNotFoundException)
  1023. {
  1024. MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>");
  1025. }
  1026. }
  1027. }
  1028. /// <summary>
  1029. /// Serialize region data to XML2Format
  1030. /// </summary>
  1031. /// <param name="module"></param>
  1032. /// <param name="cmdparams"></param>
  1033. protected void SaveXml2(string module, string[] cmdparams)
  1034. {
  1035. if (cmdparams.Length > 2)
  1036. {
  1037. SceneManager.SaveCurrentSceneToXml2(cmdparams[2]);
  1038. }
  1039. else
  1040. {
  1041. SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  1042. }
  1043. }
  1044. /// <summary>
  1045. /// Load region data from Xml2Format
  1046. /// </summary>
  1047. /// <param name="module"></param>
  1048. /// <param name="cmdparams"></param>
  1049. protected void LoadXml2(string module, string[] cmdparams)
  1050. {
  1051. if (cmdparams.Length > 2)
  1052. {
  1053. try
  1054. {
  1055. SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]);
  1056. }
  1057. catch (FileNotFoundException)
  1058. {
  1059. MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>");
  1060. }
  1061. }
  1062. else
  1063. {
  1064. try
  1065. {
  1066. SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  1067. }
  1068. catch (FileNotFoundException)
  1069. {
  1070. MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>");
  1071. }
  1072. }
  1073. }
  1074. /// <summary>
  1075. /// Load a whole region from an opensimulator archive.
  1076. /// </summary>
  1077. /// <param name="cmdparams"></param>
  1078. protected void LoadOar(string module, string[] cmdparams)
  1079. {
  1080. try
  1081. {
  1082. SceneManager.LoadArchiveToCurrentScene(cmdparams);
  1083. }
  1084. catch (Exception e)
  1085. {
  1086. MainConsole.Instance.Output(e.Message);
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// Save a region to a file, including all the assets needed to restore it.
  1091. /// </summary>
  1092. /// <param name="cmdparams"></param>
  1093. protected void SaveOar(string module, string[] cmdparams)
  1094. {
  1095. SceneManager.SaveCurrentSceneToArchive(cmdparams);
  1096. }
  1097. protected void CreateEstateCommand(string module, string[] args)
  1098. {
  1099. string response = null;
  1100. UUID userID;
  1101. if (args.Length == 2)
  1102. {
  1103. response = "No user specified.";
  1104. }
  1105. else if (!UUID.TryParse(args[2], out userID))
  1106. {
  1107. response = String.Format("{0} is not a valid UUID", args[2]);
  1108. }
  1109. else if (args.Length == 3)
  1110. {
  1111. response = "No estate name specified.";
  1112. }
  1113. else
  1114. {
  1115. Scene scene = SceneManager.CurrentOrFirstScene;
  1116. // TODO: Is there a better choice here?
  1117. UUID scopeID = UUID.Zero;
  1118. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, userID);
  1119. if (account == null)
  1120. {
  1121. response = String.Format("Could not find user {0}", userID);
  1122. }
  1123. else
  1124. {
  1125. // concatenate it all to "name"
  1126. StringBuilder sb = new StringBuilder(args[3]);
  1127. for (int i = 4; i < args.Length; i++)
  1128. sb.Append (" " + args[i]);
  1129. string estateName = sb.ToString().Trim();
  1130. // send it off for processing.
  1131. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1132. response = estateModule.CreateEstate(estateName, userID);
  1133. if (response == String.Empty)
  1134. {
  1135. List<int> estates = scene.EstateDataService.GetEstates(estateName);
  1136. response = String.Format("Estate {0} created as \"{1}\"", estates.ElementAt(0), estateName);
  1137. }
  1138. }
  1139. }
  1140. // give the user some feedback
  1141. if (response != null)
  1142. MainConsole.Instance.Output(response);
  1143. }
  1144. protected void SetEstateOwnerCommand(string module, string[] args)
  1145. {
  1146. string response = null;
  1147. Scene scene = SceneManager.CurrentOrFirstScene;
  1148. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1149. if (args.Length == 3)
  1150. {
  1151. response = "No estate specified.";
  1152. }
  1153. else
  1154. {
  1155. int estateId;
  1156. if (!int.TryParse(args[3], out estateId))
  1157. {
  1158. response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]);
  1159. }
  1160. else
  1161. {
  1162. if (args.Length == 4)
  1163. {
  1164. response = "No user specified.";
  1165. }
  1166. else
  1167. {
  1168. UserAccount account = null;
  1169. // TODO: Is there a better choice here?
  1170. UUID scopeID = UUID.Zero;
  1171. string s1 = args[4];
  1172. if (args.Length == 5)
  1173. {
  1174. // attempt to get account by UUID
  1175. UUID u;
  1176. if (UUID.TryParse(s1, out u))
  1177. {
  1178. account = scene.UserAccountService.GetUserAccount(scopeID, u);
  1179. if (account == null)
  1180. response = String.Format("Could not find user {0}", s1);
  1181. }
  1182. else
  1183. {
  1184. response = String.Format("Invalid UUID {0}", s1);
  1185. }
  1186. }
  1187. else
  1188. {
  1189. // attempt to get account by Firstname, Lastname
  1190. string s2 = args[5];
  1191. account = scene.UserAccountService.GetUserAccount(scopeID, s1, s2);
  1192. if (account == null)
  1193. response = String.Format("Could not find user {0} {1}", s1, s2);
  1194. }
  1195. // If it's valid, send it off for processing.
  1196. if (account != null)
  1197. response = estateModule.SetEstateOwner(estateId, account);
  1198. if (response == String.Empty)
  1199. {
  1200. response = String.Format("Estate owner changed to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. // give the user some feedback
  1206. if (response != null)
  1207. MainConsole.Instance.Output(response);
  1208. }
  1209. protected void SetEstateNameCommand(string module, string[] args)
  1210. {
  1211. string response = null;
  1212. Scene scene = SceneManager.CurrentOrFirstScene;
  1213. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1214. if (args.Length == 3)
  1215. {
  1216. response = "No estate specified.";
  1217. }
  1218. else
  1219. {
  1220. int estateId;
  1221. if (!int.TryParse(args[3], out estateId))
  1222. {
  1223. response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]);
  1224. }
  1225. else
  1226. {
  1227. if (args.Length == 4)
  1228. {
  1229. response = "No name specified.";
  1230. }
  1231. else
  1232. {
  1233. // everything after the estate ID is "name"
  1234. StringBuilder sb = new StringBuilder(args[4]);
  1235. for (int i = 5; i < args.Length; i++)
  1236. sb.Append (" " + args[i]);
  1237. string estateName = sb.ToString();
  1238. // send it off for processing.
  1239. response = estateModule.SetEstateName(estateId, estateName);
  1240. if (response == String.Empty)
  1241. {
  1242. response = String.Format("Estate {0} renamed to \"{1}\"", estateId, estateName);
  1243. }
  1244. }
  1245. }
  1246. }
  1247. // give the user some feedback
  1248. if (response != null)
  1249. MainConsole.Instance.Output(response);
  1250. }
  1251. private void EstateLinkRegionCommand(string module, string[] args)
  1252. {
  1253. int estateId =-1;
  1254. UUID regionId = UUID.Zero;
  1255. Scene scene = null;
  1256. string response = null;
  1257. if (args.Length == 3)
  1258. {
  1259. response = "No estate specified.";
  1260. }
  1261. else if (!int.TryParse(args [3], out estateId))
  1262. {
  1263. response = String.Format("\"{0}\" is not a valid ID for an Estate", args [3]);
  1264. }
  1265. else if (args.Length == 4)
  1266. {
  1267. response = "No region specified.";
  1268. }
  1269. else if (!UUID.TryParse(args[4], out regionId))
  1270. {
  1271. response = String.Format("\"{0}\" is not a valid UUID for a Region", args [4]);
  1272. }
  1273. else if (!SceneManager.TryGetScene(regionId, out scene))
  1274. {
  1275. // region may exist, but on a different sim.
  1276. response = String.Format("No access to Region \"{0}\"", args [4]);
  1277. }
  1278. if (response != null)
  1279. {
  1280. MainConsole.Instance.Output(response);
  1281. return;
  1282. }
  1283. // send it off for processing.
  1284. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1285. response = estateModule.SetRegionEstate(scene.RegionInfo, estateId);
  1286. if (response == String.Empty)
  1287. {
  1288. estateModule.TriggerRegionInfoChange();
  1289. estateModule.sendRegionHandshakeToAll();
  1290. response = String.Format ("Region {0} is now attached to estate {1}", regionId, estateId);
  1291. }
  1292. // give the user some feedback
  1293. if (response != null)
  1294. MainConsole.Instance.Output (response);
  1295. }
  1296. #endregion
  1297. private static string CombineParams(string[] commandParams, int pos)
  1298. {
  1299. string result = String.Empty;
  1300. for (int i = pos; i < commandParams.Length; i++)
  1301. {
  1302. result += commandParams[i] + " ";
  1303. }
  1304. result = result.TrimEnd(' ');
  1305. return result;
  1306. }
  1307. }
  1308. }