/**
         * Agent-related communications
         */
        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out CreateAgentResponse response)
        {
            response = new CreateAgentResponse();
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);
            if (destination == null || Scene == null)
            {
                response.Reason = "Given destination was null";
                response.Success = false;
                return false;
            }

            if (Scene.RegionInfo.RegionID != destination.RegionID)
            {
                response.Reason = "Did not find region " + destination.RegionName;;
                response.Success = false;
                return false;
            }
            IEntityTransferModule transferModule = Scene.RequestModuleInterface<IEntityTransferModule>();
            if (transferModule != null)
                return transferModule.NewUserConnection(Scene, aCircuit, teleportFlags, out response);

            response.Reason = "Did not find region " + destination.RegionName;
            response.Success = false;
            return false;
        }
 public bool CloseAgent(GridRegion destination, UUID agentID)
 {
     CloseAgentRequest request = new CloseAgentRequest();
     request.AgentID = agentID;
     request.Destination = destination;
     m_syncMessagePoster.Post(destination.ServerURI, request.ToOSD());
     return true;
 }
Пример #3
0
 /// <summary>
 ///     Define equality as two regions having the same, non-zero UUID.
 /// </summary>
 public bool Equals(GridRegion region)
 {
     if (region == null)
     {
         return(false);
     }
     // Return true if the non-zero UUIDs are equal:
     return((RegionID != UUID.Zero) && RegionID.Equals(region.RegionID));
 }
        public bool CloseAgent(GridRegion destination, UUID agentID)
        {
            CloseAgentRequest request = new CloseAgentRequest();

            request.AgentID     = agentID;
            request.Destination = destination;
            m_syncMessagePoster.Post(destination.ServerURI, request.ToOSD());
            return(true);
        }
        public bool UpdateAgent(GridRegion destination, AgentPosition data)
        {
            if (m_blackListedRegions.ContainsKey(destination.ServerURI))
            {
                //Check against time
                if (m_blackListedRegions[destination.ServerURI] > 3 &&
                    Util.EnvironmentTickCountSubtract(m_blackListedRegions[destination.ServerURI]) > 0)
                {
                    MainConsole.Instance.Warn("[SimServiceConnector]: Blacklisted region " + destination.RegionName +
                                              " requested");
                    //Still blacklisted
                    return(false);
                }
            }

            UpdateAgentPositionRequest request = new UpdateAgentPositionRequest();

            request.Update      = data;
            request.Destination = destination;

            AutoResetEvent resetEvent = new AutoResetEvent(false);
            OSDMap         result     = null;

            m_syncMessagePoster.Get(destination.ServerURI, request.ToOSD(), (response) =>
            {
                result = response;
                resetEvent.Set();
            });
            bool success = resetEvent.WaitOne(10000) && result != null;

            if (!success)
            {
                if (m_blackListedRegions.ContainsKey(destination.ServerURI))
                {
                    if (m_blackListedRegions[destination.ServerURI] == 3)
                    {
                        //add it to the blacklist as the request completely failed 3 times
                        m_blackListedRegions[destination.ServerURI] = Util.EnvironmentTickCount() + 60 * 1000; //60 seconds
                    }
                    else if (m_blackListedRegions[destination.ServerURI] == 0)
                    {
                        m_blackListedRegions[destination.ServerURI]++;
                    }
                }
                else
                {
                    m_blackListedRegions[destination.ServerURI] = 0;
                }
                return(false);
            }

            //Clear out the blacklist if it went through
            m_blackListedRegions.Remove(destination.ServerURI);

            return(result["Success"].AsBoolean());
        }
        public virtual void Teleport(IScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt,
                                     uint teleportFlags)
        {
            int x = 0, y = 0;

            Util.UlongToInts(regionHandle, out x, out y);

            GridRegion reg = sp.Scene.GridService.GetRegionByPosition(sp.ControllingClient.AllScopeIDs, x, y);

            if (reg == null)
            {
                List <GridRegion> regions = sp.Scene.GridService.GetRegionRange(
                    sp.ControllingClient.AllScopeIDs,
                    x - (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeX),
                    x + (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeX),
                    y - (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeY),
                    y + (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeY)
                    );
                foreach (GridRegion r in regions)
                {
                    if (r.RegionLocX <= x && r.RegionLocX + r.RegionSizeX > x &&
                        r.RegionLocY <= y && r.RegionLocY + r.RegionSizeY > y)
                    {
                        reg         = r;
                        position.X += x - reg.RegionLocX;
                        position.Y += y - reg.RegionLocY;
                        break;
                    }
                }
                if (reg == null)
                {
                    // TP to a place that doesn't exist (anymore)
                    // Inform the viewer about that
                    sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");

                    // and set the map-tile to '(Offline)'
                    int regX, regY;
                    Util.UlongToInts(regionHandle, out regX, out regY);

                    MapBlockData block = new MapBlockData {
                        X      = (ushort)(regX / Constants.RegionSize),
                        Y      = (ushort)(regY / Constants.RegionSize),
                        Access = 254
                    };
                    // == not there

                    List <MapBlockData> blocks = new List <MapBlockData> {
                        block
                    };
                    sp.ControllingClient.SendMapBlock(blocks, 0);

                    return;
                }
            }
            Teleport(sp, reg, position, lookAt, teleportFlags);
        }
Пример #7
0
        public bool FailedToMoveAgentIntoNewRegion(UUID agentID, GridRegion destination)
        {
            FailedToMoveAgentIntoNewRegionRequest request = new FailedToMoveAgentIntoNewRegionRequest();

            request.AgentID  = agentID;
            request.RegionID = destination.RegionID;

            m_syncMessagePoster.Post(destination.ServerURI, request.ToOSD());
            return(true);
        }
        /// <summary>
        ///     Tries to teleport agent to other region.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="reg"></param>
        /// <param name="position"></param>
        /// <param name="lookAt"></param>
        /// <param name="teleportFlags"></param>
        public void RequestTeleportLocation(IClientAPI remoteClient, GridRegion reg, Vector3 position,
                                            Vector3 lookAt, uint teleportFlags)
        {
            IScenePresence sp = remoteClient.Scene.GetScenePresence(remoteClient.AgentId);

            if (sp != null)
            {
                Teleport(sp, reg, position, lookAt, teleportFlags);
            }
        }
        public virtual void Teleport(IScenePresence sp, GridRegion finalDestination, Vector3 position, Vector3 lookAt,
                                     uint teleportFlags)
        {
            sp.ControllingClient.SendTeleportStart(teleportFlags);
            sp.ControllingClient.SendTeleportProgress(teleportFlags, "requesting");

            // Reset animations; the viewer does that in teleports.
            if (sp.Animator != null)
            {
                sp.Animator.ResetAnimations();
            }

            try {
                string reason = "";
                if (finalDestination.RegionHandle == sp.Scene.RegionInfo.RegionHandle)
                {
                    // First check whether the user is allowed to move at all
                    if (!sp.Scene.Permissions.AllowedOutgoingLocalTeleport(sp.UUID, out reason))
                    {
                        sp.ControllingClient.SendTeleportFailed(reason);
                        return;
                    }
                    // Now respect things like parcel bans with this
                    if (
                        !sp.Scene.Permissions.AllowedIncomingTeleport(sp.UUID, position, teleportFlags, out position,
                                                                      out reason))
                    {
                        sp.ControllingClient.SendTeleportFailed(reason);
                        return;
                    }
                    MainConsole.Instance.DebugFormat("[Entity transfer]: RequestTeleportToLocation {0} within {1}",
                                                     position, sp.Scene.RegionInfo.RegionName);

                    sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
                    sp.RequestModuleInterface <IScriptControllerModule> ()
                    .HandleForceReleaseControls(sp.ControllingClient, sp.UUID);
                    sp.Teleport(position);
                }
                else   // Another region possibly in another simulator
                {
                    // Make sure the user is allowed to leave this region
                    if (!sp.Scene.Permissions.AllowedOutgoingRemoteTeleport(sp.UUID, out reason))
                    {
                        sp.ControllingClient.SendTeleportFailed(reason);
                        return;
                    }

                    DoTeleport(sp, finalDestination, position, lookAt, teleportFlags);
                }
            } catch (Exception e) {
                MainConsole.Instance.ErrorFormat("[Entity transfer]: Exception on teleport: {0}\n{1}",
                                                 e.Message, e.StackTrace);
                sp.ControllingClient.SendTeleportFailed("Internal error");
            }
        }
        public bool CloseAgent(GridRegion destination, UUID agentID)
        {
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);
            if (Scene == null || destination == null)
                return false;

            IEntityTransferModule transferModule = Scene.RequestModuleInterface<IEntityTransferModule>();
            if (transferModule != null)
                return transferModule.IncomingCloseAgent(Scene, agentID);
            return false;
        }
Пример #11
0
        public bool MakeChildAgent(UUID agentID, GridRegion oldRegion, GridRegion destination, bool isCrossing)
        {
            MakeChildAgentRequest request = new MakeChildAgentRequest();

            request.AgentID     = agentID;
            request.OldRegion   = oldRegion;
            request.Destination = destination;
            request.IsCrossing  = isCrossing;

            m_syncMessagePoster.Post(oldRegion.ServerURI, request.ToOSD());
            return(true);
        }
 public bool IsAuthorizedForRegion(GridRegion region, AgentCircuitData agent, bool isRootAgent, out string reason)
 {
     ISceneManager manager = m_registry.RequestModuleInterface<ISceneManager>();
     IScene scene = manager == null ? null : manager.Scenes.Find((s) => s.RegionInfo.RegionID == region.RegionID);
     if (scene != null)
     {
         //Found the region, check permissions
         return scene.Permissions.AllowedIncomingAgent(agent, isRootAgent, out reason);
     }
     reason = "Not Authorized as region does not exist.";
     return false;
 }
