OpenSim.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  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).Length == 0)
  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. RegisterCommonAppenders(Config.Configs["Startup"]);
  150. LogEnvironmentInformation();
  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 (!string.IsNullOrEmpty(managedStatsURI))
  160. {
  161. string urlBase = $"/{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. "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}",
  446. presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName);
  447. if (presence.IsNPC)
  448. {
  449. INPCModule npcmodule = presence.Scene.RequestModuleInterface<INPCModule>();
  450. if (npcmodule != null)
  451. {
  452. npcmodule.DeleteNPC(presence.UUID, presence.Scene);
  453. return;
  454. }
  455. }
  456. // kick client...
  457. if (alert != null)
  458. presence.ControllingClient.Kick(alert);
  459. else
  460. presence.ControllingClient.Kick("\nYou have been logged out by an administrator.\n");
  461. presence.Scene.CloseAgent(presence.UUID, force);
  462. break;
  463. }
  464. }
  465. MainConsole.Instance.Output("");
  466. }
  467. /// <summary>
  468. /// Opens a file and uses it as input to the console command parser.
  469. /// </summary>
  470. /// <param name="fileName">name of file to use as input to the console</param>
  471. private static void PrintFileToConsole(string fileName)
  472. {
  473. if (File.Exists(fileName))
  474. {
  475. using(StreamReader readFile = File.OpenText(fileName))
  476. {
  477. string currentLine;
  478. while ((currentLine = readFile.ReadLine()) != null)
  479. {
  480. m_log.Info("[!]" + currentLine);
  481. }
  482. }
  483. }
  484. }
  485. /// <summary>
  486. /// Force resending of all updates to all clients in active region(s)
  487. /// </summary>
  488. /// <param name="module"></param>
  489. /// <param name="args"></param>
  490. private void HandleForceUpdate(string module, string[] args)
  491. {
  492. MainConsole.Instance.Output("Updating all clients");
  493. SceneManager.ForceCurrentSceneClientUpdate();
  494. }
  495. /// <summary>
  496. /// Edits the scale of a primative with the name specified
  497. /// </summary>
  498. /// <param name="module"></param>
  499. /// <param name="args">0,1, name, x, y, z</param>
  500. private void HandleEditScale(string module, string[] args)
  501. {
  502. if (args.Length == 6)
  503. {
  504. SceneManager.HandleEditCommandOnCurrentScene(args);
  505. }
  506. else
  507. {
  508. MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>");
  509. }
  510. }
  511. private void HandleRotateScene(string module, string[] args)
  512. {
  513. string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2";
  514. float centerX = Constants.RegionSize * 0.5f;
  515. float centerY = Constants.RegionSize * 0.5f;
  516. if (args.Length < 3 || args.Length == 4)
  517. {
  518. MainConsole.Instance.Output(usage);
  519. return;
  520. }
  521. float angle = Convert.ToSingle(args[2]) / 180.0f * MathF.PI;
  522. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle);
  523. if (args.Length > 4)
  524. {
  525. centerX = Convert.ToSingle(args[3]);
  526. centerY = Convert.ToSingle(args[4]);
  527. }
  528. Vector3 center = new Vector3(centerX, centerY, 0.0f);
  529. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  530. {
  531. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  532. {
  533. if (!sog.IsAttachment)
  534. {
  535. sog.RootPart.UpdateRotation(rot * sog.GroupRotation);
  536. Vector3 offset = sog.AbsolutePosition - center;
  537. offset *= rot;
  538. sog.UpdateGroupPosition(center + offset);
  539. }
  540. });
  541. });
  542. }
  543. private void HandleScaleScene(string module, string[] args)
  544. {
  545. string usage = "Usage: scale scene <factor>";
  546. if (args.Length < 3)
  547. {
  548. MainConsole.Instance.Output(usage);
  549. return;
  550. }
  551. float factor = (float)(Convert.ToSingle(args[2]));
  552. float minZ = float.MaxValue;
  553. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  554. {
  555. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  556. {
  557. if (!sog.IsAttachment)
  558. {
  559. if (sog.RootPart.AbsolutePosition.Z < minZ)
  560. minZ = sog.RootPart.AbsolutePosition.Z;
  561. }
  562. });
  563. });
  564. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  565. {
  566. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  567. {
  568. if (!sog.IsAttachment)
  569. {
  570. Vector3 tmpRootPos = sog.RootPart.AbsolutePosition;
  571. tmpRootPos.Z -= minZ;
  572. tmpRootPos *= factor;
  573. tmpRootPos.Z += minZ;
  574. foreach (SceneObjectPart sop in sog.Parts)
  575. {
  576. if (sop.ParentID != 0)
  577. sop.OffsetPosition *= factor;
  578. sop.Scale *= factor;
  579. }
  580. sog.UpdateGroupPosition(tmpRootPos);
  581. }
  582. });
  583. });
  584. }
  585. private void HandleTranslateScene(string module, string[] args)
  586. {
  587. string usage = "Usage: translate scene <xOffset, yOffset, zOffset>";
  588. if (args.Length < 5)
  589. {
  590. MainConsole.Instance.Output(usage);
  591. return;
  592. }
  593. float xOFfset = (float)Convert.ToSingle(args[2]);
  594. float yOffset = (float)Convert.ToSingle(args[3]);
  595. float zOffset = (float)Convert.ToSingle(args[4]);
  596. Vector3 offset = new Vector3(xOFfset, yOffset, zOffset);
  597. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  598. {
  599. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  600. {
  601. if (!sog.IsAttachment)
  602. sog.UpdateGroupPosition(sog.AbsolutePosition + offset);
  603. });
  604. });
  605. }
  606. /// <summary>
  607. /// Creates a new region based on the parameters specified. This will ask the user questions on the console
  608. /// </summary>
  609. /// <param name="module"></param>
  610. /// <param name="cmd">0,1,region name, region ini or XML file</param>
  611. private void HandleCreateRegion(string module, string[] cmd)
  612. {
  613. string regionName = string.Empty;
  614. string regionFile = string.Empty;
  615. if (cmd.Length == 3)
  616. {
  617. regionFile = cmd[2];
  618. }
  619. else if (cmd.Length > 3)
  620. {
  621. regionName = cmd[2];
  622. regionFile = cmd[3];
  623. }
  624. string extension = Path.GetExtension(regionFile).ToLower();
  625. bool isXml = extension.Equals(".xml");
  626. bool isIni = extension.Equals(".ini");
  627. if (!isXml && !isIni)
  628. {
  629. MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>");
  630. return;
  631. }
  632. if (!Path.IsPathRooted(regionFile))
  633. {
  634. string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim();
  635. regionFile = Path.Combine(regionsDir, regionFile);
  636. }
  637. RegionInfo regInfo;
  638. if (isXml)
  639. {
  640. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source);
  641. }
  642. else
  643. {
  644. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName);
  645. }
  646. if (SceneManager.TryGetScene(regInfo.RegionID, out Scene existingScene))
  647. {
  648. MainConsole.Instance.Output(
  649. "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}",
  650. regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName);
  651. return;
  652. }
  653. bool changed = PopulateRegionEstateInfo(regInfo);
  654. CreateRegion(regInfo, true, out IScene scene);
  655. if (changed)
  656. m_estateDataService.StoreEstateSettings(regInfo.EstateSettings);
  657. scene.Start();
  658. }
  659. /// <summary>
  660. /// Runs commands issued by the server console from the operator
  661. /// </summary>
  662. /// <param name="command">The first argument of the parameter (the command)</param>
  663. /// <param name="cmdparams">Additional arguments passed to the command</param>
  664. public void RunCommand(string module, string[] cmdparams)
  665. {
  666. List<string> args = new List<string>(cmdparams);
  667. if (args.Count < 1)
  668. return;
  669. string command = args[0];
  670. args.RemoveAt(0);
  671. cmdparams = args.ToArray();
  672. switch (command)
  673. {
  674. case "backup":
  675. MainConsole.Instance.Output("Triggering save of pending object updates to persistent store");
  676. SceneManager.BackupCurrentScene();
  677. break;
  678. case "remove-region":
  679. string regRemoveName = CombineParams(cmdparams, 0);
  680. Scene removeScene;
  681. if (SceneManager.TryGetScene(regRemoveName, out removeScene))
  682. RemoveRegion(removeScene, false);
  683. else
  684. MainConsole.Instance.Output("No region with that name");
  685. break;
  686. case "delete-region":
  687. string regDeleteName = CombineParams(cmdparams, 0);
  688. Scene killScene;
  689. if (SceneManager.TryGetScene(regDeleteName, out killScene))
  690. RemoveRegion(killScene, true);
  691. else
  692. MainConsole.Instance.Output("no region with that name");
  693. break;
  694. case "restart":
  695. MainConsole.Instance.Output("Restart command disabled, because currently it is unreliable.");
  696. //SceneManager.RestartCurrentScene();
  697. break;
  698. }
  699. }
  700. /// <summary>
  701. /// Change the currently selected region. The selected region is that operated upon by single region commands.
  702. /// </summary>
  703. /// <param name="cmdParams"></param>
  704. protected void ChangeSelectedRegion(string module, string[] cmdparams)
  705. {
  706. if (cmdparams.Length > 2)
  707. {
  708. string newRegionName = CombineParams(cmdparams, 2);
  709. if (!SceneManager.TrySetCurrentScene(newRegionName))
  710. MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName));
  711. else
  712. RefreshPrompt();
  713. }
  714. else
  715. {
  716. MainConsole.Instance.Output("Usage: change region <region name>");
  717. }
  718. }
  719. /// <summary>
  720. /// Refreshs prompt with the current selection details.
  721. /// </summary>
  722. private void RefreshPrompt()
  723. {
  724. string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName);
  725. MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName));
  726. // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt);
  727. string prompt = m_consolePrompt;
  728. // Replace "\R" with the region name
  729. // Replace "\\" with "\"
  730. prompt = m_consolePromptRegex.Replace(prompt, m =>
  731. {
  732. // m_log.DebugFormat("Matched {0}", m.Groups[2].Value);
  733. if (m.Groups[2].Value == "R")
  734. return m.Groups[1].Value + regionName;
  735. else
  736. return m.Groups[0].Value;
  737. });
  738. m_console.DefaultPrompt = prompt;
  739. m_console.ConsoleScene = SceneManager.CurrentScene;
  740. }
  741. protected override void HandleRestartRegion(RegionInfo whichRegion)
  742. {
  743. base.HandleRestartRegion(whichRegion);
  744. // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the
  745. // m_console.ConsoleScene to null (indicating all scenes).
  746. if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name)
  747. SceneManager.TrySetCurrentScene(whichRegion.RegionName);
  748. RefreshPrompt();
  749. }
  750. // see BaseOpenSimServer
  751. /// <summary>
  752. /// Many commands list objects for debugging. Some of the types are listed here
  753. /// </summary>
  754. /// <param name="mod"></param>
  755. /// <param name="cmd"></param>
  756. public override void HandleShow(string mod, string[] cmd)
  757. {
  758. base.HandleShow(mod, cmd);
  759. List<string> args = new List<string>(cmd);
  760. args.RemoveAt(0);
  761. string[] showParams = args.ToArray();
  762. switch (showParams[0])
  763. {
  764. case "users":
  765. bool includeChild = false;
  766. if (showParams.Length > 1 && showParams[1] == "full")
  767. includeChild = true;
  768. SceneManager.ForEachScene(
  769. delegate (Scene scene)
  770. {
  771. RegionInfo regionInfo = scene.RegionInfo;
  772. string regionName;
  773. if (regionInfo == null)
  774. regionName = "Unresolvable";
  775. else
  776. regionName = regionInfo.RegionName;
  777. List<ScenePresence> agents = scene.GetScenePresences();
  778. List<ScenePresence> tmpagents = new List<ScenePresence>();
  779. int total = agents.Count;
  780. int childcount = 0;
  781. if (total > 0)
  782. {
  783. foreach(ScenePresence sp in agents)
  784. {
  785. if(sp.IsChildAgent)
  786. {
  787. if (includeChild)
  788. tmpagents.Add(sp);
  789. ++childcount;
  790. }
  791. else
  792. tmpagents.Add(sp);
  793. }
  794. }
  795. if(includeChild)
  796. {
  797. MainConsole.Instance.Output(String.Format("\nTotal agents in region {0}: {1} (root {2}, child {3})",
  798. regionName, total, total - childcount, childcount));
  799. }
  800. else
  801. {
  802. MainConsole.Instance.Output(String.Format("\nRoot agents in region {0}: {1} (root {2}, child {3})",
  803. regionName, tmpagents.Count, total - childcount, childcount));
  804. }
  805. if (tmpagents.Count == 0)
  806. return;
  807. MainConsole.Instance.Output(
  808. String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-30}", "Firstname", "Lastname",
  809. "Agent ID", "Type", "Position")
  810. );
  811. foreach (ScenePresence presence in tmpagents)
  812. {
  813. string sptype;
  814. if(presence.IsNPC)
  815. sptype = presence.IsChildAgent ? "NPC Child" : "NPC Root";
  816. else
  817. sptype = presence.IsChildAgent ? "Child" : "Root";
  818. MainConsole.Instance.Output(
  819. String.Format(
  820. "{0,-16} {1,-16} {2,-37} {3,-11} {4,-30}",
  821. presence.Firstname,
  822. presence.Lastname,
  823. presence.UUID,
  824. sptype,
  825. presence.AbsolutePosition.ToString())
  826. );
  827. }
  828. });
  829. MainConsole.Instance.Output(String.Empty);
  830. break;
  831. case "connections":
  832. HandleShowConnections();
  833. break;
  834. case "circuits":
  835. HandleShowCircuits();
  836. break;
  837. case "modules":
  838. SceneManager.ForEachSelectedScene(
  839. delegate (Scene scene)
  840. {
  841. MainConsole.Instance.Output("Loaded region modules in {0} are:", scene.Name);
  842. List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>();
  843. List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>();
  844. foreach (IRegionModuleBase module in scene.RegionModules.Values)
  845. {
  846. if (module.GetType().GetInterface("ISharedRegionModule") == null)
  847. nonSharedModules.Add(module);
  848. else
  849. sharedModules.Add(module);
  850. }
  851. foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name))
  852. MainConsole.Instance.Output("New Region Module (Shared): {0}", module.Name);
  853. foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name))
  854. MainConsole.Instance.Output("New Region Module (Non-Shared): {0}", module.Name);
  855. }
  856. );
  857. MainConsole.Instance.Output("");
  858. break;
  859. case "regions":
  860. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  861. cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize);
  862. cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize);
  863. cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize);
  864. cdt.AddColumn("Size", 11);
  865. cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize);
  866. cdt.AddColumn("Ready?", 6);
  867. cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize);
  868. SceneManager.ForEachScene(
  869. scene =>
  870. {
  871. RegionInfo ri = scene.RegionInfo;
  872. cdt.AddRow(
  873. ri.RegionName,
  874. ri.RegionID,
  875. string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY),
  876. string.Format("{0}x{1}", ri.RegionSizeX, ri.RegionSizeY),
  877. ri.InternalEndPoint.Port,
  878. scene.Ready ? "Yes" : "No",
  879. ri.EstateSettings.EstateName);
  880. }
  881. );
  882. MainConsole.Instance.Output(cdt.ToString());
  883. break;
  884. case "ratings":
  885. SceneManager.ForEachScene(
  886. delegate(Scene scene)
  887. {
  888. string rating = "";
  889. if (scene.RegionInfo.RegionSettings.Maturity == 1)
  890. {
  891. rating = "MATURE";
  892. }
  893. else if (scene.RegionInfo.RegionSettings.Maturity == 2)
  894. {
  895. rating = "ADULT";
  896. }
  897. else
  898. {
  899. rating = "PG";
  900. }
  901. MainConsole.Instance.Output(String.Format(
  902. "Region Name: {0}, Region Rating {1}",
  903. scene.RegionInfo.RegionName,
  904. rating));
  905. });
  906. break;
  907. }
  908. }
  909. private void HandleShowCircuits()
  910. {
  911. SceneManager.ForEachScene(
  912. s =>
  913. {
  914. ICollection<AgentCircuitData> circuits = s.AuthenticateHandler.GetAgentCircuits().Values;
  915. int n = circuits.Count;
  916. MainConsole.Instance.Output("- Circuits in region {0}: {1}", s.Name, n);
  917. if(n > 0)
  918. {
  919. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  920. cdt.AddColumn("Avatar name", 24);
  921. cdt.AddColumn("Type", 5);
  922. cdt.AddColumn("Code", 10);
  923. cdt.AddColumn("IP", 16);
  924. cdt.AddColumn("Viewer Name", 24);
  925. cdt.AddColumn("Svc Urls", 8);
  926. foreach (AgentCircuitData aCircuit in circuits)
  927. cdt.AddRow(
  928. aCircuit.Name,
  929. aCircuit.child ? "child" : "root",
  930. aCircuit.circuitcode.ToString(),
  931. aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set",
  932. Util.GetViewerName(aCircuit),
  933. aCircuit.ServiceURLs != null ? aCircuit.ServiceURLs.Count : 0
  934. );
  935. MainConsole.Instance.Output(cdt.ToString());
  936. }
  937. });
  938. }
  939. private void HandleShowConnections()
  940. {
  941. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  942. cdt.AddColumn("Region", 20);
  943. cdt.AddColumn("Avatar name", 24);
  944. cdt.AddColumn("Circuit code", 12);
  945. cdt.AddColumn("Endpoint", 23);
  946. cdt.AddColumn("Active?", 7);
  947. cdt.AddColumn("ChildAgent?", 7);
  948. cdt.AddColumn("ping(ms)", 8);
  949. SceneManager.ForEachScene(
  950. s => s.ForEachClient(
  951. c =>
  952. {
  953. bool child = false;
  954. if(c.SceneAgent != null && c.SceneAgent.IsChildAgent)
  955. child = true;
  956. cdt.AddRow(
  957. s.Name,
  958. c.Name,
  959. c.CircuitCode.ToString(),
  960. c.RemoteEndPoint.ToString(),
  961. c.IsActive.ToString(),
  962. child.ToString(),
  963. c.PingTimeMS);
  964. }));
  965. MainConsole.Instance.Output(cdt.ToString());
  966. }
  967. /// <summary>
  968. /// Use XML2 format to serialize data to a file
  969. /// </summary>
  970. /// <param name="module"></param>
  971. /// <param name="cmdparams"></param>
  972. protected void SavePrimsXml2(string module, string[] cmdparams)
  973. {
  974. if (cmdparams.Length > 4)
  975. {
  976. SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]);
  977. }
  978. else
  979. {
  980. SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME);
  981. }
  982. }
  983. /// <summary>
  984. /// Use XML format to serialize data to a file
  985. /// </summary>
  986. /// <param name="module"></param>
  987. /// <param name="cmdparams"></param>
  988. protected void SaveXml(string module, string[] cmdparams)
  989. {
  990. 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.");
  991. if (cmdparams.Length > 2)
  992. {
  993. SceneManager.SaveCurrentSceneToXml(cmdparams[2]);
  994. }
  995. else
  996. {
  997. SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME);
  998. }
  999. }
  1000. /// <summary>
  1001. /// Loads data and region objects from XML format.
  1002. /// </summary>
  1003. /// <param name="module"></param>
  1004. /// <param name="cmdparams"></param>
  1005. protected void LoadXml(string module, string[] cmdparams)
  1006. {
  1007. 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.");
  1008. Vector3 loadOffset = new Vector3(0, 0, 0);
  1009. if (cmdparams.Length > 2)
  1010. {
  1011. bool generateNewIDS = false;
  1012. if (cmdparams.Length > 3)
  1013. {
  1014. if (cmdparams[3] == "-newUID")
  1015. {
  1016. generateNewIDS = true;
  1017. }
  1018. if (cmdparams.Length > 4)
  1019. {
  1020. loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo);
  1021. if (cmdparams.Length > 5)
  1022. {
  1023. loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo);
  1024. }
  1025. if (cmdparams.Length > 6)
  1026. {
  1027. loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo);
  1028. }
  1029. MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z));
  1030. }
  1031. }
  1032. SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset);
  1033. }
  1034. else
  1035. {
  1036. try
  1037. {
  1038. SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset);
  1039. }
  1040. catch (FileNotFoundException)
  1041. {
  1042. MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>");
  1043. }
  1044. }
  1045. }
  1046. /// <summary>
  1047. /// Serialize region data to XML2Format
  1048. /// </summary>
  1049. /// <param name="module"></param>
  1050. /// <param name="cmdparams"></param>
  1051. protected void SaveXml2(string module, string[] cmdparams)
  1052. {
  1053. if (cmdparams.Length > 2)
  1054. {
  1055. SceneManager.SaveCurrentSceneToXml2(cmdparams[2]);
  1056. }
  1057. else
  1058. {
  1059. SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Load region data from Xml2Format
  1064. /// </summary>
  1065. /// <param name="module"></param>
  1066. /// <param name="cmdparams"></param>
  1067. protected void LoadXml2(string module, string[] cmdparams)
  1068. {
  1069. if (cmdparams.Length > 2)
  1070. {
  1071. try
  1072. {
  1073. SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]);
  1074. }
  1075. catch (FileNotFoundException)
  1076. {
  1077. MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>");
  1078. }
  1079. }
  1080. else
  1081. {
  1082. try
  1083. {
  1084. SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  1085. }
  1086. catch (FileNotFoundException)
  1087. {
  1088. MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>");
  1089. }
  1090. }
  1091. }
  1092. /// <summary>
  1093. /// Load a whole region from an opensimulator archive.
  1094. /// </summary>
  1095. /// <param name="cmdparams"></param>
  1096. protected void LoadOar(string module, string[] cmdparams)
  1097. {
  1098. try
  1099. {
  1100. SceneManager.LoadArchiveToCurrentScene(cmdparams);
  1101. }
  1102. catch (Exception e)
  1103. {
  1104. MainConsole.Instance.Output(e.Message);
  1105. }
  1106. }
  1107. /// <summary>
  1108. /// Save a region to a file, including all the assets needed to restore it.
  1109. /// </summary>
  1110. /// <param name="cmdparams"></param>
  1111. protected void SaveOar(string module, string[] cmdparams)
  1112. {
  1113. SceneManager.SaveCurrentSceneToArchive(cmdparams);
  1114. }
  1115. protected void CreateEstateCommand(string module, string[] args)
  1116. {
  1117. string response = null;
  1118. if (args.Length == 2)
  1119. {
  1120. response = "No user specified.";
  1121. }
  1122. else if (!UUID.TryParse(args[2], out UUID userID))
  1123. {
  1124. response = String.Format("{0} is not a valid UUID", args[2]);
  1125. }
  1126. else if (args.Length == 3)
  1127. {
  1128. response = "No estate name specified.";
  1129. }
  1130. else
  1131. {
  1132. Scene scene = SceneManager.CurrentOrFirstScene;
  1133. // TODO: Is there a better choice here?
  1134. UUID scopeID = UUID.Zero;
  1135. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, userID);
  1136. if (account == null)
  1137. {
  1138. response = String.Format("Could not find user {0}", userID);
  1139. }
  1140. else
  1141. {
  1142. // concatenate it all to "name"
  1143. StringBuilder sb = new StringBuilder(args[3]);
  1144. for (int i = 4; i < args.Length; i++)
  1145. sb.Append (" " + args[i]);
  1146. string estateName = sb.ToString().Trim();
  1147. // send it off for processing.
  1148. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1149. response = estateModule.CreateEstate(estateName, userID);
  1150. if (response.Length == 0)
  1151. {
  1152. List<int> estates = scene.EstateDataService.GetEstates(estateName);
  1153. response = String.Format("Estate {0} created as \"{1}\"", estates.ElementAt(0), estateName);
  1154. }
  1155. }
  1156. }
  1157. // give the user some feedback
  1158. if (response != null)
  1159. MainConsole.Instance.Output(response);
  1160. }
  1161. protected void SetEstateOwnerCommand(string module, string[] args)
  1162. {
  1163. string response = null;
  1164. Scene scene = SceneManager.CurrentOrFirstScene;
  1165. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1166. if (args.Length == 3)
  1167. {
  1168. response = "No estate specified.";
  1169. }
  1170. else
  1171. {
  1172. if (!int.TryParse(args[3], out int estateId))
  1173. {
  1174. response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]);
  1175. }
  1176. else
  1177. {
  1178. if (args.Length == 4)
  1179. {
  1180. response = "No user specified.";
  1181. }
  1182. else
  1183. {
  1184. UserAccount account = null;
  1185. // TODO: Is there a better choice here?
  1186. UUID scopeID = UUID.Zero;
  1187. string s1 = args[4];
  1188. if (args.Length == 5)
  1189. {
  1190. // attempt to get account by UUID
  1191. if (UUID.TryParse(s1, out UUID u))
  1192. {
  1193. account = scene.UserAccountService.GetUserAccount(scopeID, u);
  1194. if (account == null)
  1195. response = String.Format("Could not find user {0}", s1);
  1196. }
  1197. else
  1198. {
  1199. response = String.Format("Invalid UUID {0}", s1);
  1200. }
  1201. }
  1202. else
  1203. {
  1204. // attempt to get account by Firstname, Lastname
  1205. string s2 = args[5];
  1206. account = scene.UserAccountService.GetUserAccount(scopeID, s1, s2);
  1207. if (account == null)
  1208. response = String.Format("Could not find user {0} {1}", s1, s2);
  1209. }
  1210. // If it's valid, send it off for processing.
  1211. if (account != null)
  1212. response = estateModule.SetEstateOwner(estateId, account);
  1213. if (response.Length == 0)
  1214. {
  1215. response = String.Format("Estate owner changed to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. // give the user some feedback
  1221. if (response != null)
  1222. MainConsole.Instance.Output(response);
  1223. }
  1224. protected void SetEstateNameCommand(string module, string[] args)
  1225. {
  1226. string response = null;
  1227. Scene scene = SceneManager.CurrentOrFirstScene;
  1228. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1229. if (args.Length == 3)
  1230. {
  1231. response = "No estate specified.";
  1232. }
  1233. else
  1234. {
  1235. if (!int.TryParse(args[3], out int estateId))
  1236. {
  1237. response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]);
  1238. }
  1239. else
  1240. {
  1241. if (args.Length == 4)
  1242. {
  1243. response = "No name specified.";
  1244. }
  1245. else
  1246. {
  1247. // everything after the estate ID is "name"
  1248. StringBuilder sb = new StringBuilder(args[4]);
  1249. for (int i = 5; i < args.Length; i++)
  1250. sb.Append (" " + args[i]);
  1251. string estateName = sb.ToString();
  1252. // send it off for processing.
  1253. response = estateModule.SetEstateName(estateId, estateName);
  1254. if (response.Length == 0)
  1255. {
  1256. response = String.Format("Estate {0} renamed to \"{1}\"", estateId, estateName);
  1257. }
  1258. }
  1259. }
  1260. }
  1261. // give the user some feedback
  1262. if (response != null)
  1263. MainConsole.Instance.Output(response);
  1264. }
  1265. private void EstateLinkRegionCommand(string module, string[] args)
  1266. {
  1267. int estateId =-1;
  1268. UUID regionId = UUID.Zero;
  1269. Scene scene = null;
  1270. string response = null;
  1271. if (args.Length == 3)
  1272. {
  1273. response = "No estate specified.";
  1274. }
  1275. else if (!int.TryParse(args [3], out estateId))
  1276. {
  1277. response = String.Format("\"{0}\" is not a valid ID for an Estate", args [3]);
  1278. }
  1279. else if (args.Length == 4)
  1280. {
  1281. response = "No region specified.";
  1282. }
  1283. else if (!UUID.TryParse(args[4], out regionId))
  1284. {
  1285. response = String.Format("\"{0}\" is not a valid UUID for a Region", args [4]);
  1286. }
  1287. else if (!SceneManager.TryGetScene(regionId, out scene))
  1288. {
  1289. // region may exist, but on a different sim.
  1290. response = String.Format("No access to Region \"{0}\"", args [4]);
  1291. }
  1292. if (response != null)
  1293. {
  1294. MainConsole.Instance.Output(response);
  1295. return;
  1296. }
  1297. // send it off for processing.
  1298. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  1299. response = estateModule.SetRegionEstate(scene.RegionInfo, estateId);
  1300. if (response.Length == 0)
  1301. {
  1302. estateModule.TriggerRegionInfoChange();
  1303. estateModule.sendRegionHandshakeToAll();
  1304. response = String.Format ("Region {0} is now attached to estate {1}", regionId, estateId);
  1305. }
  1306. // give the user some feedback
  1307. if (response != null)
  1308. MainConsole.Instance.Output (response);
  1309. }
  1310. #endregion
  1311. private static string CombineParams(string[] commandParams, int pos)
  1312. {
  1313. string result = String.Empty;
  1314. for (int i = pos; i < commandParams.Length; i++)
  1315. {
  1316. result += commandParams[i] + " ";
  1317. }
  1318. result = result.TrimEnd(' ');
  1319. return result;
  1320. }
  1321. }
  1322. }