OpenSim.cs 65 KB

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