Пример #13
0
        void FillOutRegionData(AgentCircuitData circuitData, GridRegion destination)
        {
            IPEndPoint endPoint = destination.ExternalEndPoint;

            //We don't need this anymore, we set this from what we get from the region
            //endPoint = Util.ResolveAddressForClient (endPoint, circuitData.ClientIPEndPoint);
            SimAddress  = endPoint.Address.ToString();
            SimPort     = (uint)circuitData.RegionUDPPort;
            RegionX     = (uint)destination.RegionLocX;
            RegionY     = (uint)destination.RegionLocY;
            RegionSizeX = destination.RegionSizeX;
            RegionSizeY = destination.RegionSizeY;
        }
Пример #14
0
        public void IncomingCapsRequest (UUID agentID, GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_syncMessage = simbase.ApplicationRegistry.RequestModuleInterface<ISyncMessagePosterService> ();
            m_appearanceService = simbase.ApplicationRegistry.RequestModuleInterface<IAgentAppearanceService> ();
            m_region = region;
            m_agentID = agentID;

            if (m_appearanceService == null)
                return;//Can't bake!
            
            m_uri = "/CAPS/UpdateAvatarAppearance/" + UUID.Random () + "/";
            MainServer.Instance.AddStreamHandler (new GenericStreamHandler ("POST", m_uri, UpdateAvatarAppearance));
            capURLs ["UpdateAvatarAppearance"] = MainServer.Instance.ServerURI + m_uri;
        }
        public virtual bool TeleportHome(UUID id, IClientAPI client)
        {
            // MainConsole.Instance.DebugFormat[Entity transfer]r]: Request to teleport {0} {1} home", client.FirstName, client.LastName);

            UserInfo uinfo =
                client.Scene.RequestModuleInterface <IAgentInfoService> ().GetUserInfo(client.AgentId.ToString());

            if (uinfo != null)
            {
                GridRegion regionInfo = client.Scene.GridService.GetRegionByUUID(client.AllScopeIDs, uinfo.HomeRegionID);
                if (regionInfo == null)
                {
                    // can't find the Home region: Tell viewer and abort
                    client.SendTeleportFailed("Your home region could not be found.");
                    return(false);
                }
                MainConsole.Instance.DebugFormat("[Entity transfer]: User's home region is {0} {1} ({2}-{3})",
                                                 regionInfo.RegionName, regionInfo.RegionID,
                                                 regionInfo.RegionLocX / Constants.RegionSize,
                                                 regionInfo.RegionLocY / Constants.RegionSize);

                RequestTeleportLocation(
                    client, regionInfo, uinfo.HomePosition, uinfo.HomeLookAt,
                    (uint)(TeleportFlags.SetLastToTarget | TeleportFlags.ViaHome));
            }
            else
            {
                // Default region time...
                List <GridRegion> defaultRegions = client.Scene.GridService.GetDefaultRegions(client.AllScopeIDs);
                if (defaultRegions.Count > 0)
                {
                    MainConsole.Instance.DebugFormat("[Entity transfer]: User's home region was not found, using {0} {1} ({2}-{3})",
                                                     defaultRegions [0].RegionName,
                                                     defaultRegions [0].RegionID,
                                                     defaultRegions [0].RegionLocX / Constants.RegionSize,
                                                     defaultRegions [0].RegionLocY / Constants.RegionSize);

                    RequestTeleportLocation(
                        client, defaultRegions [0], new Vector3(128, 128, 25), new Vector3(128, 128, 128),
                        (uint)(TeleportFlags.SetLastToTarget | TeleportFlags.ViaHome));
                }
                else
                {
                    defaultRegions = null;
                }
                return(false);
            }

            return(true);
        }
Пример #16
0
        public bool FailedToTeleportAgent(GridRegion destination, UUID failedRegionID, UUID agentID, string reason,
                                          bool isCrossing)
        {
            FailedToTeleportAgentRequest request = new FailedToTeleportAgentRequest();

            request.AgentID        = agentID;
            request.Destination    = destination;
            request.IsCrossing     = isCrossing;
            request.FailedRegionID = failedRegionID;
            request.Reason         = reason;

            m_syncMessagePoster.Post(destination.ServerURI, request.ToOSD());
            return(true);
        }
Пример #17
0
        public void IncomingCapsRequest(UUID agentID, GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_syncMessage       = simbase.ApplicationRegistry.RequestModuleInterface <ISyncMessagePosterService> ();
            m_appearanceService = simbase.ApplicationRegistry.RequestModuleInterface <IAgentAppearanceService> ();
            m_region            = region;
            m_agentID           = agentID;

            if (m_appearanceService == null)
            {
                return;     // Can't bake!
            }
            m_uri = "/CAPS/UpdateAvatarAppearance/" + UUID.Random() + "/";
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", m_uri, UpdateAvatarAppearance));
            capURLs ["UpdateAvatarAppearance"] = MainServer.Instance.ServerURI + m_uri;
        }
Пример #18
0
        public List <GridRegion> GetNeighbours(UUID regionID, List <UUID> scopeIDs, uint squareRangeFromCenterInMeters)
        {
            List <GridRegion> regions = new List <GridRegion> (0);
            GridRegion        region  = Get(regionID, scopeIDs);

            if (region != null)
            {
                int centerX = region.RegionLocX + (region.RegionSizeX / 2); // calculate center of region
                int centerY = region.RegionLocY + (region.RegionSizeY / 2); // calculate center of region

                regions = GetList(scopeIDs, region.RegionID, centerX, centerY, squareRangeFromCenterInMeters);
            }

            return(regions);
        }
Пример #19
0
        /*		#region IService implementation
         *
         *      public void Initialize(IConfigSource config, IRegistryCore registry)
         *      {
         *          throw new System.NotImplementedException();
         *      }
         *
         *      public void Start(IConfigSource config, IRegistryCore registry)
         *      {
         *          throw new System.NotImplementedException();
         *      }
         *
         *      public void FinishedStartup()
         *      {
         *          throw new System.NotImplementedException();
         *      }
         *
         #endregion
         */

        #region user

        /// <summary>
        /// Gets user information for change user info page on site
        /// </summary>
        /// <param name="map">UUID</param>
        /// <returns>Verified, HomeName, HomeUUID, Online, Email, FirstName, LastName</returns>
        OSDMap GetGridUserInfo(OSDMap map)
        {
            string uuid = string.Empty;

            uuid = map ["UUID"].AsString();

            IUserAccountService accountService = m_registry.RequestModuleInterface <IUserAccountService> ();
            UserAccount         userAcct       = accountService.GetUserAccount(null, map ["UUID"].AsUUID());
            IAgentInfoService   agentService   = m_registry.RequestModuleInterface <IAgentInfoService> ();

            UserInfo userinfo;
            OSDMap   resp         = new OSDMap();
            bool     usr_verified = userAcct.Valid;

            resp ["Verified"]  = OSD.FromBoolean(usr_verified);
            resp ["UUID"]      = OSD.FromUUID(userAcct.PrincipalID);
            resp ["Email"]     = OSD.FromString(userAcct.Email);
            resp ["Name"]      = OSD.FromString(userAcct.Name);
            resp ["FirstName"] = OSD.FromString(userAcct.FirstName);
            resp ["LastName"]  = OSD.FromString(userAcct.LastName);

            // just some defaults
            resp ["HomeUUID"] = OSD.FromUUID(UUID.Zero);
            resp ["HomeName"] = OSD.FromString("");
            resp ["Online"]   = OSD.FromBoolean(false);


            if (verified)
            {
                userinfo = agentService.GetUserInfo(uuid);
                if (userinfo != null)
                {
                    resp ["HomeUUID"] = OSD.FromUUID(userinfo.HomeRegionID);
                    resp ["Online"]   = OSD.FromBoolean(userinfo.IsOnline);
                }
                IGridService gs = m_registry.RequestModuleInterface <IGridService> ();
                if (gs != null)
                {
                    GridRegion gr = gs.GetRegionByUUID(null, userinfo.HomeRegionID);
                    if (gr != null)
                    {
                        resp ["HomeName"] = OSD.FromString(gr.RegionName);
                    }
                }
            }

            return(resp);
        }
Пример #20
0
        public OSDMap GetExternalCaps(UUID agentID, GridRegion region)
        {
            if (m_registry == null)
            {
                return(new OSDMap());
            }
            OSDMap resp = new OSDMap();

            if (m_registry.RequestModuleInterface <IGridServerInfoService>() != null)
            {
                m_servers = m_registry.RequestModuleInterface <IGridServerInfoService>().GetGridURIs("SyncMessageServerURI");
                OSDMap req = new OSDMap();
                req["AgentID"] = agentID;
                req["Region"]  = region.ToOSD();
                req["Method"]  = "GetCaps";

                List <ManualResetEvent> events = new List <ManualResetEvent>();
                foreach (string uri in m_servers.Where((u) => (!u.Contains(MainServer.Instance.Port.ToString()))))
                {
                    ManualResetEvent even = new ManualResetEvent(false);
                    m_syncPoster.Get(uri, req, (r) =>
                    {
                        if (r == null)
                        {
                            return;
                        }
                        foreach (KeyValuePair <string, OSD> kvp in r)
                        {
                            resp.Add(kvp.Key, kvp.Value);
                        }
                        even.Set();
                    });
                    events.Add(even);
                }
                if (events.Count > 0)
                {
                    ManualResetEvent.WaitAll(events.ToArray());
                }
            }
            foreach (var h in GetHandlers(agentID, region.RegionID))
            {
                if (m_allowedCapsModules.Contains(h.Name))
                {
                    h.IncomingCapsRequest(agentID, region, m_registry.RequestModuleInterface <ISimulationBase>(), ref resp);
                }
            }
            return(resp);
        }
        public void RemoveExternalCaps(UUID agentID, GridRegion region)
        {
            OSDMap req = new OSDMap();
            req["AgentID"] = agentID;
            req["Region"] = region.ToOSD();
            req["Method"] = "RemoveCaps";

            foreach (string uri in m_servers)
                m_syncPoster.Post(uri, req);

            foreach (var h in GetHandlers(agentID, region.RegionID))
            {
                if (m_allowedCapsModules.Contains(h.Name))
                    h.IncomingCapsDestruction();
            }
        }
        /// <summary>
        ///     Tries to teleport agent to other region.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="regionName"></param>
        /// <param name="position"></param>
        /// <param name="lookat"></param>
        /// <param name="teleportFlags"></param>
        public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
                                            Vector3 lookat, uint teleportFlags)
        {
            GridRegion regionInfo =
                remoteClient.Scene.RequestModuleInterface <IGridService> ()
                .GetRegionByName(remoteClient.AllScopeIDs, regionName);

            if (regionInfo == null)
            {
                // can't find the region: Tell viewer and abort
                remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
                return;
            }

            RequestTeleportLocation(remoteClient, regionInfo, position, lookat, teleportFlags);
        }
