1
0

GridService.cs 45 KB

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