OpenSim.cs 66 KB

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