Пример #23
0
        private void FillOutHomeData(Framework.Services.UserInfo pinfo, GridRegion home)
        {
            int x = 1000 * Constants.RegionSize, y = 1000 * Constants.RegionSize;

            if (home != null)
            {
                x = home.RegionLocX;
                y = home.RegionLocY;
            }

            Home = string.Format(
                "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
                x,
                y,
                pinfo.HomePosition.X, pinfo.HomePosition.Y, pinfo.HomePosition.Z,
                pinfo.HomeLookAt.X, pinfo.HomeLookAt.Y, pinfo.HomeLookAt.Z);
        }
        public bool CloseAgent(GridRegion destination, UUID agentID)
        {
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);

            if (Scene == null || destination == null)
            {
                return(false);
            }

            IEntityTransferModule transferModule = Scene.RequestModuleInterface <IEntityTransferModule> ();

            if (transferModule != null)
            {
                return(transferModule.IncomingCloseAgent(Scene, agentID));
            }
            return(false);
        }
Пример #25
0
        public LLLoginResponse(UserAccount account, AgentCircuitData aCircuit, Framework.Services.UserInfo pinfo,
                               GridRegion destination, List <InventoryFolderBase> invSkel, FriendInfo[] friendsList,
                               IInventoryService invService, ILibraryService libService,
                               string where, string startlocation, Vector3 position, Vector3 lookAt,
                               List <InventoryItemBase> gestures,
                               GridRegion home, IPEndPoint clientIP, string AdultMax, string AdultRating,
                               ArrayList eventValues, ArrayList eventNotificationValues, ArrayList classifiedValues,
                               string seedCap, IConfigSource source,
                               string DisplayName, string cofversion, IGridInfo info)
            : this()
        {
            m_source       = source;
            m_gridInfo     = info;
            SeedCapability = seedCap;

            FillOutInventoryData(invSkel, libService, invService);

            FillOutActiveGestures(gestures);

            CircuitCode          = (int)aCircuit.CircuitCode;
            Lastname             = account.LastName;
            Firstname            = account.FirstName;
            this.DisplayName     = DisplayName;
            AgentID              = account.PrincipalID;
            SessionID            = aCircuit.SessionID;
            SecureSessionID      = aCircuit.SecureSessionID;
            BuddList             = ConvertFriendListItem(friendsList);
            StartLocation        = where;
            AgentAccessMax       = AdultMax;
            AgentAccess          = AdultRating;
            AgentRegionAccess    = AgentRegionAccess;
            AOTransition         = AOTransition;
            AgentFlag            = AgentFlag;
            eventCategories      = eventValues;
            eventNotifications   = eventNotificationValues;
            classifiedCategories = classifiedValues;
            COFVersion           = cofversion;

            FillOutHomeData(pinfo, home);
            LookAt = string.Format("[r{0},r{1},r{2}]", lookAt.X, lookAt.Y, lookAt.Z);

            FillOutRegionData(aCircuit, destination);
            login        = "******";
            ErrorMessage = "";
            ErrorReason  = LoginResponseEnum.OK;
        }
        public virtual void DoTeleport(IScenePresence sp, GridRegion finalDestination, Vector3 position, Vector3 lookAt,
                                       uint teleportFlags)
        {
            sp.ControllingClient.SendTeleportProgress(teleportFlags, "sending_dest");
            if (finalDestination == null)
            {
                sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
                return;
            }

            MainConsole.Instance.DebugFormat("[Entity transfer]: Request Teleport to {0}:{1}/{2}",
                                             finalDestination.ServerURI, finalDestination.RegionName, position);

            sp.ControllingClient.SendTeleportProgress(teleportFlags, "arriving");
            sp.SetAgentLeaving(finalDestination);

            // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
            // both regions
            if (sp.ParentID != UUID.Zero)
            {
                sp.StandUp();
            }

            AgentCircuitData agentCircuit = BuildCircuitDataForPresence(sp, position);

            AgentData agent = new AgentData();

            sp.CopyTo(agent);
            // Fix the position
            agent.Position = position;

            ISyncMessagePosterService syncPoster = sp.Scene.RequestModuleInterface <ISyncMessagePosterService> ();

            if (syncPoster != null)
            {
                // This does CreateAgent and sends the EnableSimulator/EstablishAgentCommunication/TeleportFinish
                //  messages if they need to be called and deals with the callback
                syncPoster.PostToServer(SyncMessageHelper.TeleportAgent((int)sp.DrawDistance,
                                                                        agentCircuit,
                                                                        agent,
                                                                        teleportFlags,
                                                                        finalDestination,
                                                                        sp.Scene.RegionInfo.RegionID));
            }
        }
Пример #27
0
        public void IncomingCapsRequest(UUID agentID, WhiteCore.Framework.Services.GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_AgentID      = agentID;
            m_assetService = simbase.ApplicationRegistry.RequestModuleInterface <IAssetService>();
            m_j2kDecoder   = simbase.ApplicationRegistry.RequestModuleInterface <IJ2KDecoder>();

            m_getTextureURI       = "/CAPS/GetTexture/" + UUID.Random() + "/";
            capURLs["GetTexture"] = MainServer.Instance.ServerURI + m_getTextureURI;
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("GET", m_getTextureURI, ProcessGetTexture));

            m_bakedTextureURI             = "/CAPS/UploadBakedTexture/" + UUID.Random() + "/";
            capURLs["UploadBakedTexture"] = MainServer.Instance.ServerURI + m_bakedTextureURI;
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", m_bakedTextureURI, UploadBakedTexture));

            m_getMeshURI       = "/CAPS/GetMesh/" + UUID.Random() + "/";
            capURLs["GetMesh"] = MainServer.Instance.ServerURI + m_getMeshURI;
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("GET", m_getMeshURI, ProcessGetMesh));
        }
        public void FailedToTeleportAgent(GridRegion failedCrossingRegion, UUID agentID, string reason, bool isCrossing)
        {
            IScenePresence sp = m_scene.GetScenePresence(agentID);

            if (sp == null)
            {
                return;
            }

            sp.IsChildAgent = false;
            // Tell modules about it
            sp.AgentFailedToLeave();
            sp.ControllingClient.SendTeleportFailed(reason);
            if (isCrossing)
            {
                sp.FailedCrossingTransit(failedCrossingRegion);
            }
        }
        public bool MakeChildAgent(UUID AgentID, GridRegion oldRegion, GridRegion destination, bool isCrossing)
        {
            IScene Scene = oldRegion == null ? null : GetScene(oldRegion.RegionID);

            if (Scene == null)
            {
                return(false);
            }

            IEntityTransferModule transferModule = Scene.RequestModuleInterface <IEntityTransferModule> ();

            if (transferModule == null)
            {
                return(false);
            }
            transferModule.MakeChildAgent(Scene.GetScenePresence(AgentID), destination, isCrossing);
            return(true);
        }
Пример #30
0
        public void IncomingCapsRequest (UUID agentID, GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_agentID = agentID;
            m_region = region;
            m_userScopeIDs = simbase.ApplicationRegistry.RequestModuleInterface<IUserAccountService> ().GetUserAccount (null, m_agentID).AllScopeIDs;

            m_gridService = simbase.ApplicationRegistry.RequestModuleInterface<IGridService> ();
            IConfig config = simbase.ConfigSource.Configs ["MapCAPS"];
            if (config != null)
                m_allowCapsMessage = config.GetBoolean ("AllowCapsMessage", m_allowCapsMessage);

            HttpServerHandle method = (path, request, httpRequest, httpResponse) => MapLayerRequest (HttpServerHandlerHelpers.ReadString (request), httpRequest, httpResponse);
            m_uri = "/CAPS/MapLayer/" + UUID.Random () + "/";
            capURLs ["MapLayer"] = MainServer.Instance.ServerURI + m_uri;
            capURLs ["MapLayerGod"] = MainServer.Instance.ServerURI + m_uri;

            MainServer.Instance.AddStreamHandler (new GenericStreamHandler ("POST", m_uri, method));
        }
        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out CreateAgentResponse response)
        {
            response = null;
            if (destination == null)
            {
                response         = new CreateAgentResponse();
                response.Reason  = "Could not connect to destination";
                response.Success = false;
                return(false);
            }
            CreateAgentRequest request = new CreateAgentRequest();

            request.CircuitData   = aCircuit;
            request.Destination   = destination;
            request.TeleportFlags = teleportFlags;

            AutoResetEvent resetEvent = new AutoResetEvent(false);
            OSDMap         result     = null;

            MainConsole.Instance.DebugFormat("[SimulationServiceConnector]: Sending Create Agent to " + destination.ServerURI);
            m_syncMessagePoster.Get(destination.ServerURI, request.ToOSD(), (osdresp) =>
            {
                result = osdresp;
                resetEvent.Set();
            });
            bool success = resetEvent.WaitOne(10000);

            if (!success || result == null)
            {
                response         = new CreateAgentResponse();
                response.Reason  = "Could not connect to destination";
                response.Success = false;
                return(false);
            }

            response = new CreateAgentResponse();
            response.FromOSD(result);

            if (!response.Success)
            {
                return(false);
            }
            return(response.Success);
        }
        public bool UpdateAgent(GridRegion destination, AgentPosition agentData)
        {
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);

            if (Scene == null || destination == null)
            {
                return(false);
            }

            //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
            IEntityTransferModule transferModule = Scene.RequestModuleInterface <IEntityTransferModule> ();

            if (transferModule != null)
            {
                return(transferModule.IncomingChildAgentDataUpdate(Scene, agentData));
            }

            return(false);
        }
        public bool FailedToTeleportAgent(GridRegion destination, UUID failedRegionID, UUID agentID, string reason,
                                          bool isCrossing)
        {
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);

            if (Scene == null)
            {
                return(false);
            }

            IEntityTransferModule transferModule = Scene.RequestModuleInterface <IEntityTransferModule> ();

            if (transferModule == null)
            {
                return(false);
            }
            transferModule.FailedToTeleportAgent(destination, agentID, reason, isCrossing);
            return(true);
        }
        /**
         * Object-related communications
         */

        public bool CreateObject(GridRegion destination, ISceneEntity sog)
        {
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);

            if (Scene == null || destination == null)
            {
                return(false);
            }

            //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
            IEntityTransferModule AgentTransferModule = Scene.RequestModuleInterface <IEntityTransferModule> ();

            if (AgentTransferModule != null)
            {
                return(AgentTransferModule.IncomingCreateObject(Scene.RegionInfo.RegionID, sog));
            }

            return(false);
        }
