GridService.cs 43 KB

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