HGEntityTransferModule.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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 = 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");
  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. protected override void OnNewClient(IClientAPI client)
  158. {
  159. client.OnTeleportHomeRequest += TriggerTeleportHome;
  160. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  161. client.OnConnectionClosed += new Action<IClientAPI>(OnConnectionClosed);
  162. }
  163. public override void RegionLoaded(Scene scene)
  164. {
  165. base.RegionLoaded(scene);
  166. if (m_Enabled)
  167. {
  168. m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService);
  169. m_UAS = scene.RequestModuleInterface<IUserAgentService>();
  170. if (m_UAS == null)
  171. m_UAS = new UserAgentServiceConnector(m_ThisHomeURI);
  172. }
  173. }
  174. public override void RemoveRegion(Scene scene)
  175. {
  176. base.RemoveRegion(scene);
  177. if (m_Enabled)
  178. {
  179. scene.UnregisterModuleInterface<IUserAgentVerificationModule>(this);
  180. m_incomingSceneObjectEngine.Stop();
  181. }
  182. }
  183. #endregion
  184. #region HG overrides of IEntityTransferModule
  185. protected override GridRegion GetFinalDestination(GridRegion region, UUID agentID, string agentHomeURI, out string message)
  186. {
  187. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, region.RegionID);
  188. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionName, flags);
  189. message = null;
  190. if ((flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  191. {
  192. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region is hyperlink");
  193. GridRegion real_destination = m_GatekeeperConnector.GetHyperlinkRegion(region, region.RegionID, agentID, agentHomeURI, out message);
  194. if (real_destination != null)
  195. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: GetFinalDestination: ServerURI={0}", real_destination.ServerURI);
  196. else
  197. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: GetHyperlinkRegion of region {0} from Gatekeeper {1} failed: {2}", region.RegionID, region.ServerURI, message);
  198. return real_destination;
  199. }
  200. return region;
  201. }
  202. protected override bool NeedsClosing(GridRegion reg, bool OutViewRange)
  203. {
  204. if (OutViewRange)
  205. return true;
  206. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  207. if (flags == -1 || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  208. return true;
  209. return false;
  210. }
  211. protected override void AgentHasMovedAway(ScenePresence sp, bool logout)
  212. {
  213. base.AgentHasMovedAway(sp, logout);
  214. if (logout)
  215. {
  216. // Log them out of this grid
  217. Scene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  218. string userId = Scene.UserManagementModule.GetUserUUI(sp.UUID);
  219. Scene.GridUserService.LoggedOut(userId, UUID.Zero, Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat);
  220. }
  221. }
  222. protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason, out bool logout)
  223. {
  224. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI);
  225. reason = string.Empty;
  226. logout = false;
  227. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  228. if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  229. {
  230. // this user is going to another grid
  231. // for local users, check if HyperGrid teleport is allowed, based on user level
  232. if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID) && sp.UserLevel < m_levelHGTeleport)
  233. {
  234. m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to HG teleport agent due to insufficient UserLevel.");
  235. reason = "Hypergrid teleport not allowed";
  236. return false;
  237. }
  238. if (agentCircuit.ServiceURLs.ContainsKey("HomeURI"))
  239. {
  240. string userAgentDriver = agentCircuit.ServiceURLs["HomeURI"].ToString();
  241. IUserAgentService connector;
  242. if (userAgentDriver.Equals(m_ThisHomeURI) && m_UAS != null)
  243. connector = m_UAS;
  244. else
  245. connector = new UserAgentServiceConnector(userAgentDriver);
  246. GridRegion source = new GridRegion(Scene.RegionInfo);
  247. source.RawServerURI = m_GatekeeperURI;
  248. bool success = connector.LoginAgentToGrid(source, agentCircuit, reg, finalDestination, false, out reason);
  249. logout = success; // flag for later logout from this grid; this is an HG TP
  250. if (success)
  251. Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
  252. return success;
  253. }
  254. else
  255. {
  256. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent does not have a HomeURI address");
  257. return false;
  258. }
  259. }
  260. return base.CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, ctx, out reason, out logout);
  261. }
  262. public override void TriggerTeleportHome(UUID id, IClientAPI client)
  263. {
  264. TeleportHome(id, client);
  265. }
  266. protected override bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason)
  267. {
  268. reason = "Please wear your grid's allowed appearance before teleporting to another grid";
  269. if (!m_RestrictAppearanceAbroad)
  270. return true;
  271. // The rest is only needed for controlling appearance
  272. int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  273. if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0)
  274. {
  275. // this user is going to another grid
  276. if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID))
  277. {
  278. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Checking generic appearance");
  279. // Check wearables
  280. for (int i = 0; i < sp.Appearance.Wearables.Length ; i++)
  281. {
  282. for (int j = 0; j < sp.Appearance.Wearables[i].Count; j++)
  283. {
  284. if (sp.Appearance.Wearables[i] == null)
  285. continue;
  286. bool found = false;
  287. foreach (AvatarAppearance a in ExportedAppearance)
  288. if (i < a.Wearables.Length && a.Wearables[i] != null)
  289. {
  290. found = true;
  291. break;
  292. }
  293. if (!found)
  294. {
  295. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i);
  296. return false;
  297. }
  298. found = false;
  299. foreach (AvatarAppearance a in ExportedAppearance)
  300. if (i < a.Wearables.Length && sp.Appearance.Wearables[i][j].AssetID == a.Wearables[i][j].AssetID)
  301. {
  302. found = true;
  303. break;
  304. }
  305. if (!found)
  306. {
  307. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i);
  308. return false;
  309. }
  310. }
  311. }
  312. // Check attachments
  313. foreach (AvatarAttachment att in sp.Appearance.GetAttachments())
  314. {
  315. bool found = false;
  316. foreach (AvatarAttachment att2 in m_Attachs)
  317. {
  318. if (att2.AssetID == att.AssetID)
  319. {
  320. found = true;
  321. break;
  322. }
  323. }
  324. if (!found)
  325. {
  326. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Attachment not allowed to go outside {0}", att.AttachPoint);
  327. return false;
  328. }
  329. }
  330. }
  331. }
  332. reason = string.Empty;
  333. return true;
  334. }
  335. //protected override bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agentData, ScenePresence sp)
  336. //{
  337. // int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID);
  338. // if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0)
  339. // {
  340. // // this user is going to another grid
  341. // if (m_RestrictAppearanceAbroad && Scene.UserManagementModule.IsLocalGridUser(agentData.AgentID))
  342. // {
  343. // // We need to strip the agent off its appearance
  344. // m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Sending generic appearance");
  345. // // Delete existing npc attachments
  346. // Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, false);
  347. // // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet since it doesn't transfer attachments
  348. // AvatarAppearance newAppearance = new AvatarAppearance(ExportedAppearance, true);
  349. // sp.Appearance = newAppearance;
  350. // // Rez needed npc attachments
  351. // Scene.AttachmentsModule.RezAttachments(sp);
  352. // IAvatarFactoryModule module = Scene.RequestModuleInterface<IAvatarFactoryModule>();
  353. // //module.SendAppearance(sp.UUID);
  354. // module.RequestRebake(sp, false);
  355. // Scene.AttachmentsModule.CopyAttachments(sp, agentData);
  356. // agentData.Appearance = sp.Appearance;
  357. // }
  358. // }
  359. // foreach (AvatarAttachment a in agentData.Appearance.GetAttachments())
  360. // m_log.DebugFormat("[XXX]: {0}-{1}", a.ItemID, a.AssetID);
  361. // return base.UpdateAgent(reg, finalDestination, agentData, sp);
  362. //}
  363. public override bool TeleportHome(UUID id, IClientAPI client)
  364. {
  365. m_log.DebugFormat(
  366. "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId);
  367. // Let's find out if this is a foreign user or a local user
  368. IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
  369. if (uMan != null && uMan.IsLocalGridUser(id))
  370. {
  371. // local grid user
  372. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: User is local");
  373. return base.TeleportHome(id, client);
  374. }
  375. // Foreign user wants to go home
  376. //
  377. AgentCircuitData aCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode);
  378. if (aCircuit == null || (aCircuit != null && !aCircuit.ServiceURLs.ContainsKey("HomeURI")))
  379. {
  380. client.SendTeleportFailed("Your information has been lost");
  381. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information");
  382. return false;
  383. }
  384. IUserAgentService userAgentService = new UserAgentServiceConnector(aCircuit.ServiceURLs["HomeURI"].ToString());
  385. Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
  386. GridRegion finalDestination = null;
  387. try
  388. {
  389. finalDestination = userAgentService.GetHomeRegion(aCircuit.AgentID, out position, out lookAt);
  390. }
  391. catch (Exception e)
  392. {
  393. m_log.Debug("[HG ENTITY TRANSFER MODULE]: GetHomeRegion call failed ", e);
  394. }
  395. if (finalDestination == null)
  396. {
  397. client.SendTeleportFailed("Your home region could not be found");
  398. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found");
  399. return false;
  400. }
  401. ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(client.AgentId);
  402. if (sp == null)
  403. {
  404. client.SendTeleportFailed("Internal error");
  405. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene where it is supposed to be");
  406. return false;
  407. }
  408. GridRegion homeGatekeeper = MakeRegion(aCircuit);
  409. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}",
  410. aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ServerURI, homeGatekeeper.RegionName);
  411. DoTeleport(sp, homeGatekeeper, finalDestination, position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  412. return true;
  413. }
  414. /// <summary>
  415. /// Tries to teleport agent to landmark.
  416. /// </summary>
  417. /// <param name="remoteClient"></param>
  418. /// <param name="regionHandle"></param>
  419. /// <param name="position"></param>
  420. public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  421. {
  422. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}",
  423. (lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position);
  424. if (lm.Gatekeeper == string.Empty)
  425. {
  426. base.RequestTeleportLandmark(remoteClient, lm);
  427. return;
  428. }
  429. GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  430. // Local region?
  431. if (info != null)
  432. {
  433. Scene.RequestTeleportLocation(
  434. remoteClient, info.RegionHandle, lm.Position,
  435. Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  436. }
  437. else
  438. {
  439. // Foreign region
  440. GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
  441. GridRegion gatekeeper = new GridRegion();
  442. gatekeeper.ServerURI = lm.Gatekeeper;
  443. string homeURI = Scene.GetAgentHomeURI(remoteClient.AgentId);
  444. string message;
  445. GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID), remoteClient.AgentId, homeURI, out message);
  446. if (finalDestination != null)
  447. {
  448. ScenePresence sp = Scene.GetScenePresence(remoteClient.AgentId);
  449. if (sp != null)
  450. {
  451. if (message != null)
  452. sp.ControllingClient.SendAgentAlertMessage(message, true);
  453. // Validate assorted conditions
  454. string reason = string.Empty;
  455. if (!ValidateGenericConditions(sp, gatekeeper, finalDestination, 0, out reason))
  456. {
  457. sp.ControllingClient.SendTeleportFailed(reason);
  458. return;
  459. }
  460. DoTeleport(
  461. sp, gatekeeper, finalDestination, lm.Position, Vector3.UnitX,
  462. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  463. }
  464. }
  465. else
  466. {
  467. remoteClient.SendTeleportFailed(message);
  468. }
  469. }
  470. }
  471. private void RemoveIncomingSceneObjectJobs(string commonIdToRemove)
  472. {
  473. List<JobEngine.Job> jobsToReinsert = new List<JobEngine.Job>();
  474. int jobsRemoved = 0;
  475. JobEngine.Job job;
  476. while ((job = m_incomingSceneObjectEngine.RemoveNextJob()) != null)
  477. {
  478. if (job.CommonId != commonIdToRemove)
  479. jobsToReinsert.Add(job);
  480. else
  481. jobsRemoved++;
  482. }
  483. m_log.DebugFormat(
  484. "[HG ENTITY TRANSFER]: Removing {0} jobs with common ID {1} and reinserting {2} other jobs",
  485. jobsRemoved, commonIdToRemove, jobsToReinsert.Count);
  486. if (jobsToReinsert.Count > 0)
  487. {
  488. foreach (JobEngine.Job jobToReinsert in jobsToReinsert)
  489. m_incomingSceneObjectEngine.QueueJob(jobToReinsert);
  490. }
  491. }
  492. public override bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition)
  493. {
  494. // FIXME: We must make it so that we can use SOG.IsAttachment here. At the moment it is always null!
  495. if (!so.IsAttachmentCheckFull())
  496. return base.HandleIncomingSceneObject(so, newPosition);
  497. // Equally, we can't use so.AttachedAvatar here.
  498. if (so.OwnerID == UUID.Zero || Scene.UserManagementModule.IsLocalGridUser(so.OwnerID))
  499. return base.HandleIncomingSceneObject(so, newPosition);
  500. // foreign user
  501. AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(so.OwnerID);
  502. if (aCircuit != null)
  503. {
  504. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) == 0)
  505. {
  506. // We have already pulled the necessary attachments from the source grid.
  507. base.HandleIncomingSceneObject(so, newPosition);
  508. }
  509. else
  510. {
  511. if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
  512. {
  513. m_incomingSceneObjectEngine.QueueJob(
  514. string.Format("HG UUID Gather for attachment {0} for {1}", so.Name, aCircuit.Name),
  515. () =>
  516. {
  517. string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
  518. // m_log.DebugFormat(
  519. // "[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset service {2}",
  520. // so.Name, so.AttachedAvatar, url);
  521. IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
  522. HGUuidGatherer uuidGatherer
  523. = new HGUuidGatherer(Scene.AssetService, url, ids);
  524. uuidGatherer.AddForInspection(so);
  525. while (!uuidGatherer.Complete)
  526. {
  527. int tickStart = Util.EnvironmentTickCount();
  528. UUID? nextUuid = uuidGatherer.NextUuidToInspect;
  529. uuidGatherer.GatherNext();
  530. // m_log.DebugFormat(
  531. // "[HG ENTITY TRANSFER]: Gathered attachment asset uuid {0} for object {1} for HG user {2} took {3} ms with asset service {4}",
  532. // nextUuid, so.Name, so.OwnerID, Util.EnvironmentTickCountSubtract(tickStart), url);
  533. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  534. if (ticksElapsed > 30000)
  535. {
  536. m_log.WarnFormat(
  537. "[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)",
  538. so.OwnerID, so.Name, url, ticksElapsed, 30000);
  539. RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
  540. return;
  541. }
  542. }
  543. // m_log.DebugFormat(
  544. // "[HG ENTITY TRANSFER]: Fetching {0} assets for attachment {1} for HG user {2} with asset service {3}",
  545. // ids.Count, so.Name, so.OwnerID, url);
  546. foreach (KeyValuePair<UUID, sbyte> kvp in ids)
  547. {
  548. int tickStart = Util.EnvironmentTickCount();
  549. uuidGatherer.FetchAsset(kvp.Key);
  550. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  551. if (ticksElapsed > 30000)
  552. {
  553. m_log.WarnFormat(
  554. "[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)",
  555. so.OwnerID, kvp.Key, url, ticksElapsed, 30000);
  556. RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
  557. return;
  558. }
  559. }
  560. base.HandleIncomingSceneObject(so, newPosition);
  561. // m_log.DebugFormat(
  562. // "[HG ENTITY TRANSFER MODULE]: Completed incoming attachment {0} for HG user {1} with asset server {2}",
  563. // so.Name, so.OwnerID, url);
  564. },
  565. so.OwnerID.ToString());
  566. }
  567. }
  568. }
  569. return true;
  570. }
  571. #endregion
  572. #region IUserAgentVerificationModule
  573. public bool VerifyClient(AgentCircuitData aCircuit, string token)
  574. {
  575. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  576. {
  577. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  578. IUserAgentService security = new UserAgentServiceConnector(url);
  579. return security.VerifyClient(aCircuit.SessionID, token);
  580. }
  581. else
  582. {
  583. m_log.DebugFormat(
  584. "[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!",
  585. aCircuit.firstname, aCircuit.lastname);
  586. }
  587. return false;
  588. }
  589. void OnConnectionClosed(IClientAPI obj)
  590. {
  591. if (obj.SceneAgent.IsChildAgent)
  592. return;
  593. // Let's find out if this is a foreign user or a local user
  594. IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
  595. // UserAccount account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, obj.AgentId);
  596. if (uMan != null && uMan.IsLocalGridUser(obj.AgentId))
  597. {
  598. // local grid user
  599. m_UAS.LogoutAgent(obj.AgentId, obj.SessionId);
  600. return;
  601. }
  602. AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode);
  603. if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  604. {
  605. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  606. IUserAgentService security = new UserAgentServiceConnector(url);
  607. security.LogoutAgent(obj.AgentId, obj.SessionId);
  608. //m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
  609. }
  610. else
  611. {
  612. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId);
  613. }
  614. }
  615. #endregion
  616. private GridRegion MakeRegion(AgentCircuitData aCircuit)
  617. {
  618. GridRegion region = new GridRegion();
  619. Uri uri = null;
  620. if (!aCircuit.ServiceURLs.ContainsKey("HomeURI") ||
  621. (aCircuit.ServiceURLs.ContainsKey("HomeURI") && !Uri.TryCreate(aCircuit.ServiceURLs["HomeURI"].ToString(), UriKind.Absolute, out uri)))
  622. return null;
  623. region.ExternalHostName = uri.Host;
  624. region.HttpPort = (uint)uri.Port;
  625. region.ServerURI = aCircuit.ServiceURLs["HomeURI"].ToString();
  626. region.RegionName = string.Empty;
  627. region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0);
  628. return region;
  629. }
  630. }
  631. }