Пример #35
0
        void FillOutHomeData(Framework.Services.UserInfo pinfo, GridRegion homeRegion)
        {
            // TODO: The region start positions should be retrieved from the SimulationBase MapCenterX/MapCenterY
            // This is a fallback setting as the user's home region should have been set on login
            int x = Constants.DEFAULT_REGIONSTART_X * Constants.RegionSize;
            int y = Constants.DEFAULT_REGIONSTART_Y * Constants.RegionSize;

            if (homeRegion != null)
            {
                x = homeRegion.RegionLocX;
                y = homeRegion.RegionLocY;
            }

            Home = string.Format(
                "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
                x,
                y,
                pinfo.HomePosition.X, pinfo.HomePosition.Y, pinfo.HomePosition.Z,
                pinfo.HomeLookAt.X, pinfo.HomeLookAt.Y, pinfo.HomeLookAt.Z);
        }
        public bool UpdateAgent(GridRegion destination, AgentData agentData)
        {
            IScene Scene = destination == null ? null : GetScene(destination.RegionID);

            if (destination == null || Scene == null || agentData == null)
            {
                return(false);
            }

            bool retVal = false;
            IEntityTransferModule transferModule = Scene.RequestModuleInterface <IEntityTransferModule> ();

            if (transferModule != null)
            {
                retVal = transferModule.IncomingChildAgentDataUpdate(Scene, agentData);
            }

            //            MainConsole.Instance.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle);
            return(retVal);
        }
        public void Close(IScene scene)
        {
            //Deregister the interface
            scene.UnregisterModuleInterface<IGridRegisterModule>(this);
            m_scene = null;

            MainConsole.Instance.InfoFormat("[RegisterRegionWithGrid]: Deregistering region {0} from the grid...",
                                            scene.RegionInfo.RegionName);

            //Deregister from the grid server
            GridRegion r = new GridRegion(scene.RegionInfo);
            r.IsOnline = false;
            string error = "";
            if (scene.RegionInfo.HasBeenDeleted || !m_markRegionsAsOffline)
                scene.GridService.DeregisterRegion(r);
            else if ((error = scene.GridService.UpdateMap(r, false)) != "")
                MainConsole.Instance.WarnFormat(
                    "[RegisterRegionWithGrid]: Deregister from grid failed for region {0}, {1}",
                    scene.RegionInfo.RegionName, error);
        }
