OpenSim.cs 65 KB

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