GridService.cs 43 KB

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