Пример #38
0
        public bool Store(GridRegion region)
        {
            if (region.EstateOwner == UUID.Zero)
            {
                IEstateConnector EstateConnector = Framework.Utilities.DataManager.RequestPlugin <IEstateConnector> ();
                EstateSettings   ES = null;
                if (EstateConnector != null)
                {
                    ES = EstateConnector.GetRegionEstateSettings(region.RegionID);
                    if ((ES != null) && (ES.EstateID != 0))
                    {
                        region.EstateOwner = ES.EstateOwner;
                    }
                }
                if (region.EstateOwner == UUID.Zero && ES != null && ES.EstateID != 0)
                {
                    MainConsole.Instance.Error(
                        "[LocalGridConnector] Attempt to store region with owner of UUID.Zero detected:" +
                        (new System.Diagnostics.StackTrace()).GetFrame(1));
                }
            }

            Dictionary <string, object> row = new Dictionary <string, object> (14);

            row ["ScopeID"]    = region.ScopeID;
            row ["RegionUUID"] = region.RegionID;
            row ["RegionName"] = region.RegionName;
            row ["LocX"]       = region.RegionLocX;
            row ["LocY"]       = region.RegionLocY;
            row ["LocZ"]       = region.RegionLocZ;
            row ["OwnerUUID"]  = region.EstateOwner;
            row ["Access"]     = region.Access;
            row ["SizeX"]      = region.RegionSizeX;
            row ["SizeY"]      = region.RegionSizeY;
            row ["SizeZ"]      = region.RegionSizeZ;
            row ["Flags"]      = region.Flags;
            row ["SessionID"]  = region.SessionID;
            row ["Info"]       = OSDParser.SerializeJsonString(region.ToOSD());

            return(m_GD.Replace(m_realm, row));
        }
        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out CreateAgentResponse response)
        {
            response = null;
            if (destination == null)
            {
                response = new CreateAgentResponse();
                response.Reason = "Could not connect to destination";
                response.Success = false;
                return false;
            }
            CreateAgentRequest request = new CreateAgentRequest();
            request.CircuitData = aCircuit;
            request.Destination = destination;
            request.TeleportFlags = teleportFlags;

            AutoResetEvent resetEvent = new AutoResetEvent(false);
            OSDMap result = null;
            MainConsole.Instance.DebugFormat("[SimulationServiceConnector]: Sending Create Agent to " + destination.ServerURI);
            m_syncMessagePoster.Get(destination.ServerURI, request.ToOSD(), (osdresp) =>
            {
                result = osdresp;
                resetEvent.Set();
            });
            bool success = resetEvent.WaitOne(10000);
            if (!success || result == null)
            {
                response = new CreateAgentResponse();
                response.Reason = "Could not connect to destination";
                response.Success = false;
                return false;
            }

            response = new CreateAgentResponse();
            response.FromOSD(result);

            if (!response.Success)
                return false;
            return response.Success;
        }
        public OSDMap GetExternalCaps (UUID agentID, GridRegion region)
        {
            if (m_registry == null)
                return new OSDMap ();
            OSDMap resp = new OSDMap ();
            if (m_registry.RequestModuleInterface<IGridServerInfoService> () != null)
            {
                m_servers = m_registry.RequestModuleInterface<IGridServerInfoService> ().GetGridURIs ("SyncMessageServerURI");
                OSDMap req = new OSDMap ();
                req ["AgentID"] = agentID;
                req ["Region"] = region.ToOSD ();
                req ["Method"] = "GetCaps";

                List<ManualResetEvent> events = new List<ManualResetEvent> ();
                foreach (string uri in m_servers.Where((u)=>(!u.Contains(MainServer.Instance.Port.ToString()))))
                {
                    ManualResetEvent even = new ManualResetEvent (false);
                    m_syncPoster.Get (uri, req, (r) => {
                        if (r == null)
                            return;
                        foreach (KeyValuePair<string, OSD> kvp in r)
                            resp.Add (kvp.Key, kvp.Value);
                        even.Set ();
                    });
                    events.Add (even);
                }
                if (events.Count > 0)
                    ManualResetEvent.WaitAll (events.ToArray ());
            }
            foreach (var h in GetHandlers(agentID, region.RegionID))
            {
                if (m_allowedCapsModules.Contains (h.Name))
                    h.IncomingCapsRequest (agentID, region, m_registry.RequestModuleInterface<ISimulationBase> (), ref resp);
            }
            return resp;
        }
 /// <summary>
 ///     Tries to teleport agent to other region.
 /// </summary>
 /// <param name="remoteClient"></param>
 /// <param name="reg"></param>
 /// <param name="position"></param>
 /// <param name="lookAt"></param>
 /// <param name="teleportFlags"></param>
 public void RequestTeleportLocation(IClientAPI remoteClient, GridRegion reg, Vector3 position,
     Vector3 lookAt, uint teleportFlags)
 {
     IScenePresence sp = remoteClient.Scene.GetScenePresence(remoteClient.AgentId);
     if (sp != null)
     {
         Teleport(sp, reg, position, lookAt, teleportFlags);
     }
 }
        public void MakeChildAgent(IScenePresence sp, GridRegion finalDestination, bool isCrossing)
        {
            if (sp == null)
                return;

            sp.SetAgentLeaving(finalDestination);

            //Kill the groups here, otherwise they will become ghost attachments
            //  and stay in the sim, they'll get readded below into the new sim
            //KillAttachments(sp);

            // Well, this is it. The agent is over there.
            KillEntity(sp.Scene, sp);

            //Make it a child agent for now... the grid will kill us later if we need to close
            sp.MakeChildAgent(finalDestination);

            if (isCrossing)
                sp.SuccessfulCrossingTransit(finalDestination);
        }
        public virtual void InternalCross(IScenePresence agent, Vector3 attemptedPos, bool isFlying,
            GridRegion crossingRegion)
        {
            MainConsole.Instance.DebugFormat("[EntityTransferModule]: Crossing agent {0} to region {1}", agent.Name,
                                             crossingRegion.RegionName);

            try
            {
                agent.SetAgentLeaving(crossingRegion);

                AgentData cAgent = new AgentData();
                agent.CopyTo(cAgent);
                cAgent.Position = attemptedPos;
                if (isFlying)
                    cAgent.ControlFlags |= (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY;

                AgentCircuitData agentCircuit = BuildCircuitDataForPresence(agent, attemptedPos);
                agentCircuit.TeleportFlags = (uint) TeleportFlags.ViaRegionID;

                //This does UpdateAgent and closing of child agents
                //  messages if they need to be called
                ISyncMessagePosterService syncPoster =
                    agent.Scene.RequestModuleInterface<ISyncMessagePosterService>();
                if (syncPoster != null)
                {
                    syncPoster.PostToServer(SyncMessageHelper.CrossAgent(crossingRegion, attemptedPos,
                                                                         agent.Velocity, agentCircuit, cAgent,
                                                                         agent.Scene.RegionInfo.RegionID));
                }
            }
            catch (Exception ex)
            {
                MainConsole.Instance.Warn("[EntityTransferModule]: Exception in crossing: " + ex);
            }
        }
        public void FailedToTeleportAgent(GridRegion failedCrossingRegion, UUID agentID, string reason, bool isCrossing)
        {
            IScenePresence sp = m_scene.GetScenePresence(agentID);
            if (sp == null)
                return;

            sp.IsChildAgent = false;
            //Tell modules about it
            sp.AgentFailedToLeave();
            sp.ControllingClient.SendTeleportFailed(reason);
            if (isCrossing)
                sp.FailedCrossingTransit(failedCrossingRegion);
        }
        public virtual void DoTeleport(IScenePresence sp, GridRegion finalDestination, Vector3 position, Vector3 lookAt,
            uint teleportFlags)
        {
            sp.ControllingClient.SendTeleportProgress(teleportFlags, "sending_dest");
            if (finalDestination == null)
            {
                sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
                return;
            }

            MainConsole.Instance.DebugFormat(
                "[ENTITY TRANSFER MODULE]: Request Teleport to {0}:{1}/{2}",
                finalDestination.ServerURI, finalDestination.RegionName, position);

            sp.ControllingClient.SendTeleportProgress(teleportFlags, "arriving");
            sp.SetAgentLeaving(finalDestination);

            // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
            // both regions
            if (sp.ParentID != UUID.Zero)
                sp.StandUp();

            AgentCircuitData agentCircuit = BuildCircuitDataForPresence(sp, position);

            AgentData agent = new AgentData();
            sp.CopyTo(agent);
            //Fix the position
            agent.Position = position;

            ISyncMessagePosterService syncPoster = sp.Scene.RequestModuleInterface<ISyncMessagePosterService>();
            if (syncPoster != null)
            {
                //This does CreateAgent and sends the EnableSimulator/EstablishAgentCommunication/TeleportFinish
                //  messages if they need to be called and deals with the callback
                syncPoster.PostToServer(SyncMessageHelper.TeleportAgent((int) sp.DrawDistance,
                                                                        agentCircuit, agent, teleportFlags,
                                                                        finalDestination, sp.Scene.RegionInfo.RegionID));
            }
        }
        /// <summary>
        ///     Move the given scene object into a new region depending on which region its absolute position has moved
        ///     into.
        ///     This method locates the new region handle and offsets the prim position for the new region
        /// </summary>
        /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
        /// <param name="grp">the scene object that we're crossing</param>
        /// <param name="destination"></param>
        public bool CrossGroupToNewRegion(ISceneEntity grp, Vector3 attemptedPosition, GridRegion destination)
        {
            if (grp == null)
                return false;
            if (grp.IsDeleted)
                return false;

            if (grp.Scene == null)
                return false;
            if (grp.RootChild.DIE_AT_EDGE)
            {
                // We remove the object here
                try
                {
                    IBackupModule backup = grp.Scene.RequestModuleInterface<IBackupModule>();
                    if (backup != null)
                        return backup.DeleteSceneObjects(new[] {grp}, true, true);
                }
                catch (Exception)
                {
                    MainConsole.Instance.Warn(
                        "[DATABASE]: exception when trying to remove the prim that crossed the border.");
                }
                return false;
            }

            if (grp.RootChild.RETURN_AT_EDGE)
            {
                // We remove the object here
                try
                {
                    List<ISceneEntity> objects = new List<ISceneEntity> {grp};
                    ILLClientInventory inventoryModule = grp.Scene.RequestModuleInterface<ILLClientInventory>();
                    if (inventoryModule != null)
                        return inventoryModule.ReturnObjects(objects.ToArray(), UUID.Zero);
                }
                catch (Exception)
                {
                    MainConsole.Instance.Warn(
                        "[SCENE]: exception when trying to return the prim that crossed the border.");
                }
                return false;
            }

            Vector3 oldGroupPosition = grp.RootChild.GroupPosition;
            // If we fail to cross the border, then reset the position of the scene object on that border.
            if (destination != null && !CrossPrimGroupIntoNewRegion(destination, grp, attemptedPosition))
            {
                grp.OffsetForNewRegion(oldGroupPosition);
                grp.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
                return false;
            }
            return true;
        }
        public virtual void Cross(IScenePresence agent, bool isFlying, GridRegion crossingRegion)
        {
            Vector3 pos = new Vector3(agent.AbsolutePosition.X, agent.AbsolutePosition.Y, agent.AbsolutePosition.Z);
            pos.X = (agent.Scene.RegionInfo.RegionLocX + pos.X) - crossingRegion.RegionLocX;
            pos.Y = (agent.Scene.RegionInfo.RegionLocY + pos.Y) - crossingRegion.RegionLocY;

            //Make sure that they are within bounds (velocity can push it out of bounds)
            if (pos.X < 0)
                pos.X = 1;
            if (pos.Y < 0)
                pos.Y = 1;

            if (pos.X > crossingRegion.RegionSizeX)
                pos.X = crossingRegion.RegionSizeX - 1;
            if (pos.Y > crossingRegion.RegionSizeY)
                pos.Y = crossingRegion.RegionSizeY - 1;
            InternalCross(agent, pos, isFlying, crossingRegion);
        }
        /// <summary>
        ///     Recursive SendGridInstantMessage over XMLRPC method.
        ///     This is called from within a dedicated thread.
        ///     The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from
        ///     itself, prevRegionHandle will be the last region handle that we tried to send.
        ///     If the handles are the same, we look up the user's location using the grid.
        ///     If the handles are still the same, we end.  The send failed.
        /// </summary>
        /// <param name="im"></param>
        /// <param name="prevRegion">
        ///     Pass in 0 the first time this method is called.  It will be called recursively with the last
        ///     regionhandle tried
        /// </param>
        protected virtual void SendGridInstantMessageViaXMLRPCAsync (GridInstantMessage im,
                                                                    GridRegion prevRegion)
        {
            UUID toAgentID = im.ToAgentID;
            string HTTPPath = "";

            lock (IMUsersCache) {
                if (!IMUsersCache.TryGetValue (toAgentID, out HTTPPath))
                    HTTPPath = "";
            }

            if (HTTPPath != "") {
                //We've tried to send an IM to them before, pull out their info
                //Send the IM to their last location
                if (!doIMSending (HTTPPath, im)) {
                    //If this fails, the user has either moved from their stored location or logged out
                    //Since it failed, let it look them up again and rerun
                    lock (IMUsersCache) {
                        IMUsersCache.Remove (toAgentID);
                    }
                    //Clear the path and let it continue trying again.
                    HTTPPath = "";
                } else {
                    //Send the IM, and it made it to the user, return true
                    return;
                }
            }

            //Now query the grid server for the agent
            List<string> AgentLocations = m_agentInfoService.GetAgentsLocations (im.FromAgentID.ToString (),
                                                                 new List<string> (new [] { toAgentID.ToString () }));
            if (AgentLocations != null && AgentLocations.Count > 0) {
                //No agents, so this user is offline
                if (AgentLocations [0] == "NotOnline") {
                    lock (IMUsersCache) {
                        //Remove them so we keep testing against the db
                        IMUsersCache.Remove (toAgentID);
                    }
                    MainConsole.Instance.Debug ("[GRID INSTANT MESSAGE]: Unable to deliver an instant message as user is not online");
                    HandleUndeliveredMessage (im, "User is not online.");
                    return;
                }
                if (AgentLocations [0] == "NonExistant") {
                    IMUsersCache.Remove (toAgentID);
                    MainConsole.Instance.Info ("[GRID INSTANT MESSAGE]: Unable to deliver an instant message to " +
                                              toAgentID +
                                              ", user does not exist");
                    HandleUndeliveredMessage (im, "User does not exist.");
                    return;
                }
                HTTPPath = AgentLocations [0];
            }

            //We found the agent's location, now ask them about the user
            if (HTTPPath != "") {
                if (!doIMSending (HTTPPath, im)) {
                    //It failed, stop now
                    lock (IMUsersCache) {
                        //Remove them so we keep testing against the db
                        IMUsersCache.Remove (toAgentID);
                    }
                    MainConsole.Instance.Info (
                        "[GRID INSTANT MESSAGE]: Unable to deliver an instant message as the region could not be found");
                    HandleUndeliveredMessage (im, "Failed to send IM to destination.");
                    return;
                } else {
                    //Add to the cache
                    if (!IMUsersCache.ContainsKey (toAgentID))
                        IMUsersCache.Add (toAgentID, HTTPPath);
                    //Send the IM, and it made it to the user, return true
                    return;
                }
            } else {
                //Couldn't find them, stop for now
                lock (IMUsersCache) {
                    //Remove them so we keep testing against the db
                    IMUsersCache.Remove (toAgentID);
                }
                MainConsole.Instance.Info (
                    "[GRID INSTANT MESSAGE]: Unable to deliver an instant message as the region could not be found");
                HandleUndeliveredMessage (im, "Agent Location was blank.");
            }
        }
Пример #49
0
 protected bool TryFindGridRegionForAgentLogin(List<GridRegion> regions, UserAccount account,
     UUID session, UUID secureSession,
     uint circuitCode, Vector3 position,
     IPEndPoint clientIP, AgentCircuitData aCircuit, List<UUID> friendsToInform,
     out string seedCap, out string reason, out GridRegion destination)
 {
     LoginAgentArgs args = null;
     foreach (GridRegion r in regions)
     {
         if (r == null)
             continue;
         MainConsole.Instance.DebugFormat("[LoginService]: Attempting to log {0} into {1} at {2}...", account.Name, r.RegionName, r.ServerURI);
         args = m_registry.RequestModuleInterface<IAgentProcessing>().
                           LoginAgent(r, aCircuit, friendsToInform);
         if (args.Success)
         {
             aCircuit = MakeAgent(r, account, session, secureSession, circuitCode, position, clientIP);
             destination = r;
             reason = args.Reason;
             seedCap = args.SeedCap;
             return true;
         }
         m_GridService.SetRegionUnsafe(r.RegionID);
     }
     if (args != null)
     {
         seedCap = args.SeedCap;
         reason = args.Reason;
     }
     else
     {
         seedCap = "";
         reason = "";
     }
     destination = null;
     return false;
 }
Пример #50
0
        protected AgentCircuitData LaunchAgentAtGrid(GridRegion destination, TeleportFlags tpFlags, UserAccount account,
            UUID session, UUID secureSession, Vector3 position,
            string currentWhere,
            IPEndPoint clientIP, List<UUID> friendsToInform, out string where, out string reason,
            out string seedCap, out GridRegion dest)
        {
            where = currentWhere;
            reason = string.Empty;
            uint circuitCode = 0;
            AgentCircuitData aCircuit = null;
            dest = destination;

            #region Launch Agent

            circuitCode = (uint) Util.RandomClass.Next();
            aCircuit = MakeAgent(destination, account, session, secureSession, circuitCode, position,
                                 clientIP);
            aCircuit.TeleportFlags = (uint) tpFlags;
            MainConsole.Instance.DebugFormat("[LoginService]: Attempting to log {0} into {1} at {2}...", account.Name, destination.RegionName, destination.ServerURI);
            LoginAgentArgs args = m_registry.RequestModuleInterface<IAgentProcessing>().
                                             LoginAgent(destination, aCircuit, friendsToInform);
            aCircuit.CachedUserInfo = args.CircuitData.CachedUserInfo;
            aCircuit.RegionUDPPort = args.CircuitData.RegionUDPPort;

            reason = args.Reason;
            reason = "";
            seedCap = args.SeedCap;
            bool success = args.Success;
            if (!success && m_GridService != null)
            {
                MainConsole.Instance.DebugFormat("[LoginService]: Failed to log {0} into {1} at {2}...", account.Name, destination.RegionName, destination.ServerURI);
                //Remove the landmark flag (landmark is used for ignoring the landing points in the region)
                aCircuit.TeleportFlags &= ~(uint) TeleportFlags.ViaLandmark;
                m_GridService.SetRegionUnsafe(destination.RegionID);

                // Make sure the client knows this isn't where they wanted to land
                where = "safe";

                // Try the default regions
                List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(account.AllScopeIDs);
                if (defaultRegions != null)
                {
                    success = TryFindGridRegionForAgentLogin(defaultRegions, account,
                                                             session, secureSession, circuitCode, position,
                                                             clientIP, aCircuit, friendsToInform,
                                                             out seedCap, out reason, out dest);
                }
                if (!success)
                {
                    // Try the fallback regions
                    List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs,
                                                                                  destination.RegionLocX,
                                                                                  destination.RegionLocY);
                    if (fallbacks != null)
                    {
                        success = TryFindGridRegionForAgentLogin(fallbacks, account,
                                                                 session, secureSession, circuitCode,
                                                                 position,
                                                                 clientIP, aCircuit, friendsToInform,
                                                                 out seedCap, out reason, out dest);
                    }
                    if (!success)
                    {
                        //Try to find any safe region
                        List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs,
                                                                                    destination.RegionLocX,
                                                                                    destination.RegionLocY);
                        if (safeRegions != null)
                        {
                            success = TryFindGridRegionForAgentLogin(safeRegions, account,
                                                                     session, secureSession, circuitCode,
                                                                     position, clientIP, aCircuit, friendsToInform,
                                                                     out seedCap, out reason, out dest);
                            if (!success)
                                reason = "No Region Found";
                        }
                    }
                }
            }

            #endregion

            if (success)
            {
                MainConsole.Instance.DebugFormat("[LoginService]: Successfully logged {0} into {1} at {2}...", account.Name, destination.RegionName, destination.ServerURI);
                //Set the region to safe since we got there
                m_GridService.SetRegionSafe(destination.RegionID);
                return aCircuit;
            }
            return null;
        }
        /// <summary>
        ///     Move the given scene object into a new region
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="grp">Scene Object Group that we're crossing</param>
        /// <param name="attemptedPos"></param>
        /// <returns>
        ///     true if the crossing itself was successful, false on failure
        /// </returns>
        protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, ISceneEntity grp, Vector3 attemptedPos)
        {
            bool successYN = false;
            if (destination != null)
            {
                if (grp.SitTargetAvatar.Count != 0)
                {
                    foreach (UUID avID in grp.SitTargetAvatar)
                    {
                        IScenePresence SP = grp.Scene.GetScenePresence(avID);
                        SP.Velocity = grp.RootChild.PhysActor.Velocity;
                        InternalCross(SP, attemptedPos, false, destination);
                    }
                    foreach (ISceneChildEntity part in grp.ChildrenEntities())
                        part.SitTargetAvatar = new List<UUID>();

                    IBackupModule backup = grp.Scene.RequestModuleInterface<IBackupModule>();
                    if (backup != null)
                        return backup.DeleteSceneObjects(new[] {grp}, false, false);
                    return true; //They do all the work adding the prim in the other region
                }

                ISceneEntity copiedGroup = grp.Copy(false);
                copiedGroup.SetAbsolutePosition(true, attemptedPos);
                if (grp.Scene != null)
                    successYN = grp.Scene.RequestModuleInterface<ISimulationService>()
                                   .CreateObject(destination, copiedGroup);

                if (successYN)
                {
                    // We remove the object here
                    try
                    {
                        IBackupModule backup = grp.Scene.RequestModuleInterface<IBackupModule>();
                        if (backup != null)
                            return backup.DeleteSceneObjects(new[] {grp}, false, true);
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.ErrorFormat(
                            "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
                            grp, e);
                    }
                }
                else
                {
                    if (!grp.IsDeleted)
                    {
                        if (grp.RootChild.PhysActor != null)
                        {
                            grp.RootChild.PhysActor.CrossingFailure();
                        }
                    }

                    MainConsole.Instance.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp);
                }
            }
            else
            {
                MainConsole.Instance.Error(
                    "[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
            }

            return successYN;
        }
        public virtual void Teleport(IScenePresence sp, GridRegion finalDestination, Vector3 position, Vector3 lookAt,
            uint teleportFlags)
        {
            sp.ControllingClient.SendTeleportStart(teleportFlags);
            sp.ControllingClient.SendTeleportProgress(teleportFlags, "requesting");

            // Reset animations; the viewer does that in teleports.
            if (sp.Animator != null)
                sp.Animator.ResetAnimations();

            try
            {
                string reason = "";
                if (finalDestination.RegionHandle == sp.Scene.RegionInfo.RegionHandle)
                {
                    //First check whether the user is allowed to move at all
                    if (!sp.Scene.Permissions.AllowedOutgoingLocalTeleport(sp.UUID, out reason))
                    {
                        sp.ControllingClient.SendTeleportFailed(reason);
                        return;
                    }
                    //Now respect things like parcel bans with this
                    if (
                        !sp.Scene.Permissions.AllowedIncomingTeleport(sp.UUID, position, teleportFlags, out position,
                                                                      out reason))
                    {
                        sp.ControllingClient.SendTeleportFailed(reason);
                        return;
                    }
                    MainConsole.Instance.DebugFormat(
                        "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation {0} within {1}",
                        position, sp.Scene.RegionInfo.RegionName);

                    sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
                    sp.RequestModuleInterface<IScriptControllerModule>()
                      .HandleForceReleaseControls(sp.ControllingClient, sp.UUID);
                    sp.Teleport(position);
                }
                else // Another region possibly in another simulator
                {
                    // Make sure the user is allowed to leave this region
                    if (!sp.Scene.Permissions.AllowedOutgoingRemoteTeleport(sp.UUID, out reason))
                    {
                        sp.ControllingClient.SendTeleportFailed(reason);
                        return;
                    }

                    DoTeleport(sp, finalDestination, position, lookAt, teleportFlags);
                }
            }
            catch (Exception e)
            {
                MainConsole.Instance.ErrorFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0}\n{1}", e.Message,
                                                 e.StackTrace);
                sp.ControllingClient.SendTeleportFailed("Internal error");
            }
        }
        /// <summary>
        ///     Verify if the user can connect to this region.  Checks the banlist and ensures that the region is set for public access
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="agent">The circuit data for the agent</param>
        /// <param name="reason">outputs the reason to this string</param>
        /// <returns>
        ///     True if the region accepts this agent.  False if it does not.  False will
        ///     also return a reason.
        /// </returns>
        protected bool AuthorizeUser(IScene scene, AgentCircuitData agent, out string reason)
        {
            reason = String.Empty;

            IAuthorizationService AuthorizationService = scene.RequestModuleInterface<IAuthorizationService>();
            if (AuthorizationService != null)
            {
                GridRegion ourRegion = new GridRegion(scene.RegionInfo);
                if (!AuthorizationService.IsAuthorizedForRegion(ourRegion, agent, !agent.IsChildAgent, out reason))
                {
                    MainConsole.Instance.WarnFormat(
                        "[ConnectionBegin]: Denied access to {0} at {1} because the user does not have access to the region, reason: {2}",
                        agent.AgentID, scene.RegionInfo.RegionName, reason);
                    reason = String.Format("You do not have access to the region {0}, reason: {1}",
                                           scene.RegionInfo.RegionName, reason);
                    return false;
                }
            }

            return true;
        }
