OpenSim.cs 64 KB

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