HGEntityTransferModule.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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.Reflection;
  30. using OpenSim.Framework;
  31. using OpenSim.Framework.Client;
  32. using OpenSim.Framework.Monitoring;
  33. using OpenSim.Region.Framework.Interfaces;
  34. using OpenSim.Region.Framework.Scenes;
  35. using OpenSim.Services.Connectors.Hypergrid;
  36. using OpenSim.Services.Interfaces;
  37. using OpenSim.Server.Base;
  38. using OpenMetaverse;
  39. using log4net;
  40. using Nini.Config;
  41. using Mono.Addins;
  42. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  43. namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
  44. {
  45. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGEntityTransferModule")]
  46. public class HGEntityTransferModule : EntityTransferModule, IUserAgentVerificationModule
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private int m_levelHGTeleport = 0;
  50. private GatekeeperServiceConnector m_GatekeeperConnector;
  51. private IUserAgentService m_UAS;
  52. protected bool m_RestrictAppearanceAbroad;
  53. protected string m_AccountName;
  54. protected List<AvatarAppearance> m_ExportedAppearances;
  55. protected List<AvatarAttachment> m_Attachs;
  56. protected List<AvatarAppearance> ExportedAppearance
  57. {
  58. get
  59. {
  60. if (m_ExportedAppearances != null)
  61. return m_ExportedAppearances;
  62. m_ExportedAppearances = new List<AvatarAppearance>();
  63. m_Attachs = new List<AvatarAttachment>();
  64. string[] names = m_AccountName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  65. foreach (string name in names)
  66. {
  67. string[] parts = name.Trim().Split();
  68. if (parts.Length != 2)
  69. {
  70. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Wrong user account name format {0}. Specify 'First Last'", name);
  71. return null;
  72. }
  73. UserAccount account = m_scene.UserAccountService.GetUserAccount(UUID.Zero, parts[0], parts[1]);
  74. if (account == null)
  75. {
  76. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unknown account {0}", m_AccountName);
  77. return null;
  78. }
  79. AvatarAppearance a = m_scene.AvatarService.GetAppearance(account.PrincipalID);
  80. if (a != null)
  81. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Successfully retrieved appearance for {0}", name);
  82. foreach (AvatarAttachment att in a.GetAttachments())
  83. {
  84. InventoryItemBase item = m_scene.InventoryService.GetItem(account.PrincipalID, att.ItemID);
  85. if (item != null)
  86. a.SetAttachment(att.AttachPoint, att.ItemID, item.AssetID);
  87. else
  88. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to retrieve item {0} from inventory {1}", att.ItemID, name);
  89. }
  90. m_ExportedAppearances.Add(a);
  91. m_Attachs.AddRange(a.GetAttachments());
  92. }
  93. return m_ExportedAppearances;
  94. }
  95. }
  96. /// <summary>
  97. /// Used for processing analysis of incoming attachments in a controlled fashion.
  98. /// </summary>
  99. private JobEngine m_incomingSceneObjectEngine;
  100. #region ISharedRegionModule
  101. public override string Name
  102. {
  103. get { return "HGEntityTransferModule"; }
  104. }
  105. public override void Initialise(IConfigSource source)
  106. {
  107. IConfig moduleConfig = source.Configs["Modules"];
  108. if (moduleConfig != null)
  109. {
  110. string name = moduleConfig.GetString("EntityTransferModule", "");
  111. if (name == Name)
  112. {
  113. IConfig transferConfig = source.Configs["EntityTransfer"];
  114. if (transferConfig != null)
  115. {
  116. m_levelHGTeleport = transferConfig.GetInt("LevelHGTeleport", 0);
  117. m_RestrictAppearanceAbroad = transferConfig.GetBoolean("RestrictAppearanceAbroad", false);
  118. if (m_RestrictAppearanceAbroad)
  119. {
  120. m_AccountName = transferConfig.GetString("AccountForAppearance", string.Empty);
  121. if (m_AccountName.Length == 0)
  122. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is on, but no account has been given for avatar appearance!");
  123. }
  124. }
  125. InitialiseCommon(source);
  126. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: {0} enabled.", Name);
  127. }
  128. }
  129. }
  130. public override void AddRegion(Scene scene)
  131. {
  132. base.AddRegion(scene);
  133. if (m_Enabled)
  134. {
  135. scene.RegisterModuleInterface<IUserAgentVerificationModule>(this);
  136. //scene.EventManager.OnIncomingSceneObject += OnIncomingSceneObject;
  137. m_incomingSceneObjectEngine
  138. = new JobEngine(
  139. string.Format("HG Incoming Scene Object Engine ({0})", scene.Name),
  140. "HG INCOMING SCENE OBJECT ENGINE", 30000);
  141. StatsManager.RegisterStat(
  142. new Stat(
  143. "HGIncomingAttachmentsWaiting",
  144. "Number of incoming attachments waiting for processing.",
  145. "",
  146. "",
  147. "entitytransfer",
  148. Name,
  149. StatType.Pull,
  150. MeasuresOfInterest.None,
  151. stat => stat.Value = m_incomingSceneObjectEngine.JobsWaiting,
  152. StatVerbosity.Debug));
  153. m_incomingSceneObjectEngine.Start();
  154. }
  155. }
  156. public override void RegionLoaded(Scene scene)
  157. {
  158. base.RegionLoaded(scene);
  159. if (m_Enabled)
  160. {
  161. m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService);
  162. m_UAS = scene.RequestModuleInterface<IUserAgentService>();
  163. if (m_UAS == null)
  164. m_UAS = new UserAgentServiceConnector(m_thisGridInfo.HomeURL);
  165. }
  166. }
  167. public override void RemoveRegion(Scene scene)
  168. {
  169. base.RemoveRegion(scene);
  170. if (m_Enabled)
  171. {
  172. scene.UnregisterModuleInterface<IUserAgentVerificationModule>(this);
  173. m_incomingSceneObjectEngine.Stop();
  174. }
  175. }
  176. #endregion
  177. #region HG overrides of IEntityTransferModule
  178. protected override GridRegion GetFinalDestination(GridRegion region, UUID agentID, string agentHomeURI, out string message)
  179. {
  180. int flags = m_scene.GridService.GetRegionFlags(m_sceneRegionInfo.ScopeID, region.RegionID);
  181. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionName, flags);
  182. message = null;
  183. if ((flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  184. {
  185. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region is hyperlink");
  186. GridRegion real_destination = m_GatekeeperConnector.GetHyperlinkRegion(region, region.RegionID, agentID, agentHomeURI, out message);
  187. if (real_destination != null)
  188. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: GetFinalDestination: ServerURI={0}", real_destination.ServerURI);
  189. else
  190. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: GetHyperlinkRegion of region {0} from Gatekeeper {1} failed: {2}", region.RegionID, region.ServerURI, message);
  191. return real_destination;
  192. }
  193. return region;
  194. }
  195. protected override bool NeedsClosing(GridRegion reg, bool OutViewRange)
  196. {
  197. if (OutViewRange)
  198. return true;
  199. int flags = m_scene.GridService.GetRegionFlags(m_sceneRegionInfo.ScopeID, reg.RegionID);
  200. if (flags == -1 || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  201. return true;
  202. return false;
  203. }
  204. protected override void AgentHasMovedAway(ScenePresence sp, bool logout)
  205. {
  206. base.AgentHasMovedAway(sp, logout);
  207. if (logout)
  208. {
  209. // Log them out of this grid
  210. m_scene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  211. string userId = m_scene.UserManagementModule.GetUserUUI(sp.UUID);
  212. m_scene.GridUserService.LoggedOut(userId, UUID.Zero, m_sceneRegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat);
  213. }
  214. }
  215. protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason, out bool logout)
  216. {
  217. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI);
  218. reason = string.Empty;
  219. logout = false;
  220. int flags = Scene.GridService.GetRegionFlags(m_sceneRegionInfo.ScopeID, reg.RegionID);
  221. if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  222. {
  223. // this user is going to another grid
  224. // for local users, check if HyperGrid teleport is allowed, based on user level
  225. bool isLocal = m_scene.UserManagementModule.IsLocalGridUser(sp.UUID);
  226. if (isLocal && sp.GodController.UserLevel < m_levelHGTeleport)
  227. {
  228. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to HG teleport agent due to insufficient UserLevel.");
  229. reason = "Hypergrid teleport not allowed";
  230. return false;
  231. }
  232. if (agentCircuit.ServiceURLs.ContainsKey("HomeURI"))
  233. {
  234. string userAgentDriver = agentCircuit.ServiceURLs["HomeURI"].ToString();
  235. IUserAgentService connector;
  236. if (m_thisGridInfo.IsLocalHome(userAgentDriver) == 1 && m_UAS != null)
  237. connector = m_UAS;
  238. else
  239. connector = new UserAgentServiceConnector(userAgentDriver);
  240. GridRegion source = new GridRegion(m_sceneRegionInfo)
  241. {
  242. RawServerURI = m_thisGridInfo.GateKeeperURL
  243. };
  244. bool success = connector.LoginAgentToGrid(source, agentCircuit, reg, finalDestination, false, out reason);
  245. //logout = success & !isLocal; // flag for later logout from this grid; this is an HG TP
  246. logout = success; // flag for later logout from this grid; this is an HG TP
  247. if (success)
  248. m_scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
  249. return success;
  250. }
  251. else
  252. {
  253. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent does not have a HomeURI address");
  254. return false;
  255. }
  256. }
  257. return base.CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, ctx, out reason, out logout);
  258. }
  259. public override void TriggerTeleportHome(UUID id, IClientAPI client)
  260. {
  261. TeleportHome(id, client);
  262. }
  263. protected override bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason)
  264. {
  265. reason = "Please wear your grid's allowed appearance before teleporting to another grid";
  266. if (!m_RestrictAppearanceAbroad)
  267. return true;
  268. // The rest is only needed for controlling appearance
  269. int flags = m_scene.GridService.GetRegionFlags(m_sceneRegionInfo.ScopeID, reg.RegionID);
  270. if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  271. {
  272. // this user is going to another grid
  273. if (m_scene.UserManagementModule.IsLocalGridUser(sp.UUID))
  274. {
  275. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Checking generic appearance");
  276. // Check wearables
  277. for (int i = 0; i < sp.Appearance.Wearables.Length ; i++)
  278. {
  279. for (int j = 0; j < sp.Appearance.Wearables[i].Count; j++)
  280. {
  281. if (sp.Appearance.Wearables[i] == null)
  282. continue;
  283. bool found = false;
  284. foreach (AvatarAppearance a in ExportedAppearance)
  285. if (i < a.Wearables.Length && a.Wearables[i] != null)
  286. {
  287. found = true;
  288. break;
  289. }
  290. if (!found)
  291. {
  292. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i);
  293. return false;
  294. }
  295. found = false;
  296. foreach (AvatarAppearance a in ExportedAppearance)
  297. if (i < a.Wearables.Length && sp.Appearance.Wearables[i][j].AssetID == a.Wearables[i][j].AssetID)
  298. {
  299. found = true;
  300. break;
  301. }
  302. if (!found)
  303. {
  304. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i);
  305. return false;
  306. }
  307. }
  308. }
  309. // Check attachments
  310. foreach (AvatarAttachment att in sp.Appearance.GetAttachments())
  311. {
  312. bool found = false;
  313. foreach (AvatarAttachment att2 in m_Attachs)
  314. {
  315. if (att2.AssetID == att.AssetID)
  316. {
  317. found = true;
  318. break;
  319. }
  320. }
  321. if (!found)
  322. {
  323. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Attachment not allowed to go outside {0}", att.AttachPoint);
  324. return false;
  325. }
  326. }
  327. }
  328. }
  329. reason = string.Empty;
  330. return true;
  331. }
  332. //protected override bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agentData, ScenePresence sp)
  333. //{
  334. // int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  335. // if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0)
  336. // {
  337. // // this user is going to another grid
  338. // if (m_RestrictAppearanceAbroad && Scene.UserManagementModule.IsLocalGridUser(agentData.AgentID))
  339. // {
  340. // // We need to strip the agent off its appearance
  341. // m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Sending generic appearance");
  342. // // Delete existing npc attachments
  343. // Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, false);
  344. // // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet since it doesn't transfer attachments
  345. // AvatarAppearance newAppearance = new AvatarAppearance(ExportedAppearance, true);
  346. // sp.Appearance = newAppearance;
  347. // // Rez needed npc attachments
  348. // Scene.AttachmentsModule.RezAttachments(sp);
  349. // IAvatarFactoryModule module = Scene.RequestModuleInterface<IAvatarFactoryModule>();
  350. // //module.SendAppearance(sp.UUID);
  351. // module.RequestRebake(sp, false);
  352. // Scene.AttachmentsModule.CopyAttachments(sp, agentData);
  353. // agentData.Appearance = sp.Appearance;
  354. // }
  355. // }
  356. // foreach (AvatarAttachment a in agentData.Appearance.GetAttachments())
  357. // m_log.DebugFormat("[XXX]: {0}-{1}", a.ItemID, a.AssetID);
  358. // return base.UpdateAgent(reg, finalDestination, agentData, sp);
  359. //}
  360. public override bool TeleportHome(UUID id, IClientAPI client)
  361. {
  362. // Let's find out if this is a foreign user or a local user
  363. IUserManagement uMan = m_scene.RequestModuleInterface<IUserManagement>();
  364. if (uMan != null && uMan.IsLocalGridUser(id))
  365. {
  366. // local grid user
  367. return base.TeleportHome(id, client);
  368. }
  369. bool notsame = false;
  370. if (client == null)
  371. {
  372. m_log.DebugFormat(
  373. "[HG ENTITY TRANSFER MODULE]: Request to teleport {0} home", id);
  374. }
  375. else
  376. {
  377. if (id == client.AgentId)
  378. {
  379. m_log.DebugFormat(
  380. "[HG ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, id);
  381. }
  382. else
  383. {
  384. notsame = true;
  385. m_log.DebugFormat(
  386. "[HG ENTITY TRANSFER MODULE]: Request to teleport {0} home by {1} {2}", id, client.Name, client.AgentId);
  387. }
  388. }
  389. ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(id);
  390. if (sp == null || sp.IsDeleted || sp.IsChildAgent || sp.ControllingClient == null || !sp.ControllingClient.IsActive)
  391. {
  392. if (notsame)
  393. client.SendAlertMessage("TeleportHome: Agent not found in the scene");
  394. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene");
  395. return false;
  396. }
  397. IClientAPI targetClient = sp.ControllingClient;
  398. if (sp.IsInTransit)
  399. {
  400. if (notsame)
  401. client.SendAlertMessage("TeleportHome: Agent already processing a teleport");
  402. targetClient.SendTeleportFailed("Already processing a teleport");
  403. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent still in teleport");
  404. return false;
  405. }
  406. // Foreign user wants to go home
  407. //
  408. AgentCircuitData aCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(targetClient.CircuitCode);
  409. if (aCircuit == null)
  410. {
  411. if (notsame)
  412. client.SendAlertMessage("TeleportHome: Agent information not found");
  413. targetClient.SendTeleportFailed("Home information not found");
  414. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information");
  415. return false;
  416. }
  417. if (!aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  418. {
  419. if (notsame)
  420. client.SendAlertMessage("TeleportHome: Agent home not set");
  421. targetClient.SendTeleportFailed("Home not set");
  422. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent home not set");
  423. return false;
  424. }
  425. string homeURI = aCircuit.ServiceURLs["HomeURI"].ToString();
  426. IUserAgentService userAgentService = new UserAgentServiceConnector(homeURI);
  427. Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
  428. GridRegion finalDestination = null;
  429. try
  430. {
  431. finalDestination = userAgentService.GetHomeRegion(id, out position, out lookAt);
  432. }
  433. catch (Exception e)
  434. {
  435. m_log.Debug("[HG ENTITY TRANSFER MODULE]: GetHomeRegion call failed ", e);
  436. }
  437. if (finalDestination == null)
  438. {
  439. if (notsame)
  440. client.SendAlertMessage("TeleportHome: Agent Home region not found");
  441. targetClient.SendTeleportFailed("Home region not found");
  442. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found");
  443. return false;
  444. }
  445. GridRegion homeGatekeeper = MakeGateKeeperRegion(homeURI);
  446. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}",
  447. aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ServerURI, homeGatekeeper.RegionName);
  448. DoTeleport(sp, homeGatekeeper, finalDestination, position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  449. return true;
  450. }
  451. /// <summary>
  452. /// Tries to teleport agent to landmark.
  453. /// </summary>
  454. /// <param name="remoteClient"></param>
  455. /// <param name="regionHandle"></param>
  456. /// <param name="position"></param>
  457. public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm, Vector3 lookAt)
  458. {
  459. if (lm == null || lm.Data == null || lm.Data.Length == 0)
  460. return;
  461. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}",
  462. (string.IsNullOrEmpty(lm.Gatekeeper)) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position);
  463. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  464. if (sp == null || sp.IsDeleted || sp.IsInTransit || sp.IsChildAgent || sp.IsNPC)
  465. return;
  466. OSHHTPHost gatekeeperHost = new OSHHTPHost(lm.Gatekeeper);
  467. if (m_thisGridInfo.IsLocalGrid(gatekeeperHost) != 0)
  468. {
  469. // Local region?
  470. GridRegion info = m_scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  471. if (info == null)
  472. {
  473. remoteClient.SendTeleportFailed("Landmark region not found");
  474. return;
  475. }
  476. //check if region on same position and fix local offset
  477. if (Util.CompareRegionHandles(lm.RegionHandle, lm.Position, info.RegionLocX, info.RegionLocY, info.RegionSizeX, info.RegionSizeY, out Vector3 offset))
  478. {
  479. m_scene.RequestTeleportLocation(remoteClient, info.RegionHandle, offset,
  480. lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  481. }
  482. else //region may had move to other grid slot. assume the lm position is good
  483. m_scene.RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
  484. lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  485. return;
  486. }
  487. if (!gatekeeperHost.ResolveDNS())
  488. {
  489. remoteClient.SendTeleportFailed("Could not resolve Landmark grid gatekeeper");
  490. return;
  491. }
  492. // Foreign region
  493. GridRegion gatekeeper = new GridRegion()
  494. {
  495. ExternalHostName = gatekeeperHost.Host,
  496. HttpPort = (uint)gatekeeperHost.Port,
  497. ServerURI = lm.Gatekeeper,
  498. RegionName = string.Empty,
  499. InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0),
  500. RegionFlags = OpenSim.Framework.RegionFlags.Hyperlink
  501. };
  502. string homeURI = m_scene.GetAgentHomeURI(remoteClient.AgentId);
  503. GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
  504. GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, lm.RegionID, remoteClient.AgentId, homeURI, out string message);
  505. if(finalDestination == null)
  506. {
  507. remoteClient.SendTeleportFailed(message);
  508. return;
  509. }
  510. // Validate assorted conditions
  511. if (!ValidateGenericConditions(sp, gatekeeper, finalDestination, 0, out string reason))
  512. {
  513. remoteClient.SendTeleportFailed(reason);
  514. return;
  515. }
  516. if (Util.CompareRegionHandles(lm.RegionHandle, lm.Position, finalDestination.RegionLocX, finalDestination.RegionLocY,
  517. finalDestination.RegionSizeX, finalDestination.RegionSizeY, out Vector3 roffset))
  518. {
  519. DoTeleport(sp, gatekeeper, finalDestination, roffset, lookAt,
  520. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  521. return;
  522. }
  523. remoteClient.SendTeleportFailed("landmark region not found");
  524. }
  525. private void RemoveIncomingSceneObjectJobs(string commonIdToRemove)
  526. {
  527. List<JobEngine.Job> jobsToReinsert = new List<JobEngine.Job>();
  528. int jobsRemoved = 0;
  529. JobEngine.Job job;
  530. while ((job = m_incomingSceneObjectEngine.RemoveNextJob()) != null)
  531. {
  532. if (job.CommonId != commonIdToRemove)
  533. jobsToReinsert.Add(job);
  534. else
  535. jobsRemoved++;
  536. }
  537. m_log.DebugFormat(
  538. "[HG ENTITY TRANSFER]: Removing {0} jobs with common ID {1} and reinserting {2} other jobs",
  539. jobsRemoved, commonIdToRemove, jobsToReinsert.Count);
  540. if (jobsToReinsert.Count > 0)
  541. {
  542. foreach (JobEngine.Job jobToReinsert in jobsToReinsert)
  543. m_incomingSceneObjectEngine.QueueJob(jobToReinsert);
  544. }
  545. }
  546. public override bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition)
  547. {
  548. UUID OwnerID = so.OwnerID;
  549. if (OwnerID.IsZero())
  550. {
  551. m_log.DebugFormat(
  552. "[HG TRANSFER MODULE]: Denied object {0}({1}) entry into {2} because ownerID is zero",
  553. so.Name, so.UUID, m_sceneName);
  554. return false;
  555. }
  556. if (m_sceneRegionInfo.EstateSettings.IsBanned(OwnerID))
  557. {
  558. m_log.DebugFormat(
  559. "[HG TRANSFER MODULE]: Denied prim crossing of {0} {1} into {2} for banned avatar {3}",
  560. so.Name, so.UUID, m_sceneName, so.OwnerID);
  561. return false;
  562. }
  563. // FIXME: We must make it so that we can use SOG.IsAttachment here. At the moment it is always null!
  564. if (!so.IsAttachmentCheckFull())
  565. return base.HandleIncomingSceneObject(so, newPosition);
  566. // Equally, we can't use so.AttachedAvatar here.
  567. if (m_scene.UserManagementModule.IsLocalGridUser(OwnerID))
  568. return base.HandleIncomingSceneObject(so, newPosition);
  569. if (m_scene.GetScenePresence(OwnerID) == null)
  570. {
  571. m_log.DebugFormat(
  572. "[HG TRANSFER MODULE]: Denied attachment {0}({1}) owner {2} not in region {3}",
  573. so.Name, so.UUID, OwnerID, m_sceneName);
  574. return false;
  575. }
  576. if (!m_scene.AddSceneObject(so))
  577. {
  578. m_log.DebugFormat(
  579. "[ENTITY TRANSFER MODULE]: Problem adding scene object {0} {1} into {2} ",
  580. so.Name, so.UUID, m_sceneName);
  581. return false;
  582. }
  583. // foreign user
  584. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(OwnerID);
  585. if (aCircuit != null)
  586. {
  587. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) == 0)
  588. {
  589. // We have already pulled the necessary attachments from the source grid.
  590. base.HandleIncomingSceneObject(so, newPosition);
  591. }
  592. else
  593. {
  594. if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
  595. {
  596. SceneObjectGroup defso = so;
  597. m_incomingSceneObjectEngine.QueueJob(
  598. string.Format("HG UUID Gather for attachment {0} for {1}", defso.Name, aCircuit.Name),
  599. () =>
  600. {
  601. string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
  602. //m_log.DebugFormat(
  603. // "[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset service {2}",
  604. // so.Name, so.AttachedAvatar, url);
  605. IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
  606. HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, url, ids);
  607. uuidGatherer.AddForInspection(defso);
  608. while (!uuidGatherer.Complete)
  609. {
  610. int tickStart = Util.EnvironmentTickCount();
  611. uuidGatherer.GatherNext();
  612. //m_log.DebugFormat(
  613. // "[HG ENTITY TRANSFER]: Gathered attachment asset uuid {0} for object {1} for HG user {2} took {3} ms with asset service {4}",
  614. // nextUuid, so.Name, so.OwnerID, Util.EnvironmentTickCountSubtract(tickStart), url);
  615. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  616. if (ticksElapsed > 30000)
  617. {
  618. m_log.WarnFormat(
  619. "[HG ENTITY TRANSFER]: Removing incoming scene object jobs for HG user {0} as gather of {1} from {2} took {3} ms to respond (> {4} ms)",
  620. so.OwnerID, so.Name, url, ticksElapsed, 30000);
  621. RemoveIncomingSceneObjectJobs(OwnerID.ToString());
  622. return;
  623. }
  624. }
  625. //m_log.DebugFormat(
  626. // "[HG ENTITY TRANSFER]: Fetching {0} assets for attachment {1} for HG user {2} with asset service {3}",
  627. // ids.Count, so.Name, so.OwnerID, url);
  628. foreach (UUID id in ids.Keys)
  629. {
  630. int tickStart = Util.EnvironmentTickCount();
  631. uuidGatherer.FetchAsset(id);
  632. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  633. if (ticksElapsed > 30000)
  634. {
  635. m_log.WarnFormat(
  636. "[HG ENTITY TRANSFER]: Removing incoming scene object jobs for HG user {0} as fetch of {1} from {2} took {3} ms to respond (> {4} ms)",
  637. so.OwnerID, id, url, ticksElapsed, 30000);
  638. RemoveIncomingSceneObjectJobs(OwnerID.ToString());
  639. return;
  640. }
  641. }
  642. base.HandleIncomingSceneObject(defso, newPosition);
  643. defso = null;
  644. aCircuit = null;
  645. uuidGatherer = null;
  646. //m_log.DebugFormat(
  647. // "[HG ENTITY TRANSFER MODULE]: Completed incoming attachment {0} for HG user {1} with asset server {2}",
  648. // so.Name, so.OwnerID, url);
  649. },
  650. OwnerID.ToString());
  651. }
  652. }
  653. }
  654. return true;
  655. }
  656. public override bool HandleIncomingAttachments(ScenePresence sp, List<SceneObjectGroup> attachments)
  657. {
  658. UUID OwnerID = sp.UUID;
  659. if (m_sceneRegionInfo.EstateSettings.IsBanned(OwnerID))
  660. {
  661. m_log.DebugFormat(
  662. "[HG TRANSFER MODULE]: Attachments of banned avatar {0} into {1}", sp.Name, m_sceneName);
  663. return false;
  664. }
  665. if (OwnerID.IsZero() || m_scene.UserManagementModule.IsLocalGridUser(OwnerID))
  666. return base.HandleIncomingAttachments(sp, attachments);
  667. // foreign user
  668. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(OwnerID);
  669. if (aCircuit != null)
  670. {
  671. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) == 0)
  672. {
  673. // first region in local grid did pull the necessary attachments from the source grid.
  674. base.HandleIncomingAttachments(sp, attachments);
  675. }
  676. else
  677. {
  678. if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
  679. {
  680. ScenePresence defsp = sp;
  681. List<SceneObjectGroup> deftatt = attachments;
  682. List<SceneObjectGroup> toadd = new List<SceneObjectGroup>(deftatt.Count);
  683. m_incomingSceneObjectEngine.QueueJob(
  684. string.Format("HG UUID Gather attachments {0}", defsp.Name), () =>
  685. {
  686. string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
  687. IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
  688. HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, url, ids);
  689. foreach (SceneObjectGroup defso in deftatt)
  690. {
  691. if(defso.OwnerID.NotEqual(defsp.UUID))
  692. {
  693. m_log.ErrorFormat(
  694. "[HG TRANSFER MODULE] attachment {0}({1} owner {2} does not match HG avatarID {3}",
  695. defso.Name, defso.UUID, defso.OwnerID, defsp.UUID);
  696. continue;
  697. }
  698. uuidGatherer.AddForInspection(defso);
  699. while (!uuidGatherer.Complete)
  700. {
  701. if (sp.IsDeleted)
  702. {
  703. deftatt = null;
  704. defsp = null;
  705. uuidGatherer = null;
  706. toadd = null;
  707. return;
  708. }
  709. uuidGatherer.GatherNext();
  710. }
  711. toadd.Add(defso);
  712. }
  713. deftatt = null;
  714. foreach (UUID id in ids.Keys)
  715. {
  716. int tickStart = Util.EnvironmentTickCount();
  717. uuidGatherer.FetchAsset(id);
  718. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  719. if (sp.IsDeleted || ticksElapsed > 30000)
  720. {
  721. m_log.WarnFormat(
  722. "[HG ENTITY TRANSFER]: Aborting fetch attachments assets for HG user {0}", sp.Name);
  723. defsp = null;
  724. uuidGatherer = null;
  725. toadd = null;
  726. return;
  727. }
  728. }
  729. base.HandleIncomingAttachments(sp, toadd);
  730. defsp = null;
  731. uuidGatherer = null;
  732. toadd = null;
  733. },
  734. OwnerID.ToString());
  735. }
  736. }
  737. }
  738. return true;
  739. }
  740. #endregion
  741. #region IUserAgentVerificationModule
  742. public bool VerifyClient(AgentCircuitData aCircuit, string token)
  743. {
  744. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  745. {
  746. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  747. IUserAgentService security = new UserAgentServiceConnector(url);
  748. return security.VerifyClient(aCircuit.SessionID, token);
  749. }
  750. else
  751. {
  752. m_log.DebugFormat(
  753. "[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!",
  754. aCircuit.firstname, aCircuit.lastname);
  755. }
  756. return false;
  757. }
  758. public override void OnConnectionClosed(IClientAPI obj)
  759. {
  760. if (obj.SceneAgent.IsChildAgent)
  761. return;
  762. // Let's find out if this is a foreign user or a local user
  763. IUserManagement uMan = m_scene.RequestModuleInterface<IUserManagement>();
  764. // UserAccount account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, obj.AgentId);
  765. if (uMan != null && uMan.IsLocalGridUser(obj.AgentId))
  766. {
  767. // local grid user
  768. m_UAS.LogoutAgent(obj.AgentId, obj.SessionId);
  769. return;
  770. }
  771. AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode);
  772. if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  773. {
  774. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  775. IUserAgentService security = new UserAgentServiceConnector(url);
  776. security.LogoutAgent(obj.AgentId, obj.SessionId);
  777. //m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
  778. }
  779. else
  780. {
  781. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId);
  782. }
  783. base.OnConnectionClosed(obj);
  784. }
  785. #endregion
  786. private GridRegion MakeGateKeeperRegion(string wantedURI)
  787. {
  788. if(!Uri.TryCreate(wantedURI, UriKind.Absolute, out Uri uri))
  789. return null;
  790. return new GridRegion()
  791. {
  792. ExternalHostName = uri.Host,
  793. HttpPort = (uint)uri.Port,
  794. ServerURI = wantedURI, //uri.AbsoluteUri for some reason default ports are needed
  795. RegionName = string.Empty,
  796. InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0),
  797. RegionFlags = OpenSim.Framework.RegionFlags.Hyperlink
  798. };
  799. }
  800. }
  801. }