Пример #54
0
        protected virtual OSDMap OnMessageReceived(OSDMap message)
        {
            if (!message.ContainsKey("Method"))
                return null;

            if (m_capsService == null)
                return null;

            string method = message["Method"].AsString();
            if (method != "RegionIsOnline" && method != "LogoutRegionAgents" &&
                method != "ArrivedAtDestination" && method != "CancelTeleport" &&
                method != "AgentLoggedOut" && method != "SendChildAgentUpdate" &&
                method != "TeleportAgent" && method != "CrossAgent")
                return null;

            UUID AgentID = message["AgentID"].AsUUID();
            UUID requestingRegion = message["RequestingRegion"].AsUUID();

            IClientCapsService clientCaps = m_capsService.GetClientCapsService(AgentID);

            IRegionClientCapsService regionCaps = null;
            if (clientCaps != null)
                regionCaps = clientCaps.GetCapsService(requestingRegion);
            if (message["Method"] == "LogoutRegionAgents")
            {
                LogOutAllAgentsForRegion(requestingRegion);
            }
            else if (message["Method"] == "RegionIsOnline")
                //This gets fired when the scene is fully finished starting up
            {
                //Log out all the agents first, then add any child agents that should be in this region
                //Don't do this, we don't need to kill all the clients right now
                //LogOutAllAgentsForRegion(requestingRegion);
                IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
                if (GridService != null)
                {
                    GridRegion requestingGridRegion = GridService.GetRegionByUUID(null, requestingRegion);
                    if (requestingGridRegion != null)
                        Util.FireAndForget((o) => EnableChildAgentsForRegion(requestingGridRegion));
                }
            }
            else if (message["Method"] == "ArrivedAtDestination")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                //Recieved a callback
                if (clientCaps.InTeleport) //Only set this if we are in a teleport,
                    //  otherwise (such as on login), this won't check after the first tp!
                    clientCaps.CallbackHasCome = true;

                regionCaps.Disabled = false;

                //The agent is getting here for the first time (eg. login)
                OSDMap body = ((OSDMap) message["Message"]);

                //Parse the OSDMap
                int DrawDistance = body["DrawDistance"].AsInteger();

                AgentCircuitData circuitData = new AgentCircuitData();
                circuitData.FromOSD((OSDMap)body["Circuit"]);

                //Now do the creation
                EnableChildAgents(AgentID, requestingRegion, DrawDistance, circuitData);
            }
            else if (message["Method"] == "CancelTeleport")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                //Only the region the client is root in can do this
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    //The user has requested to cancel the teleport, stop them.
                    clientCaps.RequestToCancelTeleport = true;
                    regionCaps.Disabled = false;
                }
            }
            else if (message["Method"] == "AgentLoggedOut")
            {
                //ONLY if the agent is root do we even consider it
                if (regionCaps != null && regionCaps.RootAgent)
                {
                    OSDMap body = ((OSDMap) message["Message"]);

                    AgentPosition pos = new AgentPosition();
                    pos.FromOSD((OSDMap)body["AgentPos"]);

                    regionCaps.Disabled = true;

                    Util.FireAndForget((o) =>
                                           {
                                               LogoutAgent(regionCaps, false); //The root is killing itself
                                               SendChildAgentUpdate(pos, regionCaps);
                                           });
                }
            }
            else if (message["Method"] == "SendChildAgentUpdate")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle) //Has to be root
                {
                    OSDMap body = ((OSDMap) message["Message"]);

                    AgentPosition pos = new AgentPosition();
                    pos.FromOSD((OSDMap) body["AgentPos"]);

                    SendChildAgentUpdate(pos, regionCaps);
                    regionCaps.Disabled = false;
                }
            }
            else if (message["Method"] == "TeleportAgent")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    OSDMap body = ((OSDMap) message["Message"]);

                    GridRegion destination = new GridRegion();
                    destination.FromOSD((OSDMap) body["Region"]);

                    uint TeleportFlags = body["TeleportFlags"].AsUInteger();

                    AgentCircuitData Circuit = new AgentCircuitData();
                    Circuit.FromOSD((OSDMap)body["Circuit"]);

                    AgentData AgentData = new AgentData();
                    AgentData.FromOSD((OSDMap)body["AgentData"]);
                    regionCaps.Disabled = false;

                    //Don't need to wait for this to finish on the main http thread
                    Util.FireAndForget((o) =>
                                           {
                                               string reason = "";
                                               TeleportAgent(ref destination, TeleportFlags,
                                                             Circuit, AgentData, AgentID, requestingRegion, out reason);
                                           });
                    return null;
                }
            }
            else if (message["Method"] == "CrossAgent")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps == null || rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    //This is a simulator message that tells us to cross the agent
                    OSDMap body = ((OSDMap) message["Message"]);

                    Vector3 pos = body["Pos"].AsVector3();
                    Vector3 Vel = body["Vel"].AsVector3();
                    GridRegion Region = new GridRegion();
                    Region.FromOSD((OSDMap) body["Region"]);
                    AgentCircuitData Circuit = new AgentCircuitData();
                    Circuit.FromOSD((OSDMap)body["Circuit"]);
                    AgentData AgentData = new AgentData();
                    AgentData.FromOSD((OSDMap)body["AgentData"]);
                    regionCaps.Disabled = false;

                    Util.FireAndForget((o) =>
                                           {
                                               string reason = "";
                                               CrossAgent(Region, pos, Vel, Circuit, AgentData,
                                                          AgentID, requestingRegion, out reason);
                                           });
                    return null;
                }
                else if (clientCaps.InTeleport)
                {
                    OSDMap result = new OSDMap();
                    result["success"] = false;
                    result["Note"] = false;
                    return result;
                }
                else
                {
                    OSDMap result = new OSDMap();
                    result["success"] = false;
                    result["Note"] = false;
                    return result;
                }
            }
            return null;
        }
