HGEntityTransferModule.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. 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.GodController.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. // Let's find out if this is a foreign user or a local user
  366. IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
  367. if (uMan != null && uMan.IsLocalGridUser(id))
  368. {
  369. // local grid user
  370. return base.TeleportHome(id, client);
  371. }
  372. bool notsame = false;
  373. if (client == null)
  374. {
  375. m_log.DebugFormat(
  376. "[HG ENTITY TRANSFER MODULE]: Request to teleport {0} home", id);
  377. }
  378. else
  379. {
  380. if (id == client.AgentId)
  381. {
  382. m_log.DebugFormat(
  383. "[HG ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, id);
  384. }
  385. else
  386. {
  387. notsame = true;
  388. m_log.DebugFormat(
  389. "[HG ENTITY TRANSFER MODULE]: Request to teleport {0} home by {1} {2}", id, client.Name, client.AgentId);
  390. }
  391. }
  392. ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(id);
  393. if (sp == null || sp.IsDeleted || sp.IsChildAgent || sp.ControllingClient == null || !sp.ControllingClient.IsActive)
  394. {
  395. if (notsame)
  396. client.SendAlertMessage("TeleportHome: Agent not found in the scene");
  397. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene");
  398. return false;
  399. }
  400. IClientAPI targetClient = sp.ControllingClient;
  401. if (sp.IsInTransit)
  402. {
  403. if (notsame)
  404. client.SendAlertMessage("TeleportHome: Agent already processing a teleport");
  405. targetClient.SendTeleportFailed("Already processing a teleport");
  406. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent still in teleport");
  407. return false;
  408. }
  409. // Foreign user wants to go home
  410. //
  411. AgentCircuitData aCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(targetClient.CircuitCode);
  412. if (aCircuit == null)
  413. {
  414. if (notsame)
  415. client.SendAlertMessage("TeleportHome: Agent information not found");
  416. targetClient.SendTeleportFailed("Home information not found");
  417. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information");
  418. return false;
  419. }
  420. if (!aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  421. {
  422. if (notsame)
  423. client.SendAlertMessage("TeleportHome: Agent home not set");
  424. targetClient.SendTeleportFailed("Home not set");
  425. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent home not set");
  426. return false;
  427. }
  428. string homeURI = aCircuit.ServiceURLs["HomeURI"].ToString();
  429. IUserAgentService userAgentService = new UserAgentServiceConnector(homeURI);
  430. Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
  431. GridRegion finalDestination = null;
  432. try
  433. {
  434. finalDestination = userAgentService.GetHomeRegion(id, out position, out lookAt);
  435. }
  436. catch (Exception e)
  437. {
  438. m_log.Debug("[HG ENTITY TRANSFER MODULE]: GetHomeRegion call failed ", e);
  439. }
  440. if (finalDestination == null)
  441. {
  442. if (notsame)
  443. client.SendAlertMessage("TeleportHome: Agent Home region not found");
  444. targetClient.SendTeleportFailed("Home region not found");
  445. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found");
  446. return false;
  447. }
  448. GridRegion homeGatekeeper = MakeGateKeeperRegion(homeURI);
  449. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}",
  450. aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ServerURI, homeGatekeeper.RegionName);
  451. DoTeleport(sp, homeGatekeeper, finalDestination, position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  452. return true;
  453. }
  454. /// <summary>
  455. /// Tries to teleport agent to landmark.
  456. /// </summary>
  457. /// <param name="remoteClient"></param>
  458. /// <param name="regionHandle"></param>
  459. /// <param name="position"></param>
  460. public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  461. {
  462. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}",
  463. (lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position);
  464. if (lm.Gatekeeper == string.Empty)
  465. {
  466. base.RequestTeleportLandmark(remoteClient, lm);
  467. return;
  468. }
  469. GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  470. // Local region?
  471. if (info != null)
  472. {
  473. Scene.RequestTeleportLocation(
  474. remoteClient, info.RegionHandle, lm.Position,
  475. Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  476. }
  477. else
  478. {
  479. // Foreign region
  480. GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
  481. GridRegion gatekeeper = MakeGateKeeperRegion(lm.Gatekeeper);
  482. if (gatekeeper == null)
  483. {
  484. remoteClient.SendTeleportFailed("Could not parse landmark destiny URI");
  485. return;
  486. }
  487. string homeURI = Scene.GetAgentHomeURI(remoteClient.AgentId);
  488. string message;
  489. GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID), remoteClient.AgentId, homeURI, out message);
  490. if (finalDestination != null)
  491. {
  492. ScenePresence sp = Scene.GetScenePresence(remoteClient.AgentId);
  493. if (sp != null)
  494. {
  495. if (message != null)
  496. sp.ControllingClient.SendAgentAlertMessage(message, true);
  497. // Validate assorted conditions
  498. string reason = string.Empty;
  499. if (!ValidateGenericConditions(sp, gatekeeper, finalDestination, 0, out reason))
  500. {
  501. sp.ControllingClient.SendTeleportFailed(reason);
  502. return;
  503. }
  504. DoTeleport(
  505. sp, gatekeeper, finalDestination, lm.Position, Vector3.UnitX,
  506. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  507. }
  508. }
  509. else
  510. {
  511. remoteClient.SendTeleportFailed(message);
  512. }
  513. }
  514. }
  515. private void RemoveIncomingSceneObjectJobs(string commonIdToRemove)
  516. {
  517. List<JobEngine.Job> jobsToReinsert = new List<JobEngine.Job>();
  518. int jobsRemoved = 0;
  519. JobEngine.Job job;
  520. while ((job = m_incomingSceneObjectEngine.RemoveNextJob()) != null)
  521. {
  522. if (job.CommonId != commonIdToRemove)
  523. jobsToReinsert.Add(job);
  524. else
  525. jobsRemoved++;
  526. }
  527. m_log.DebugFormat(
  528. "[HG ENTITY TRANSFER]: Removing {0} jobs with common ID {1} and reinserting {2} other jobs",
  529. jobsRemoved, commonIdToRemove, jobsToReinsert.Count);
  530. if (jobsToReinsert.Count > 0)
  531. {
  532. foreach (JobEngine.Job jobToReinsert in jobsToReinsert)
  533. m_incomingSceneObjectEngine.QueueJob(jobToReinsert);
  534. }
  535. }
  536. public override bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition)
  537. {
  538. // FIXME: We must make it so that we can use SOG.IsAttachment here. At the moment it is always null!
  539. if (!so.IsAttachmentCheckFull())
  540. return base.HandleIncomingSceneObject(so, newPosition);
  541. // Equally, we can't use so.AttachedAvatar here.
  542. if (so.OwnerID == UUID.Zero || Scene.UserManagementModule.IsLocalGridUser(so.OwnerID))
  543. return base.HandleIncomingSceneObject(so, newPosition);
  544. // foreign user
  545. AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(so.OwnerID);
  546. if (aCircuit != null)
  547. {
  548. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) == 0)
  549. {
  550. // We have already pulled the necessary attachments from the source grid.
  551. base.HandleIncomingSceneObject(so, newPosition);
  552. }
  553. else
  554. {
  555. if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
  556. {
  557. m_incomingSceneObjectEngine.QueueJob(
  558. string.Format("HG UUID Gather for attachment {0} for {1}", so.Name, aCircuit.Name),
  559. () =>
  560. {
  561. string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
  562. // m_log.DebugFormat(
  563. // "[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset service {2}",
  564. // so.Name, so.AttachedAvatar, url);
  565. IDictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
  566. HGUuidGatherer uuidGatherer
  567. = new HGUuidGatherer(Scene.AssetService, url, ids);
  568. uuidGatherer.AddForInspection(so);
  569. while (!uuidGatherer.Complete)
  570. {
  571. int tickStart = Util.EnvironmentTickCount();
  572. UUID? nextUuid = uuidGatherer.NextUuidToInspect;
  573. uuidGatherer.GatherNext();
  574. // m_log.DebugFormat(
  575. // "[HG ENTITY TRANSFER]: Gathered attachment asset uuid {0} for object {1} for HG user {2} took {3} ms with asset service {4}",
  576. // nextUuid, so.Name, so.OwnerID, Util.EnvironmentTickCountSubtract(tickStart), url);
  577. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  578. if (ticksElapsed > 30000)
  579. {
  580. m_log.WarnFormat(
  581. "[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)",
  582. so.OwnerID, so.Name, url, ticksElapsed, 30000);
  583. RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
  584. return;
  585. }
  586. }
  587. // m_log.DebugFormat(
  588. // "[HG ENTITY TRANSFER]: Fetching {0} assets for attachment {1} for HG user {2} with asset service {3}",
  589. // ids.Count, so.Name, so.OwnerID, url);
  590. foreach (KeyValuePair<UUID, sbyte> kvp in ids)
  591. {
  592. int tickStart = Util.EnvironmentTickCount();
  593. uuidGatherer.FetchAsset(kvp.Key);
  594. int ticksElapsed = Util.EnvironmentTickCountSubtract(tickStart);
  595. if (ticksElapsed > 30000)
  596. {
  597. m_log.WarnFormat(
  598. "[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)",
  599. so.OwnerID, kvp.Key, url, ticksElapsed, 30000);
  600. RemoveIncomingSceneObjectJobs(so.OwnerID.ToString());
  601. return;
  602. }
  603. }
  604. base.HandleIncomingSceneObject(so, newPosition);
  605. // m_log.DebugFormat(
  606. // "[HG ENTITY TRANSFER MODULE]: Completed incoming attachment {0} for HG user {1} with asset server {2}",
  607. // so.Name, so.OwnerID, url);
  608. },
  609. so.OwnerID.ToString());
  610. }
  611. }
  612. }
  613. return true;
  614. }
  615. #endregion
  616. #region IUserAgentVerificationModule
  617. public bool VerifyClient(AgentCircuitData aCircuit, string token)
  618. {
  619. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  620. {
  621. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  622. IUserAgentService security = new UserAgentServiceConnector(url);
  623. return security.VerifyClient(aCircuit.SessionID, token);
  624. }
  625. else
  626. {
  627. m_log.DebugFormat(
  628. "[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!",
  629. aCircuit.firstname, aCircuit.lastname);
  630. }
  631. return false;
  632. }
  633. void OnConnectionClosed(IClientAPI obj)
  634. {
  635. if (obj.SceneAgent.IsChildAgent)
  636. return;
  637. // Let's find out if this is a foreign user or a local user
  638. IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>();
  639. // UserAccount account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, obj.AgentId);
  640. if (uMan != null && uMan.IsLocalGridUser(obj.AgentId))
  641. {
  642. // local grid user
  643. m_UAS.LogoutAgent(obj.AgentId, obj.SessionId);
  644. return;
  645. }
  646. AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode);
  647. if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  648. {
  649. string url = aCircuit.ServiceURLs["HomeURI"].ToString();
  650. IUserAgentService security = new UserAgentServiceConnector(url);
  651. security.LogoutAgent(obj.AgentId, obj.SessionId);
  652. //m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
  653. }
  654. else
  655. {
  656. m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId);
  657. }
  658. }
  659. #endregion
  660. private GridRegion MakeGateKeeperRegion(string wantedURI)
  661. {
  662. Uri uri;
  663. if(!Uri.TryCreate(wantedURI, UriKind.Absolute, out uri))
  664. return null;
  665. GridRegion region = new GridRegion();
  666. region.ExternalHostName = uri.Host;
  667. region.HttpPort = (uint)uri.Port;
  668. region.ServerURI = wantedURI; //uri.AbsoluteUri for some reason default ports are needed
  669. region.RegionName = string.Empty;
  670. region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0);
  671. region.RegionFlags = OpenSim.Framework.RegionFlags.Hyperlink;
  672. return region;
  673. }
  674. }
  675. }