HGEntityTransferModule.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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 GridRegion = OpenSim.Services.Interfaces.GridRegion;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. using Mono.Addins;
  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 = new InventoryItemBase(att.ItemID, account.PrincipalID);
  86. item = Scene.InventoryService.GetItem(item);
  87. if (item != null)
  88. a.SetAttachment(att.AttachPoint, att.ItemID, item.AssetID);
  89. else
  90. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to retrieve item {0} from inventory {1}", att.ItemID, name);
  91. }
  92. m_ExportedAppearances.Add(a);
  93. m_Attachs.AddRange(a.GetAttachments());
  94. }
  95. return m_ExportedAppearances;
  96. }
  97. }
  98. /// <summary>
  99. /// Used for processing analysis of incoming attachments in a controlled fashion.
  100. /// </summary>
  101. private JobEngine m_incomingSceneObjectEngine;
  102. #region ISharedRegionModule
  103. public override string Name
  104. {
  105. get { return "HGEntityTransferModule"; }
  106. }
  107. public override void Initialise(IConfigSource source)
  108. {
  109. IConfig moduleConfig = source.Configs["Modules"];
  110. if (moduleConfig != null)
  111. {
  112. string name = moduleConfig.GetString("EntityTransferModule", "");
  113. if (name == Name)
  114. {
  115. IConfig transferConfig = source.Configs["EntityTransfer"];
  116. if (transferConfig != null)
  117. {
  118. m_levelHGTeleport = transferConfig.GetInt("LevelHGTeleport", 0);
  119. m_RestrictAppearanceAbroad = transferConfig.GetBoolean("RestrictAppearanceAbroad", false);
  120. if (m_RestrictAppearanceAbroad)
  121. {
  122. m_AccountName = transferConfig.GetString("AccountForAppearance", string.Empty);
  123. if (m_AccountName == string.Empty)
  124. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is on, but no account has been given for avatar appearance!");
  125. }
  126. }
  127. InitialiseCommon(source);
  128. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: {0} enabled.", Name);
  129. }
  130. }
  131. }
  132. public override void AddRegion(Scene scene)
  133. {
  134. base.AddRegion(scene);
  135. if (m_Enabled)
  136. {
  137. scene.RegisterModuleInterface<IUserAgentVerificationModule>(this);
  138. //scene.EventManager.OnIncomingSceneObject += OnIncomingSceneObject;
  139. m_incomingSceneObjectEngine
  140. = new JobEngine(
  141. string.Format("HG Incoming Scene Object Engine ({0})", scene.Name),
  142. "HG INCOMING SCENE OBJECT ENGINE");
  143. StatsManager.RegisterStat(
  144. new Stat(
  145. "HGIncomingAttachmentsWaiting",
  146. "Number of incoming attachments waiting for processing.",
  147. "",
  148. "",
  149. "entitytransfer",
  150. Name,
  151. StatType.Pull,
  152. MeasuresOfInterest.None,
  153. stat => stat.Value = m_incomingSceneObjectEngine.JobsWaiting,
  154. StatVerbosity.Debug));
  155. m_incomingSceneObjectEngine.Start();
  156. }
  157. }
  158. protected override void OnNewClient(IClientAPI client)
  159. {
  160. client.OnTeleportHomeRequest += TriggerTeleportHome;
  161. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  162. client.OnConnectionClosed += new Action<IClientAPI>(OnConnectionClosed);
  163. }
  164. public override void RegionLoaded(Scene scene)
  165. {
  166. base.RegionLoaded(scene);
  167. if (m_Enabled)
  168. {
  169. m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService);
  170. m_UAS = scene.RequestModuleInterface<IUserAgentService>();
  171. if (m_UAS == null)
  172. m_UAS = new UserAgentServiceConnector(m_ThisHomeURI);
  173. }
  174. }
  175. public override void RemoveRegion(Scene scene)
  176. {
  177. base.RemoveRegion(scene);
  178. if (m_Enabled)
  179. {
  180. scene.UnregisterModuleInterface<IUserAgentVerificationModule>(this);
  181. m_incomingSceneObjectEngine.Stop();
  182. }
  183. }
  184. #endregion
  185. #region HG overrides of IEntityTransferModule
  186. protected override GridRegion GetFinalDestination(GridRegion region, UUID agentID, string agentHomeURI, out string message)
  187. {
  188. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, region.RegionID);
  189. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionName, flags);
  190. message = null;
  191. if ((flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  192. {
  193. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region is hyperlink");
  194. GridRegion real_destination = m_GatekeeperConnector.GetHyperlinkRegion(region, region.RegionID, agentID, agentHomeURI, out message);
  195. if (real_destination != null)
  196. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: GetFinalDestination: ServerURI={0}", real_destination.ServerURI);
  197. else
  198. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: GetHyperlinkRegion of region {0} from Gatekeeper {1} failed: {2}", region.RegionID, region.ServerURI, message);
  199. return real_destination;
  200. }
  201. return region;
  202. }
  203. protected override bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
  204. {
  205. if (base.NeedsClosing(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
  206. return true;
  207. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  208. if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  209. return true;
  210. return false;
  211. }
  212. protected override void AgentHasMovedAway(ScenePresence sp, bool logout)
  213. {
  214. base.AgentHasMovedAway(sp, logout);
  215. if (logout)
  216. {
  217. // Log them out of this grid
  218. Scene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  219. string userId = Scene.UserManagementModule.GetUserUUI(sp.UUID);
  220. Scene.GridUserService.LoggedOut(userId, UUID.Zero, Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat);
  221. }
  222. }
  223. protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout)
  224. {
  225. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI);
  226. reason = string.Empty;
  227. logout = false;
  228. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  229. if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  230. {
  231. // this user is going to another grid
  232. // for local users, check if HyperGrid teleport is allowed, based on user level
  233. if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID) && sp.UserLevel < m_levelHGTeleport)
  234. {
  235. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to HG teleport agent due to insufficient UserLevel.");
  236. reason = "Hypergrid teleport not allowed";
  237. return false;
  238. }
  239. if (agentCircuit.ServiceURLs.ContainsKey("HomeURI"))
  240. {
  241. string userAgentDriver = agentCircuit.ServiceURLs["HomeURI"].ToString();
  242. IUserAgentService connector;
  243. if (userAgentDriver.Equals(m_ThisHomeURI) && m_UAS != null)
  244. connector = m_UAS;
  245. else
  246. connector = new UserAgentServiceConnector(userAgentDriver);
  247. GridRegion source = new GridRegion(Scene.RegionInfo);
  248. source.RawServerURI = m_GatekeeperURI;
  249. bool success = connector.LoginAgentToGrid(source, agentCircuit, reg, finalDestination, false, out reason);
  250. logout = success; // flag for later logout from this grid; this is an HG TP
  251. if (success)
  252. Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
  253. return success;
  254. }
  255. else
  256. {
  257. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent does not have a HomeURI address");
  258. return false;
  259. }
  260. }
  261. return base.CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout);
  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 = Scene.GridService.GetRegionFlags(Scene.RegionInfo.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 (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 < AvatarWearable.MAX_WEARABLES; 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 (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 (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 void TriggerTeleportHome(UUID id, IClientAPI client)
  361. {
  362. TeleportHome(id, client);
  363. }
  364. public override bool TeleportHome(UUID id, IClientAPI client)
  365. {
  366. m_log.DebugFormat(
  367. "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId);
  368. // Let's find out if this is a foreign user or a local user
  369. IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
  370. if (uMan != null && uMan.IsLocalGridUser(id))
  371. {
  372. // local grid user
  373. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: User is local");
  374. return base.TeleportHome(id, client);
  375. }
  376. // Foreign user wants to go home
  377. //
  378. AgentCircuitData aCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode);
  379. if (aCircuit == null || (aCircuit != null && !aCircuit.ServiceURLs.ContainsKey("HomeURI")))
  380. {
  381. client.SendTeleportFailed("Your information has been lost");
  382. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information");
  383. return false;
  384. }
  385. IUserAgentService userAgentService = new UserAgentServiceConnector(aCircuit.ServiceURLs["HomeURI"].ToString());
  386. Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
  387. GridRegion finalDestination = null;
  388. try
  389. {
  390. finalDestination = userAgentService.GetHomeRegion(aCircuit.AgentID, out position, out lookAt);
  391. }
  392. catch (Exception e)
  393. {
  394. m_log.Debug("[HG ENTITY TRANSFER MODULE]: GetHomeRegion call failed ", e);
  395. }
  396. if (finalDestination == null)
  397. {
  398. client.SendTeleportFailed("Your home region could not be found");
  399. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found");
  400. return false;
  401. }
  402. ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(client.AgentId);
  403. if (sp == null)
  404. {
  405. client.SendTeleportFailed("Internal error");
  406. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene where it is supposed to be");
  407. return false;
  408. }
  409. GridRegion homeGatekeeper = MakeRegion(aCircuit);
  410. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}",
  411. aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ServerURI, homeGatekeeper.RegionName);
  412. DoTeleport(
  413. sp, homeGatekeeper, finalDestination,
  414. position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  415. return true;
  416. }
  417. /// <summary>
  418. /// Tries to teleport agent to landmark.
  419. /// </summary>
  420. /// <param name="remoteClient"></param>
  421. /// <param name="regionHandle"></param>
  422. /// <param name="position"></param>
  423. public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  424. {
  425. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}",
  426. (lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position);
  427. if (lm.Gatekeeper == string.Empty)
  428. {
  429. base.RequestTeleportLandmark(remoteClient, lm);
  430. return;
  431. }
  432. GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  433. // Local region?
  434. if (info != null)
  435. {
  436. Scene.RequestTeleportLocation(
  437. remoteClient, info.RegionHandle, lm.Position,
  438. Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  439. }
  440. else
  441. {
  442. // Foreign region
  443. GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
  444. GridRegion gatekeeper = new GridRegion();
  445. gatekeeper.ServerURI = lm.Gatekeeper;
  446. string homeURI = Scene.GetAgentHomeURI(remoteClient.AgentId);
  447. string message;
  448. GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID), remoteClient.AgentId, homeURI, out message);
  449. if (finalDestination != null)
  450. {
  451. ScenePresence sp = Scene.GetScenePresence(remoteClient.AgentId);
  452. if (sp != null)
  453. {
  454. if (message != null)
  455. sp.ControllingClient.SendAgentAlertMessage(message, true);
  456. // Validate assorted conditions
  457. string reason = string.Empty;
  458. if (!ValidateGenericConditions(sp, gatekeeper, finalDestination, 0, out reason))
  459. {
  460. sp.ControllingClient.SendTeleportFailed(reason);
  461. return;
  462. }
  463. DoTeleport(
  464. sp, gatekeeper, finalDestination, lm.Position, Vector3.UnitX,
  465. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  466. }
  467. }
  468. else
  469. {
  470. remoteClient.SendTeleportFailed(message);
  471. }
  472. }
  473. }
  474. private void RemoveIncomingSceneObjectJobs(string commonIdToRemove)
  475. {
  476. List<JobEngine.Job> jobsToReinsert = new List<JobEngine.Job>();
  477. int jobsRemoved = 0;
  478. JobEngine.Job job;
  479. while ((job = m_incomingSceneObjectEngine.RemoveNextJob()) != null)
  480. {
  481. if (job.CommonId != commonIdToRemove)
  482. jobsToReinsert.Add(job);
  483. else
  484. jobsRemoved++;
  485. }
  486. m_log.DebugFormat(
  487. "[HG ENTITY TRANSFER]: Removing {0} jobs with common ID {1} and reinserting {2} other jobs",
  488. jobsRemoved, commonIdToRemove, jobsToReinsert.Count);
  489. if (jobsToReinsert.Count > 0)
  490. {
  491. foreach (JobEngine.Job jobToReinsert in jobsToReinsert)
  492. m_incomingSceneObjectEngine.QueueJob(jobToReinsert);
  493. }
  494. }
  495. public override bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition)
  496. {
  497. // FIXME: We must make it so that we can use SOG.IsAttachment here. At the moment it is always null!
  498. if (!so.IsAttachmentCheckFull())
  499. return base.HandleIncomingSceneObject(so, newPosition);
  500. // Equally, we can't use so.AttachedAvatar here.
  501. if (so.OwnerID == UUID.Zero || Scene.UserManagementModule.IsLocalGridUser(so.OwnerID))
  502. return base.HandleIncomingSceneObject(so, newPosition);
  503. // foreign user
  504. AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(so.OwnerID);
  505. if (aCircuit != null)
  506. {
  507. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) == 0)
  508. {
  509. // We have already pulled the necessary attachments from the source grid.
  510. base.HandleIncomingSceneObject(so, newPosition);
  511. }
  512. else
  513. {
  514. if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
  515. {
  516. m_incomingSceneObjectEngine.QueueJob(
  517. string.Format("HG UUID Gather for attachment {0} for {1}", so.Name, aCircuit.Name),
  518. () =>
  519. {
  520. string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
  521. // m_log.DebugFormat(
  522. // "[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset service {2}",
  523. // so.Name, so.AttachedAvatar, url);
  524. IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
  525. HGUuidGatherer uuidGatherer
  526. = new HGUuidGatherer(Scene.AssetService, url, ids);
  527. uuidGatherer.AddForInspection(so);
  528. while (!uuidGatherer.Complete)
  529. {
  530. int tickStart = Util.EnvironmentTickCount();
  531. UUID? nextUuid = uuidGatherer.NextUuidToInspect;
  532. uuidGatherer.GatherNext();
  533. // m_log.DebugFormat(
  534. // "[HG ENTITY TRANSFER]: Gathered attachment asset uuid {0} for object {1} for HG user {2} took {3} ms with asset service {4}",
  535. // nextUuid, so.Name, so.OwnerID, Util.EnvironmentTickCountSubtract(tickStart), url);
  536. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  537. if (ticksElapsed > 30000)
  538. {
  539. m_log.WarnFormat(
  540. "[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)",
  541. so.OwnerID, so.Name, url, ticksElapsed, 30000);
  542. RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
  543. return;
  544. }
  545. }
  546. // m_log.DebugFormat(
  547. // "[HG ENTITY TRANSFER]: Fetching {0} assets for attachment {1} for HG user {2} with asset service {3}",
  548. // ids.Count, so.Name, so.OwnerID, url);
  549. foreach (KeyValuePair<UUID, sbyte> kvp in ids)
  550. {
  551. int tickStart = Util.EnvironmentTickCount();
  552. uuidGatherer.FetchAsset(kvp.Key);
  553. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  554. if (ticksElapsed > 30000)
  555. {
  556. m_log.WarnFormat(
  557. "[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)",
  558. so.OwnerID, kvp.Key, url, ticksElapsed, 30000);
  559. RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
  560. return;
  561. }
  562. }
  563. base.HandleIncomingSceneObject(so, newPosition);
  564. // m_log.DebugFormat(
  565. // "[HG ENTITY TRANSFER MODULE]: Completed incoming attachment {0} for HG user {1} with asset server {2}",
  566. // so.Name, so.OwnerID, url);
  567. },
  568. so.OwnerID.ToString());
  569. }
  570. }
  571. }
  572. return true;
  573. }
  574. #endregion
  575. #region IUserAgentVerificationModule
  576. public bool VerifyClient(AgentCircuitData aCircuit, string token)
  577. {
  578. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  579. {
  580. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  581. IUserAgentService security = new UserAgentServiceConnector(url);
  582. return security.VerifyClient(aCircuit.SessionID, token);
  583. }
  584. else
  585. {
  586. m_log.DebugFormat(
  587. "[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!",
  588. aCircuit.firstname, aCircuit.lastname);
  589. }
  590. return false;
  591. }
  592. void OnConnectionClosed(IClientAPI obj)
  593. {
  594. if (obj.SceneAgent.IsChildAgent)
  595. return;
  596. // Let's find out if this is a foreign user or a local user
  597. IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
  598. // UserAccount account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, obj.AgentId);
  599. if (uMan != null && uMan.IsLocalGridUser(obj.AgentId))
  600. {
  601. // local grid user
  602. m_UAS.LogoutAgent(obj.AgentId, obj.SessionId);
  603. return;
  604. }
  605. AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode);
  606. if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  607. {
  608. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  609. IUserAgentService security = new UserAgentServiceConnector(url);
  610. security.LogoutAgent(obj.AgentId, obj.SessionId);
  611. //m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
  612. }
  613. else
  614. {
  615. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId);
  616. }
  617. }
  618. #endregion
  619. private GridRegion MakeRegion(AgentCircuitData aCircuit)
  620. {
  621. GridRegion region = new GridRegion();
  622. Uri uri = null;
  623. if (!aCircuit.ServiceURLs.ContainsKey("HomeURI") ||
  624. (aCircuit.ServiceURLs.ContainsKey("HomeURI") && !Uri.TryCreate(aCircuit.ServiceURLs["HomeURI"].ToString(), UriKind.Absolute, out uri)))
  625. return null;
  626. region.ExternalHostName = uri.Host;
  627. region.HttpPort = (uint)uri.Port;
  628. region.ServerURI = aCircuit.ServiceURLs["HomeURI"].ToString();
  629. region.RegionName = string.Empty;
  630. region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0);
  631. return region;
  632. }
  633. }
  634. }