Пример #55
0
 private void EventManager_OnMakeChildAgent(IScenePresence presence, GridRegion destination)
 {
     m_authorizedParticipants.Remove(presence.UUID);
     m_userLogLevel.Remove(presence.UUID);
 }
Пример #56
0
 public void TriggerOnRegionUp(GridRegion otherRegion)
 {
     RegionUp handlerOnRegionUp = OnRegionUp;
     if (handlerOnRegionUp != null)
     {
         foreach (RegionUp d in handlerOnRegionUp.GetInvocationList())
         {
             try
             {
                 d(otherRegion);
             }
             catch (Exception e)
             {
                 MainConsole.Instance.ErrorFormat(
                     "[EVENT MANAGER]: Delegate for TriggerOnRegionUp failed - continuing.  {0} {1}",
                     e, e.StackTrace);
             }
         }
     }
 }
Пример #57
0
 protected AgentCircuitData MakeAgent(GridRegion region, UserAccount account,
     UUID session, UUID secureSession, uint circuit,
     Vector3 position, IPEndPoint clientIP)
 {
     return new AgentCircuitData
                                     {
                                         AgentID = account.PrincipalID,
                                         IsChildAgent = false,
                                         CircuitCode = circuit,
                                         SecureSessionID = secureSession,
                                         SessionID = session,
                                         StartingPosition = position,
                                         IPAddress = clientIP.Address.ToString()
                                     };
 }
Пример #58
0
 public void TriggerOnSetAgentLeaving(IScenePresence presence, GridRegion destination)
 {
     OnMakeChildAgentDelegate handlerMakeChildAgent = OnSetAgentLeaving;
     if (handlerMakeChildAgent != null)
     {
         foreach (OnMakeChildAgentDelegate d in handlerMakeChildAgent.GetInvocationList())
         {
             try
             {
                 d(presence, destination);
             }
             catch (Exception e)
             {
                 MainConsole.Instance.ErrorFormat(
                     "[EVENT MANAGER]: Delegate for TriggerOnSetAgentLeaving failed - continuing.  {0} {1}",
                     e, e.StackTrace);
             }
         }
     }
 }
