OpenSim.cs 64 KB

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