1
0

GridService.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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.Collections.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using Nini.Config;
  32. using log4net;
  33. using OpenSim.Framework;
  34. using OpenSim.Framework.Console;
  35. using OpenSim.Data;
  36. using OpenSim.Server.Base;
  37. using OpenSim.Services.Interfaces;
  38. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  39. using OpenMetaverse;
  40. namespace OpenSim.Services.GridService
  41. {
  42. public class GridService : GridServiceBase, IGridService
  43. {
  44. private static readonly ILog m_log =
  45. LogManager.GetLogger(
  46. MethodBase.GetCurrentMethod().DeclaringType);
  47. private string LogHeader = "[GRID SERVICE]";
  48. private bool m_DeleteOnUnregister = true;
  49. private static GridService m_RootInstance = null;
  50. protected IConfigSource m_config;
  51. protected static HypergridLinker m_HypergridLinker;
  52. protected IAuthenticationService m_AuthenticationService = null;
  53. protected bool m_AllowDuplicateNames = false;
  54. protected bool m_AllowHypergridMapSearch = false;
  55. private static Dictionary<string,object> m_ExtraFeatures = new Dictionary<string, object>();
  56. public GridService(IConfigSource config)
  57. : base(config)
  58. {
  59. m_log.DebugFormat("[GRID SERVICE]: Starting...");
  60. m_config = config;
  61. IConfig gridConfig = config.Configs["GridService"];
  62. bool suppressConsoleCommands = false;
  63. if (gridConfig != null)
  64. {
  65. m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
  66. string authService = gridConfig.GetString("AuthenticationService", String.Empty);
  67. if (authService != String.Empty)
  68. {
  69. Object[] args = new Object[] { config };
  70. m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
  71. }
  72. m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
  73. m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);
  74. // This service is also used locally by a simulator running in grid mode. This switches prevents
  75. // inappropriate console commands from being registered
  76. suppressConsoleCommands = gridConfig.GetBoolean("SuppressConsoleCommands", suppressConsoleCommands);
  77. }
  78. if (m_RootInstance == null)
  79. {
  80. m_RootInstance = this;
  81. if (!suppressConsoleCommands && MainConsole.Instance != null)
  82. {
  83. MainConsole.Instance.Commands.AddCommand("Regions", true,
  84. "deregister region id",
  85. "deregister region id <region-id>+",
  86. "Deregister a region manually.",
  87. String.Empty,
  88. HandleDeregisterRegion);
  89. MainConsole.Instance.Commands.AddCommand("Regions", true,
  90. "show regions",
  91. "show regions",
  92. "Show details on all regions",
  93. String.Empty,
  94. HandleShowRegions);
  95. MainConsole.Instance.Commands.AddCommand("Regions", true,
  96. "show region name",
  97. "show region name <Region name>",
  98. "Show details on a region",
  99. String.Empty,
  100. HandleShowRegion);
  101. MainConsole.Instance.Commands.AddCommand("Regions", true,
  102. "show region at",
  103. "show region at <x-coord> <y-coord>",
  104. "Show details on a region at the given co-ordinate.",
  105. "For example, show region at 1000 1000",
  106. HandleShowRegionAt);
  107. MainConsole.Instance.Commands.AddCommand("General", true,
  108. "show grid size",
  109. "show grid size",
  110. "Show the current grid size (excluding hyperlink references)",
  111. String.Empty,
  112. HandleShowGridSize);
  113. MainConsole.Instance.Commands.AddCommand("Regions", true,
  114. "set region flags",
  115. "set region flags <Region name> <flags>",
  116. "Set database flags for region",
  117. String.Empty,
  118. HandleSetFlags);
  119. }
  120. if (!suppressConsoleCommands)
  121. SetExtraServiceURLs(config);
  122. m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
  123. }
  124. }
  125. private void SetExtraServiceURLs(IConfigSource config)
  126. {
  127. IConfig loginConfig = config.Configs["LoginService"];
  128. IConfig gridConfig = config.Configs["GridService"];
  129. if (loginConfig == null || gridConfig == null)
  130. return;
  131. string configVal;
  132. configVal = loginConfig.GetString("SearchURL", string.Empty);
  133. if (!string.IsNullOrEmpty(configVal))
  134. m_ExtraFeatures["search-server-url"] = configVal;
  135. configVal = loginConfig.GetString("MapTileURL", string.Empty);
  136. if (!string.IsNullOrEmpty(configVal))
  137. {
  138. // This URL must end with '/', the viewer doesn't check
  139. configVal = configVal.Trim();
  140. if (!configVal.EndsWith("/"))
  141. configVal = configVal + "/";
  142. m_ExtraFeatures["map-server-url"] = configVal;
  143. }
  144. configVal = loginConfig.GetString("DestinationGuide", string.Empty);
  145. if (!string.IsNullOrEmpty(configVal))
  146. m_ExtraFeatures["destination-guide-url"] = configVal;
  147. configVal = Util.GetConfigVarFromSections<string>(
  148. config, "GatekeeperURI", new string[] { "Startup", "Hypergrid" }, String.Empty);
  149. if (!string.IsNullOrEmpty(configVal))
  150. m_ExtraFeatures["GridURL"] = configVal;
  151. configVal = Util.GetConfigVarFromSections<string>(
  152. config, "GridName", new string[] { "Const", "Hypergrid" }, String.Empty);
  153. if (string.IsNullOrEmpty(configVal))
  154. configVal = Util.GetConfigVarFromSections<string>(
  155. config, "gridname", new string[] { "GridInfo" }, String.Empty);
  156. if (!string.IsNullOrEmpty(configVal))
  157. m_ExtraFeatures["GridName"] = configVal;
  158. m_ExtraFeatures["ExportSupported"] = gridConfig.GetString("ExportSupported", "true");
  159. }
  160. #region IGridService
  161. public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
  162. {
  163. IConfig gridConfig = m_config.Configs["GridService"];
  164. if (regionInfos.RegionID == UUID.Zero)
  165. return "Invalid RegionID - cannot be zero UUID";
  166. if (regionInfos.RegionLocY <= Constants.MaximumRegionSize)
  167. return "Region location reserved for HG links coord Y must be higher than " + (Constants.MaximumRegionSize/256).ToString();
  168. String reason = "Region overlaps another region";
  169. List<RegionData> rdatas = m_Database.Get(
  170. regionInfos.RegionLocX,
  171. regionInfos.RegionLocY,
  172. regionInfos.RegionLocX + regionInfos.RegionSizeX - 1,
  173. regionInfos.RegionLocY + regionInfos.RegionSizeY - 1 ,
  174. scopeID);
  175. RegionData region = null;
  176. if(rdatas.Count > 1)
  177. {
  178. m_log.WarnFormat("{0} Register region overlaps with {1} regions", LogHeader, scopeID, rdatas.Count);
  179. return reason;
  180. }
  181. else if(rdatas.Count == 1)
  182. region = rdatas[0];
  183. if ((region != null) && (region.RegionID != regionInfos.RegionID))
  184. {
  185. // If not same ID and same coordinates, this new region has conflicts and can't be registered.
  186. m_log.WarnFormat("{0} Register region conflict in scope {1}. {2}", LogHeader, scopeID, reason);
  187. return reason;
  188. }
  189. if (region != null)
  190. {
  191. // There is a preexisting record
  192. //
  193. // Get it's flags
  194. //
  195. OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(region.Data["flags"]);
  196. // Is this a reservation?
  197. //
  198. if ((rflags & OpenSim.Framework.RegionFlags.Reservation) != 0)
  199. {
  200. // Regions reserved for the null key cannot be taken.
  201. if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString())
  202. return "Region location is reserved";
  203. // Treat it as an auth request
  204. //
  205. // NOTE: Fudging the flags value here, so these flags
  206. // should not be used elsewhere. Don't optimize
  207. // this with the later retrieval of the same flags!
  208. rflags |= OpenSim.Framework.RegionFlags.Authenticate;
  209. }
  210. if ((rflags & OpenSim.Framework.RegionFlags.Authenticate) != 0)
  211. {
  212. // Can we authenticate at all?
  213. //
  214. if (m_AuthenticationService == null)
  215. return "No authentication possible";
  216. if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
  217. return "Bad authentication";
  218. }
  219. }
  220. // If we get here, the destination is clear. Now for the real check.
  221. if (!m_AllowDuplicateNames)
  222. {
  223. List<RegionData> dupe = m_Database.Get(Util.EscapeForLike(regionInfos.RegionName), scopeID);
  224. if (dupe != null && dupe.Count > 0)
  225. {
  226. foreach (RegionData d in dupe)
  227. {
  228. if (d.RegionID != regionInfos.RegionID)
  229. {
  230. m_log.WarnFormat("[GRID SERVICE]: Region tried to register using a duplicate name. New region: {0} ({1}), existing region: {2} ({3}).",
  231. regionInfos.RegionName, regionInfos.RegionID, d.RegionName, d.RegionID);
  232. return "Duplicate region name";
  233. }
  234. }
  235. }
  236. }
  237. // If there is an old record for us, delete it if it is elsewhere.
  238. region = m_Database.Get(regionInfos.RegionID, scopeID);
  239. if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
  240. ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
  241. {
  242. if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.NoMove) != 0)
  243. return "Can't move this region";
  244. if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.LockedOut) != 0)
  245. return "Region locked out";
  246. // Region reregistering in other coordinates. Delete the old entry
  247. m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
  248. regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionCoordX, regionInfos.RegionCoordY);
  249. try
  250. {
  251. m_Database.Delete(regionInfos.RegionID);
  252. }
  253. catch (Exception e)
  254. {
  255. m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
  256. }
  257. }
  258. // Everything is ok, let's register
  259. RegionData rdata = RegionInfo2RegionData(regionInfos);
  260. rdata.ScopeID = scopeID;
  261. if (region != null)
  262. {
  263. int oldFlags = Convert.ToInt32(region.Data["flags"]);
  264. oldFlags &= ~(int)OpenSim.Framework.RegionFlags.Reservation;
  265. rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
  266. }
  267. else
  268. {
  269. rdata.Data["flags"] = "0";
  270. if ((gridConfig != null) && rdata.RegionName != string.Empty)
  271. {
  272. int newFlags = 0;
  273. string regionName = rdata.RegionName.Trim().Replace(' ', '_');
  274. newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
  275. newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
  276. newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
  277. rdata.Data["flags"] = newFlags.ToString();
  278. }
  279. }
  280. int flags = Convert.ToInt32(rdata.Data["flags"]);
  281. flags |= (int)OpenSim.Framework.RegionFlags.RegionOnline;
  282. rdata.Data["flags"] = flags.ToString();
  283. try
  284. {
  285. rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
  286. m_Database.Store(rdata);
  287. }
  288. catch (Exception e)
  289. {
  290. m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
  291. }
  292. m_log.DebugFormat
  293. ("[GRID SERVICE]: Region {0} ({1}, {2}x{3}) registered at {4},{5} with flags {6}",
  294. regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionSizeX, regionInfos.RegionSizeY,
  295. regionInfos.RegionCoordX, regionInfos.RegionCoordY,
  296. (OpenSim.Framework.RegionFlags)flags);
  297. return String.Empty;
  298. }
  299. // String describing name and region location of passed region
  300. private String RegionString(RegionData reg)
  301. {
  302. return String.Format("{0}/{1} at <{2},{3}>",
  303. reg.RegionName, reg.RegionID, reg.coordX, reg.coordY);
  304. }
  305. // String describing name and region location of passed region
  306. private String RegionString(GridRegion reg)
  307. {
  308. return String.Format("{0}/{1} at <{2},{3}>",
  309. reg.RegionName, reg.RegionID, reg.RegionCoordX, reg.RegionCoordY);
  310. }
  311. public bool DeregisterRegion(UUID regionID)
  312. {
  313. RegionData region = m_Database.Get(regionID, UUID.Zero);
  314. if (region == null)
  315. return false;
  316. m_log.DebugFormat(
  317. "[GRID SERVICE]: Deregistering region {0} ({1}) at {2}-{3}",
  318. region.RegionName, region.RegionID, region.coordX, region.coordY);
  319. int flags = Convert.ToInt32(region.Data["flags"]);
  320. if ((!m_DeleteOnUnregister) || ((flags & (int)OpenSim.Framework.RegionFlags.Persistent) != 0))
  321. {
  322. flags &= ~(int)OpenSim.Framework.RegionFlags.RegionOnline;
  323. region.Data["flags"] = flags.ToString();
  324. region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
  325. try
  326. {
  327. m_Database.Store(region);
  328. }
  329. catch (Exception e)
  330. {
  331. m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
  332. }
  333. return true;
  334. }
  335. return m_Database.Delete(regionID);
  336. }
  337. public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
  338. {
  339. List<GridRegion> rinfos = new List<GridRegion>();
  340. RegionData region = m_Database.Get(regionID, scopeID);
  341. if (region != null)
  342. {
  343. List<RegionData> rdatas = m_Database.Get(
  344. region.posX - 1, region.posY - 1,
  345. region.posX + region.sizeX + 1, region.posY + region.sizeY + 1, scopeID);
  346. foreach (RegionData rdata in rdatas)
  347. {
  348. if (rdata.RegionID != regionID)
  349. {
  350. int flags = Convert.ToInt32(rdata.Data["flags"]);
  351. if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours
  352. rinfos.Add(RegionData2RegionInfo(rdata));
  353. }
  354. }
  355. // string rNames = "";
  356. // foreach (GridRegion gr in rinfos)
  357. // rNames += gr.RegionName + ",";
  358. // m_log.DebugFormat("{0} region {1} has {2} neighbours ({3})",
  359. // LogHeader, region.RegionName, rinfos.Count, rNames);
  360. }
  361. else
  362. {
  363. m_log.WarnFormat(
  364. "[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found",
  365. scopeID, regionID);
  366. }
  367. return rinfos;
  368. }
  369. public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
  370. {
  371. RegionData rdata = m_Database.Get(regionID, scopeID);
  372. if (rdata != null)
  373. return RegionData2RegionInfo(rdata);
  374. return null;
  375. }
  376. public GridRegion GetRegionByHandle(UUID scopeID, ulong regionhandle)
  377. {
  378. int x = (int)(regionhandle >> 32);
  379. int y = (int)(regionhandle & 0xfffffffful);
  380. return GetRegionByPosition(scopeID, x, y);
  381. }
  382. // Get a region given its base coordinates.
  383. // NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
  384. // be the base coordinate of the region.
  385. // The snapping is technically unnecessary but is harmless because regions are always
  386. // multiples of the legacy region size (256).
  387. public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
  388. {
  389. uint regionX = Util.WorldToRegionLoc((uint)x);
  390. uint regionY = Util.WorldToRegionLoc((uint)y);
  391. int snapX = (int)Util.RegionToWorldLoc(regionX);
  392. int snapY = (int)Util.RegionToWorldLoc(regionY);
  393. RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
  394. if (rdata != null)
  395. {
  396. m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in database. Pos=<{2},{3}>",
  397. LogHeader, rdata.RegionName, regionX, regionY);
  398. return RegionData2RegionInfo(rdata);
  399. }
  400. else
  401. {
  402. // m_log.DebugFormat("{0} GetRegionByPosition. Did not find region in database. Pos=<{1},{2}>",
  403. // LogHeader, regionX, regionY);
  404. return null;
  405. }
  406. }
  407. public GridRegion GetRegionByName(UUID scopeID, string name)
  408. {
  409. RegionData rdata = m_Database.GetSpecific(name, scopeID);
  410. if (rdata != null)
  411. return RegionData2RegionInfo(rdata);
  412. if (m_AllowHypergridMapSearch)
  413. {
  414. GridRegion r = GetHypergridRegionByName(scopeID, name);
  415. if (r != null)
  416. return r;
  417. }
  418. return null;
  419. }
  420. public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
  421. {
  422. // m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
  423. List<RegionData> rdatas = m_Database.Get("%" + Util.EscapeForLike(name) + "%", scopeID);
  424. int count = 0;
  425. List<GridRegion> rinfos = new List<GridRegion>();
  426. if (m_AllowHypergridMapSearch && name.Contains("."))
  427. {
  428. string regionURI = "";
  429. string regionName = "";
  430. if (!Util.buildHGRegionURI(name, out regionURI, out regionName))
  431. return null;
  432. string mapname;
  433. bool localGrid = m_HypergridLinker.IsLocalGrid(regionURI);
  434. if (localGrid)
  435. {
  436. if (String.IsNullOrWhiteSpace(regionName))
  437. return GetDefaultRegions(scopeID);
  438. mapname = regionName;
  439. }
  440. else
  441. mapname = regionURI + regionName;
  442. bool haveMatch = false;
  443. if (rdatas != null && (rdatas.Count > 0))
  444. {
  445. // m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
  446. foreach (RegionData rdata in rdatas)
  447. {
  448. if (count++ < maxNumber)
  449. rinfos.Add(RegionData2RegionInfo(rdata));
  450. if(mapname.Equals(rdata.RegionName,StringComparison.InvariantCultureIgnoreCase))
  451. {
  452. haveMatch = true;
  453. if(count == maxNumber)
  454. {
  455. rinfos.RemoveAt(count - 1);
  456. rinfos.Add(RegionData2RegionInfo(rdata));
  457. }
  458. }
  459. }
  460. if(haveMatch)
  461. return rinfos;
  462. }
  463. rdatas = m_Database.Get(Util.EscapeForLike(mapname)+ "%", scopeID);
  464. if (rdatas != null && (rdatas.Count > 0))
  465. {
  466. // m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
  467. foreach (RegionData rdata in rdatas)
  468. {
  469. if (count++ < maxNumber)
  470. rinfos.Add(RegionData2RegionInfo(rdata));
  471. if (mapname.Equals(rdata.RegionName, StringComparison.InvariantCultureIgnoreCase))
  472. {
  473. haveMatch = true;
  474. if(count == maxNumber)
  475. {
  476. rinfos.RemoveAt(count - 1);
  477. rinfos.Add(RegionData2RegionInfo(rdata));
  478. break;
  479. }
  480. }
  481. }
  482. if(haveMatch)
  483. return rinfos;
  484. }
  485. if(!localGrid && !string.IsNullOrWhiteSpace(regionURI))
  486. {
  487. string HGname = regionURI +" "+ regionName; // include space for compatibility
  488. GridRegion r = m_HypergridLinker.LinkRegion(scopeID, HGname);
  489. if (r != null)
  490. {
  491. if( count == maxNumber)
  492. rinfos.RemoveAt(count - 1);
  493. rinfos.Add(r);
  494. }
  495. }
  496. }
  497. else if (rdatas != null && (rdatas.Count > 0))
  498. {
  499. //m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
  500. foreach (RegionData rdata in rdatas)
  501. {
  502. if (count++ < maxNumber)
  503. rinfos.Add(RegionData2RegionInfo(rdata));
  504. if (name.Equals(rdata.RegionName, StringComparison.InvariantCultureIgnoreCase))
  505. {
  506. if (count == maxNumber)
  507. {
  508. rinfos.RemoveAt(count - 1);
  509. rinfos.Add(RegionData2RegionInfo(rdata));
  510. break;
  511. }
  512. }
  513. }
  514. }
  515. return rinfos;
  516. }
  517. /// <summary>
  518. /// Get a hypergrid region.
  519. /// </summary>
  520. /// <param name="scopeID"></param>
  521. /// <param name="name"></param>
  522. /// <returns>null if no hypergrid region could be found.</returns>
  523. protected GridRegion GetHypergridRegionByName(UUID scopeID, string name)
  524. {
  525. if (name.Contains("."))
  526. {
  527. string regionURI = "";
  528. string regionName = "";
  529. if (!Util.buildHGRegionURI(name, out regionURI, out regionName))
  530. return null;
  531. string mapname;
  532. bool localGrid = m_HypergridLinker.IsLocalGrid(regionURI);
  533. if (localGrid)
  534. {
  535. if (String.IsNullOrWhiteSpace(regionName))
  536. {
  537. List< GridRegion> defregs = GetDefaultRegions(scopeID);
  538. if(defregs == null)
  539. return null;
  540. return defregs[0];
  541. }
  542. mapname = regionName;
  543. }
  544. else
  545. mapname = regionURI + regionName;
  546. List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(mapname), scopeID);
  547. if ((rdatas != null) && (rdatas.Count > 0))
  548. return RegionData2RegionInfo(rdatas[0]); // get the first
  549. if(!localGrid && !string.IsNullOrWhiteSpace(regionURI))
  550. {
  551. string HGname = regionURI +" "+ regionName;
  552. return m_HypergridLinker.LinkRegion(scopeID, HGname);
  553. }
  554. }
  555. return null;
  556. }
  557. public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
  558. {
  559. int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
  560. int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
  561. int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
  562. int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
  563. List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
  564. List<GridRegion> rinfos = new List<GridRegion>();
  565. foreach (RegionData rdata in rdatas)
  566. rinfos.Add(RegionData2RegionInfo(rdata));
  567. return rinfos;
  568. }
  569. #endregion
  570. #region Data structure conversions
  571. public RegionData RegionInfo2RegionData(GridRegion rinfo)
  572. {
  573. RegionData rdata = new RegionData();
  574. rdata.posX = (int)rinfo.RegionLocX;
  575. rdata.posY = (int)rinfo.RegionLocY;
  576. rdata.sizeX = rinfo.RegionSizeX;
  577. rdata.sizeY = rinfo.RegionSizeY;
  578. rdata.RegionID = rinfo.RegionID;
  579. rdata.RegionName = rinfo.RegionName;
  580. rdata.Data = rinfo.ToKeyValuePairs();
  581. rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
  582. rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
  583. return rdata;
  584. }
  585. public GridRegion RegionData2RegionInfo(RegionData rdata)
  586. {
  587. GridRegion rinfo = new GridRegion(rdata.Data);
  588. rinfo.RegionLocX = rdata.posX;
  589. rinfo.RegionLocY = rdata.posY;
  590. rinfo.RegionSizeX = rdata.sizeX;
  591. rinfo.RegionSizeY = rdata.sizeY;
  592. rinfo.RegionID = rdata.RegionID;
  593. rinfo.RegionName = rdata.RegionName;
  594. rinfo.ScopeID = rdata.ScopeID;
  595. return rinfo;
  596. }
  597. #endregion
  598. public List<GridRegion> GetDefaultRegions(UUID scopeID)
  599. {
  600. List<GridRegion> ret = new List<GridRegion>();
  601. List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
  602. foreach (RegionData r in regions)
  603. {
  604. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  605. ret.Add(RegionData2RegionInfo(r));
  606. }
  607. m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
  608. return ret;
  609. }
  610. public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
  611. {
  612. List<GridRegion> ret = new List<GridRegion>();
  613. List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID);
  614. foreach (RegionData r in regions)
  615. {
  616. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  617. ret.Add(RegionData2RegionInfo(r));
  618. }
  619. int hgDefaultRegionsFoundOnline = regions.Count;
  620. // For now, hypergrid default regions will always be given precedence but we will also return simple default
  621. // regions in case no specific hypergrid regions are specified.
  622. ret.AddRange(GetDefaultRegions(scopeID));
  623. int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline;
  624. m_log.DebugFormat(
  625. "[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions",
  626. hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline);
  627. return ret;
  628. }
  629. public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
  630. {
  631. List<GridRegion> ret = new List<GridRegion>();
  632. List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
  633. foreach (RegionData r in regions)
  634. {
  635. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  636. ret.Add(RegionData2RegionInfo(r));
  637. }
  638. m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
  639. return ret;
  640. }
  641. public List<GridRegion> GetHyperlinks(UUID scopeID)
  642. {
  643. List<GridRegion> ret = new List<GridRegion>();
  644. List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
  645. foreach (RegionData r in regions)
  646. {
  647. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  648. ret.Add(RegionData2RegionInfo(r));
  649. }
  650. m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
  651. return ret;
  652. }
  653. public int GetRegionFlags(UUID scopeID, UUID regionID)
  654. {
  655. RegionData region = m_Database.Get(regionID, scopeID);
  656. if (region != null)
  657. {
  658. int flags = Convert.ToInt32(region.Data["flags"]);
  659. //m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
  660. return flags;
  661. }
  662. else
  663. return -1;
  664. }
  665. private void HandleDeregisterRegion(string module, string[] cmd)
  666. {
  667. if (cmd.Length < 4)
  668. {
  669. MainConsole.Instance.Output("Usage: degregister region id <region-id>+");
  670. return;
  671. }
  672. for (int i = 3; i < cmd.Length; i++)
  673. {
  674. string rawRegionUuid = cmd[i];
  675. UUID regionUuid;
  676. if (!UUID.TryParse(rawRegionUuid, out regionUuid))
  677. {
  678. MainConsole.Instance.Output("{0} is not a valid region uuid", rawRegionUuid);
  679. return;
  680. }
  681. GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid);
  682. if (region == null)
  683. {
  684. MainConsole.Instance.Output("No region with UUID {0}", regionUuid);
  685. return;
  686. }
  687. if (DeregisterRegion(regionUuid))
  688. {
  689. MainConsole.Instance.Output("Deregistered {0} {1}", region.RegionName, regionUuid);
  690. }
  691. else
  692. {
  693. // I don't think this can ever occur if we know that the region exists.
  694. MainConsole.Instance.Output("Error deregistering {0} {1}", region.RegionName, regionUuid);
  695. }
  696. }
  697. }
  698. private void HandleShowRegions(string module, string[] cmd)
  699. {
  700. if (cmd.Length != 2)
  701. {
  702. MainConsole.Instance.Output("Syntax: show regions");
  703. return;
  704. }
  705. List<RegionData> regions = m_Database.Get(0, 0, int.MaxValue, int.MaxValue, UUID.Zero);
  706. OutputRegionsToConsoleSummary(regions);
  707. }
  708. private void HandleShowGridSize(string module, string[] cmd)
  709. {
  710. List<RegionData> regions = m_Database.Get(0, 0, int.MaxValue, int.MaxValue, UUID.Zero);
  711. double size = 0;
  712. foreach (RegionData region in regions)
  713. {
  714. int flags = Convert.ToInt32(region.Data["flags"]);
  715. if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0)
  716. size += region.sizeX * region.sizeY;
  717. }
  718. MainConsole.Instance.Output("This is a very rough approximation.");
  719. MainConsole.Instance.Output("Although it will not count regions that are actually links to others over the Hypergrid, ");
  720. MainConsole.Instance.Output("it will count regions that are inactive but were not deregistered from the grid service");
  721. MainConsole.Instance.Output("(e.g. simulator crashed rather than shutting down cleanly).\n");
  722. MainConsole.Instance.Output("Grid size: {0} km squared.", size / 1000000);
  723. }
  724. private void HandleShowRegion(string module, string[] cmd)
  725. {
  726. if (cmd.Length != 4)
  727. {
  728. MainConsole.Instance.Output("Syntax: show region name <region name>");
  729. return;
  730. }
  731. string regionName = cmd[3];
  732. List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero);
  733. if (regions == null || regions.Count < 1)
  734. {
  735. MainConsole.Instance.Output("No region with name {0} found", regionName);
  736. return;
  737. }
  738. OutputRegionsToConsole(regions);
  739. }
  740. private void HandleShowRegionAt(string module, string[] cmd)
  741. {
  742. if (cmd.Length != 5)
  743. {
  744. MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>");
  745. return;
  746. }
  747. uint x, y;
  748. if (!uint.TryParse(cmd[3], out x))
  749. {
  750. MainConsole.Instance.Output("x-coord must be an integer");
  751. return;
  752. }
  753. if (!uint.TryParse(cmd[4], out y))
  754. {
  755. MainConsole.Instance.Output("y-coord must be an integer");
  756. return;
  757. }
  758. RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero);
  759. if (region == null)
  760. {
  761. MainConsole.Instance.Output("No region found at {0},{1}", x, y);
  762. return;
  763. }
  764. OutputRegionToConsole(region);
  765. }
  766. private void OutputRegionToConsole(RegionData r)
  767. {
  768. OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
  769. ConsoleDisplayList dispList = new ConsoleDisplayList();
  770. dispList.AddRow("Region Name", r.RegionName);
  771. dispList.AddRow("Region ID", r.RegionID);
  772. dispList.AddRow("Location", string.Format("{0},{1}", r.coordX, r.coordY));
  773. dispList.AddRow("Size", string.Format("{0}x{1}", r.sizeX, r.sizeY));
  774. dispList.AddRow("URI", r.Data["serverURI"]);
  775. dispList.AddRow("Owner ID", r.Data["owner_uuid"]);
  776. dispList.AddRow("Flags", flags);
  777. MainConsole.Instance.Output(dispList.ToString());
  778. }
  779. private void OutputRegionsToConsole(List<RegionData> regions)
  780. {
  781. foreach (RegionData r in regions)
  782. OutputRegionToConsole(r);
  783. }
  784. private void OutputRegionsToConsoleSummary(List<RegionData> regions)
  785. {
  786. ConsoleDisplayTable dispTable = new ConsoleDisplayTable();
  787. dispTable.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize);
  788. dispTable.AddColumn("ID", ConsoleDisplayUtil.UuidSize);
  789. dispTable.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize);
  790. dispTable.AddColumn("Size", 11);
  791. dispTable.AddColumn("Flags", 60);
  792. foreach (RegionData r in regions)
  793. {
  794. OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
  795. dispTable.AddRow(
  796. r.RegionName,
  797. r.RegionID.ToString(),
  798. string.Format("{0},{1}", r.coordX, r.coordY),
  799. string.Format("{0}x{1}", r.sizeX, r.sizeY),
  800. flags.ToString());
  801. }
  802. MainConsole.Instance.Output(dispTable.ToString());
  803. }
  804. private int ParseFlags(int prev, string flags)
  805. {
  806. OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev;
  807. string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
  808. foreach (string p in parts)
  809. {
  810. int val;
  811. try
  812. {
  813. if (p.StartsWith("+"))
  814. {
  815. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
  816. f |= (OpenSim.Framework.RegionFlags)val;
  817. }
  818. else if (p.StartsWith("-"))
  819. {
  820. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
  821. f &= ~(OpenSim.Framework.RegionFlags)val;
  822. }
  823. else
  824. {
  825. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p);
  826. f |= (OpenSim.Framework.RegionFlags)val;
  827. }
  828. }
  829. catch (Exception)
  830. {
  831. MainConsole.Instance.Output("Error in flag specification: " + p);
  832. }
  833. }
  834. return (int)f;
  835. }
  836. private void HandleSetFlags(string module, string[] cmd)
  837. {
  838. if (cmd.Length < 5)
  839. {
  840. MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
  841. return;
  842. }
  843. List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero);
  844. if (regions == null || regions.Count < 1)
  845. {
  846. MainConsole.Instance.Output("Region not found");
  847. return;
  848. }
  849. foreach (RegionData r in regions)
  850. {
  851. int flags = Convert.ToInt32(r.Data["flags"]);
  852. flags = ParseFlags(flags, cmd[4]);
  853. r.Data["flags"] = flags.ToString();
  854. OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags;
  855. MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
  856. m_Database.Store(r);
  857. }
  858. }
  859. /// <summary>
  860. /// Gets the grid extra service URls we wish for the region to send in OpenSimExtras to dynamically refresh
  861. /// parameters in the viewer used to access services like map, search and destination guides.
  862. /// <para>see "SimulatorFeaturesModule" </para>
  863. /// </summary>
  864. /// <returns>
  865. /// The grid extra service URls.
  866. /// </returns>
  867. public Dictionary<string,object> GetExtraFeatures()
  868. {
  869. return m_ExtraFeatures;
  870. }
  871. }
  872. }