Пример #59
0
        protected GridRegion FindDestination(UserAccount account, UserInfo pinfo, UUID sessionID, string startLocation,
            GridRegion home, out TeleportFlags tpFlags, out string where,
            out Vector3 position, out Vector3 lookAt)
        {
            where = "home";
            position = new Vector3(128, 128, 25);
            lookAt = new Vector3(0, 1, 0);
            tpFlags = TeleportFlags.ViaLogin;

            if (m_GridService == null)
                return null;

            if (startLocation.Equals("home"))
            {
                tpFlags |= TeleportFlags.ViaLandmark;
                // logging into home region
                if (pinfo == null)
                    return null;

                GridRegion region = null;

                bool tryDefaults = false;

                if (home == null)
                {
                    MainConsole.Instance.WarnFormat(
                        "[LLOGIN SERVICE]: User {0} {1} tried to login to a 'home' start location but they have none set",
                        account.FirstName, account.LastName);

                    tryDefaults = true;
                }
                else
                {
                    region = home;

                    position = pinfo.HomePosition;
                    lookAt = pinfo.HomeLookAt;
                }

                if (tryDefaults)
                {
                    tpFlags &= ~TeleportFlags.ViaLandmark;
                    List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.AllScopeIDs);
                    if (defaults != null && defaults.Count > 0)
                    {
                        region = defaults[0];
                        where = "safe";
                    }
                    else
                    {
                        List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0);
                        if (fallbacks != null && fallbacks.Count > 0)
                        {
                            region = fallbacks[0];
                            where = "safe";
                        }
                        else
                        {
                            //Try to find any safe region
                            List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0);
                            if (safeRegions != null && safeRegions.Count > 0)
                            {
                                region = safeRegions[0];
                                where = "safe";
                            }
                            else
                            {
                                MainConsole.Instance.WarnFormat(
                                    "[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region",
                                    account.FirstName, account.LastName);
                                defaults = m_GridService.GetRegionsByName(account.AllScopeIDs, "", 0, 1);
                                if (defaults != null && defaults.Count > 0)
                                {
                                    region = defaults[0];
                                    where = "safe";
                                }
                            }
                        }
                    }
                }

                return region;
            }
            if (startLocation.Equals("last"))
            {
                tpFlags |= TeleportFlags.ViaLandmark;
                // logging into last visited region
                where = "last";

                if (pinfo == null)
                    return null;

                GridRegion region = null;

                if (pinfo.CurrentRegionID.Equals(UUID.Zero) ||
                    (region = m_GridService.GetRegionByUUID(account.AllScopeIDs, pinfo.CurrentRegionID)) == null)
                {
                    tpFlags &= ~TeleportFlags.ViaLandmark;
                    List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.AllScopeIDs);
                    if (defaults != null && defaults.Count > 0)
                    {
                        region = defaults[0];
                        where = "safe";
                    }
                    else
                    {
                        defaults = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0);
                        if (defaults != null && defaults.Count > 0)
                        {
                            region = defaults[0];
                            where = "safe";
                        }
                        else
                        {
                            defaults = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0);
                            if (defaults != null && defaults.Count > 0)
                            {
                                region = defaults[0];
                                where = "safe";
                            }
                        }
                    }
                }
                else
                {
                    position = pinfo.CurrentPosition;
                    if (position.X < 0)
                        position.X = 0;
                    if (position.Y < 0)
                        position.Y = 0;
                    if (position.Z < 0)
                        position.Z = 0;
                    if (position.X > region.RegionSizeX)
                        position.X = region.RegionSizeX;
                    if (position.Y > region.RegionSizeY)
                        position.Y = region.RegionSizeY;

                    lookAt = pinfo.CurrentLookAt;
                }

                return region;
            }
            else
            {
                // free uri form
                // e.g. New Moon&135&46  New [email protected]:8002&153&34
                where = "url";
                Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
                Match uriMatch = reURI.Match(startLocation);
                position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
                                       float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo),
                                       float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));

                string regionName = uriMatch.Groups["region"].ToString();
                if (!regionName.Contains("@"))
                {
                    List<GridRegion> regions = m_GridService.GetRegionsByName(account.AllScopeIDs, regionName, 0, 1);
                    if ((regions == null) || (regions.Count == 0))
                    {
                        MainConsole.Instance.InfoFormat(
                            "[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.",
                            startLocation, regionName);
                        regions = m_GridService.GetDefaultRegions(account.AllScopeIDs);
                        if (regions != null && regions.Count > 0)
                        {
                            where = "safe";
                            return regions[0];
                        }
                        List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0);
                        if (fallbacks != null && fallbacks.Count > 0)
                        {
                            where = "safe";
                            return fallbacks[0];
                        }
                        //Try to find any safe region
                        List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0);
                        if (safeRegions != null && safeRegions.Count > 0)
                        {
                            where = "safe";
                            return safeRegions[0];
                        }
                        MainConsole.Instance.InfoFormat(
                            "[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not have any available regions.",
                            startLocation);
                        return null;
                    }
                    return regions[0];
                }
                //This is so that you can login to other grids via IWC (or HG), example"[email protected]:8002". All this really needs to do is inform the other grid that we have a user who wants to connect. IWC allows users to login by default to other regions (without the host names), but if one is provided and we don't have a link, we need to create one here.
                string[] parts = regionName.Split(new char[] {'@'});
                if (parts.Length < 2)
                {
                    MainConsole.Instance.InfoFormat(
                        "[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}",
                        startLocation, regionName);
                    return null;
                }
                // Valid specification of a remote grid

                regionName = parts[0];
                //Try now that we removed the domain locator
                GridRegion region = m_GridService.GetRegionByName(account.AllScopeIDs, regionName);
                if (region != null && region.RegionName == regionName)
                    //Make sure the region name is right too... it could just be a similar name
                    return region;

                List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.AllScopeIDs);
                if (defaults != null && defaults.Count > 0)
                {
                    where = "safe";
                    return defaults[0];
                }
                else
                {
                    List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0);
                    if (fallbacks != null && fallbacks.Count > 0)
                    {
                        where = "safe";
                        return fallbacks[0];
                    }
                    else
                    {
                        //Try to find any safe region
                        List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0);
                        if (safeRegions != null && safeRegions.Count > 0)
                        {
                            where = "safe";
                            return safeRegions[0];
                        }
                        MainConsole.Instance.InfoFormat(
                            "[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not have any available regions.",
                            startLocation);
                        return null;
                    }
                }
            }
        }
        /// <summary>
        ///     Register this region with the grid service
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="returnResponseFirstTime">Should we try to walk the user through what went wrong?</param>
        /// <param name="continueTrying"> </param>
        /// <param name="password"> </param>
        public bool RegisterRegionWithGrid(IScene scene, bool returnResponseFirstTime, bool continueTrying,
            string password)
        {
            if (password == null)
                password = m_RegisterRegionPassword;

            GridRegion region = new GridRegion (scene.RegionInfo);

            IGridService GridService = scene.RequestModuleInterface<IGridService> ();

            scene.RequestModuleInterface<ISimulationBase> ()
                 .EventManager.FireGenericEventHandler ("PreRegisterRegion", region);

            //Tell the grid service about us
            RegisterRegion error = GridService.RegisterRegion (region, scene.RegionInfo.GridSecureSessionID, password,
                                       ProtocolVersion.MAJOR_PROTOCOL_VERSION,
                                       ProtocolVersion.MINOR_PROTOCOL_VERSION);
            if (error.Error == String.Empty)
            {
                //If it registered ok, we save the sessionID to the database and tell the neighbor service about it
                scene.RegionInfo.GridSecureSessionID = error.SessionID;
                //Update our local copy of what our region flags are
                scene.RegionInfo.RegionFlags = error.RegionFlags;
                scene.RegionInfo.ScopeID = error.Region.ScopeID;
                scene.RegionInfo.AllScopeIDs = error.Region.AllScopeIDs;
                scene.RequestModuleInterface<IConfigurationService> ().SetURIs (error.URIs);
                m_knownNeighbors [scene.RegionInfo.RegionID] = error.Neighbors;
                return true; //Success
            }
            if (returnResponseFirstTime && !continueTrying)
            {
                MainConsole.Instance.Error (
                    "[RegisterRegionWithGrid]: Registration of region with grid failed again - " + error.Error);
                return false;
            }

            //Parse the error and try to do something about it if at all possible
            if (error.Error == "Region location is reserved")
            {
                MainConsole.Instance.Error (
                    "[RegisterRegionWithGrid]: Registration of region with grid failed - The region location you specified is reserved. You must move your region.");
                int X;
                int Y;
                int.TryParse (MainConsole.Instance.Prompt ("New Region Location X", "1000"), out X);
                int.TryParse (MainConsole.Instance.Prompt ("New Region Location Y", "1000"), out Y);

                scene.RegionInfo.RegionLocX = X * Constants.RegionSize;
                scene.RegionInfo.RegionLocY = Y * Constants.RegionSize;

            } else if (error.Error == "Region overlaps another region")
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - The region location you specified is already in use. You must move your region.");
                int X;
                int Y;
                int.TryParse (
                    MainConsole.Instance.Prompt ("New Region Location X",
                        (scene.RegionInfo.RegionLocX / Constants.RegionSize).ToString ()), out X);
                int.TryParse (
                    MainConsole.Instance.Prompt ("New Region Location Y",
                        (scene.RegionInfo.RegionLocY  / Constants.RegionSize).ToString ()), out Y);

                scene.RegionInfo.RegionLocX = X * Constants.RegionSize;
                scene.RegionInfo.RegionLocY = Y * Constants.RegionSize;

            } else if (error.Error.Contains ("Can't move this region"))
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - You can not move this region. Moving it back to its original position.");
                //Opensim Grid Servers don't have this functionality.
                try
                {
                    string[] position = error.Error.Split (',');

                    scene.RegionInfo.RegionLocX = int.Parse (position [1]) * Constants.RegionSize;
                    scene.RegionInfo.RegionLocY = int.Parse (position [2]) * Constants.RegionSize;
                } catch (Exception)
                {
                    MainConsole.Instance.Error ("Unable to move the region back to its original position, is this an Opensim server? Please manually move the region back.");
                    throw;
                }

            } else if (error.Error == "Duplicate region name")
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - The region name you specified is already in use. Please change the name.");
                scene.RegionInfo.RegionName = MainConsole.Instance.Prompt ("New Region Name", "");

            } else if (error.Error == "Region locked out")
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid the failed - The region you are attempting to join has been blocked from connecting. Please connect another region.");
                MainConsole.Instance.Prompt ("Press enter when you are ready to exit");
                Environment.Exit (0);

            } else if (error.Error == "Could not reach grid service")
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - The grid service can not be found! Please make sure that you can connect to the grid server and that the grid server is on.");
                MainConsole.Instance.Error (
                    "You should also make sure you've provided the correct address and port of the grid service.");
                string input =
                    MainConsole.Instance.Prompt (
                        "Press enter when you are ready to proceed, or type cancel to exit");
                if (input == "cancel")
                {
                    Environment.Exit (0);
                }

            } else if (error.Error == "Wrong Session ID")
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - Wrong Session ID for this region!");
                MainConsole.Instance.Error (
                    "This means that this region has failed to connect to the grid server and needs removed from it before it can connect again.");
                MainConsole.Instance.Error (
                    "If you are running the WhiteCore.Server instance this region is connecting to, type \"grid clear region <RegionName>\" and then press enter on this console and it will work");
                MainConsole.Instance.Error (
                    "If you are not running the WhiteCore.Server instance this region is connecting to, please contact your grid operator so that he can fix it");

                string input =
                    MainConsole.Instance.Prompt (
                        "Press enter when you are ready to proceed, or type cancel to exit");
                if (input == "cancel")
                    Environment.Exit (0);

            } else if (error.Error == "Grid is not fully ready yet, please try again shortly")
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - " + error.Error + ", retrying... ");
                System.Threading.Thread.Sleep (3000);   //Sleep for a bit and try again
            } else
            {
                MainConsole.Instance.Error ("[RegisterRegionWithGrid]: Registration of region " +
                    scene.RegionInfo.RegionName +
                    " with the grid failed - " + error.Error + "!");
                string input =
                    MainConsole.Instance.Prompt (
                        "Press enter when you are ready to proceed, or type cancel to exit");
                if (input == "cancel")
                    Environment.Exit (0);
            }

            return RegisterRegionWithGrid (scene, true, continueTrying, password);
        }