HGEntityTransferModule.cs 35 KB

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