/**
         * 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 CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out CreateAgentResponse response)
        {
            response = null;
            CreateAgentRequest request = new CreateAgentRequest();
            request.CircuitData = aCircuit;
            request.Destination = destination;
            request.TeleportFlags = teleportFlags;

            AutoResetEvent resetEvent = new AutoResetEvent(false);
            OSDMap result = null;
            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 IsAuthorizedForRegion(GridRegion region, AgentCircuitData agent, bool isRootAgent, out string reason)
 {
     ISceneManager manager = m_registry.RequestModuleInterface<ISceneManager>();
     if (manager != null && manager.Scene != null && manager.Scene.RegionInfo.RegionID == region.RegionID)
     {
         //Found the region, check permissions
         return manager.Scene.Permissions.AllowedIncomingAgent(agent, isRootAgent, out reason);
     }
     reason = "Not Authorized as region does not exist.";
     return false;
 }
        public void setup()
        {

            AgentId1 = UUID.Random();
            AgentId2 = UUID.Random();
            circuitcode1 = (uint) rnd.Next((int)uint.MinValue, int.MaxValue);
            circuitcode2 = (uint) rnd.Next((int)uint.MinValue, int.MaxValue);
            SessionId1 = UUID.Random();
            SessionId2 = UUID.Random();
            UUID BaseFolder = UUID.Random();
            string CapsPath = "http://www.opensimulator.org/Caps/Foo";
            Dictionary<ulong,string> ChildrenCapsPaths = new Dictionary<ulong, string>();
            ChildrenCapsPaths.Add(ulong.MaxValue, "http://www.opensimulator.org/Caps/Foo2");
            string firstname = "CoolAvatarTest";
            string lastname = "test";
            Vector3 StartPos = new Vector3(5, 23, 125);

            UUID SecureSessionId = UUID.Random();
            // TODO: unused: UUID SessionId = UUID.Random();

            m_agentCircuitData1 = new AgentCircuitData();
            m_agentCircuitData1.AgentID = AgentId1;
            m_agentCircuitData1.Appearance = new AvatarAppearance();
            m_agentCircuitData1.BaseFolder = BaseFolder;
            m_agentCircuitData1.CapsPath = CapsPath;
            m_agentCircuitData1.child = false;
            m_agentCircuitData1.ChildrenCapSeeds = ChildrenCapsPaths;
            m_agentCircuitData1.circuitcode = circuitcode1;
            m_agentCircuitData1.firstname = firstname;
            m_agentCircuitData1.InventoryFolder = BaseFolder;
            m_agentCircuitData1.lastname = lastname;
            m_agentCircuitData1.SecureSessionID = SecureSessionId;
            m_agentCircuitData1.SessionID = SessionId1;
            m_agentCircuitData1.startpos = StartPos;

            m_agentCircuitData2 = new AgentCircuitData();
            m_agentCircuitData2.AgentID = AgentId2;
            m_agentCircuitData2.Appearance = new AvatarAppearance();
            m_agentCircuitData2.BaseFolder = BaseFolder;
            m_agentCircuitData2.CapsPath = CapsPath;
            m_agentCircuitData2.child = false;
            m_agentCircuitData2.ChildrenCapSeeds = ChildrenCapsPaths;
            m_agentCircuitData2.circuitcode = circuitcode2;
            m_agentCircuitData2.firstname = firstname;
            m_agentCircuitData2.InventoryFolder = BaseFolder;
            m_agentCircuitData2.lastname = lastname;
            m_agentCircuitData2.SecureSessionID = SecureSessionId;
            m_agentCircuitData2.SessionID = SessionId2;
            m_agentCircuitData2.startpos = StartPos;
        }
        public bool RetrieveAgent(GridRegion destination, UUID agentID, bool agentIsLeaving, out AgentData agentData,
            out AgentCircuitData circuitData)
        {
            agentData = null;
            circuitData = null;

            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.IncomingRetrieveRootAgent(Scene, agentID, agentIsLeaving, out agentData,
                                                                out circuitData);
            return false;
            //MainConsole.Instance.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
        }
Exemplo n.º 6
0
        /// <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="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 virtual bool AuthorizeUser(AgentCircuitData agent, out string reason)
        {
            reason = String.Empty;

            if (!m_strictAccessControl) return true; //No checking if we don't do access control
            if (Permissions.IsGod(agent.AgentID)) return true;
                      
            if (AuthorizationService != null)
            {
                if (!AuthorizationService.IsAuthorizedForRegion(agent.AgentID.ToString(), RegionInfo.RegionID.ToString(),out reason))
                {
                    m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
                                     agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
                    //reason = String.Format("You are not currently on the access list for {0}",RegionInfo.RegionName);
                    return false;
                }
            }

            return true;
        }
       public void TestAgentCircuitDataOSDConversion()
       {
           AgentCircuitData Agent1Data = new AgentCircuitData();
           Agent1Data.AgentID = AgentId;
           Agent1Data.Appearance = AvAppearance;
           Agent1Data.BaseFolder = BaseFolder;
           Agent1Data.CapsPath = CapsPath;
           Agent1Data.child = false;
           Agent1Data.ChildrenCapSeeds = ChildrenCapsPaths;
           Agent1Data.circuitcode = circuitcode;
           Agent1Data.firstname = firstname;
           Agent1Data.InventoryFolder = BaseFolder;
           Agent1Data.lastname = lastname;
           Agent1Data.SecureSessionID = SecureSessionId;
           Agent1Data.SessionID = SessionId;
           Agent1Data.startpos = StartPos;

            OSDMap map2;
            OSDMap map = Agent1Data.PackAgentCircuitData();
            try
            {
                string str = OSDParser.SerializeJsonString(map);
                //System.Console.WriteLine(str);
                map2 = (OSDMap) OSDParser.DeserializeJson(str);
            } 
            catch (System.NullReferenceException)
            {
                //spurious litjson errors :P
                map2 = map;
                Assert.That(1==1);
                return;
            }

           AgentCircuitData Agent2Data = new AgentCircuitData();
           Agent2Data.UnpackAgentCircuitData(map2);

           Assert.That((Agent1Data.AgentID == Agent2Data.AgentID));
           Assert.That((Agent1Data.BaseFolder == Agent2Data.BaseFolder));

           Assert.That((Agent1Data.CapsPath == Agent2Data.CapsPath));
           Assert.That((Agent1Data.child == Agent2Data.child));
           Assert.That((Agent1Data.ChildrenCapSeeds.Count == Agent2Data.ChildrenCapSeeds.Count));
           Assert.That((Agent1Data.circuitcode == Agent2Data.circuitcode));
           Assert.That((Agent1Data.firstname == Agent2Data.firstname));
           Assert.That((Agent1Data.InventoryFolder == Agent2Data.InventoryFolder));
           Assert.That((Agent1Data.lastname == Agent2Data.lastname));
           Assert.That((Agent1Data.SecureSessionID == Agent2Data.SecureSessionID));
           Assert.That((Agent1Data.SessionID == Agent2Data.SessionID));
           Assert.That((Agent1Data.startpos == Agent2Data.startpos));

           /*
            Enable this once VisualParams go in the packing method
           for (int i = 0; i < 208; i++)
               Assert.That((Agent1Data.Appearance.VisualParams[i] == Agent2Data.Appearance.VisualParams[i]));
           */


        }
Exemplo n.º 8
0
 private bool CheckEstateGroups (EstateSettings ES, AgentCircuitData agent)
 {
     IGroupsModule gm = m_scenes.Count == 0 ? null : m_scenes[0].RequestModuleInterface<IGroupsModule>();
     if(gm != null && ES.EstateGroups.Length > 0)
     {
         List<UUID> esGroups = new List<UUID>(ES.EstateGroups);
         GroupMembershipData[] gmds = gm.GetMembershipData(agent.AgentID);
         foreach(GroupMembershipData gmd in gmds)
         {
             if(esGroups.Contains(gmd.GroupID))
                 return true;
         }
     }
     return false;
 }
        public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID,
                                   string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP)
        {
            bool success = false;
            UUID session = UUID.Random();

            m_log.InfoFormat("[LLOGIN SERVICE]: Login request for {0} {1} at {2} using viewer {3}, channel {4}, IP {5}, Mac {6}, Id0 {7}",
                             firstName, lastName, startLocation, clientVersion, channel, clientIP.Address.ToString(), mac, id0);

            try
            {
                //
                // Check client
                //
                if (m_AllowedClients != string.Empty)
                {
                    Regex arx = new Regex(m_AllowedClients);
                    Match am  = arx.Match(clientVersion);

                    if (!am.Success)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is not allowed",
                            firstName, lastName, clientVersion);
                        return(LLFailedLoginResponse.LoginBlockedProblem);
                    }
                }

                if (m_DeniedClients != string.Empty)
                {
                    Regex drx = new Regex(m_DeniedClients);
                    Match dm  = drx.Match(clientVersion);

                    if (dm.Success)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is denied",
                            firstName, lastName, clientVersion);
                        return(LLFailedLoginResponse.LoginBlockedProblem);
                    }
                }

                //
                // Get the account and check that it exists
                //
                UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName);
                if (account == null)
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user not found", firstName, lastName);
                    return(LLFailedLoginResponse.UserProblem);
                }

                if (account.UserLevel < m_MinLoginLevel)
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user level is {2} but minimum login level is {3}",
                        firstName, lastName, account.UserLevel, m_MinLoginLevel);
                    return(LLFailedLoginResponse.LoginBlockedProblem);
                }

                // If a scope id is requested, check that the account is in
                // that scope, or unscoped.
                //
                if (scopeID != UUID.Zero)
                {
                    if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed, reason: user {0} {1} not found", firstName, lastName);
                        return(LLFailedLoginResponse.UserProblem);
                    }
                }
                else
                {
                    scopeID = account.ScopeID;
                }

                //
                // Authenticate this user
                //
                if (!passwd.StartsWith("$1$"))
                {
                    passwd = "$1$" + Util.Md5Hash(passwd);
                }
                passwd = passwd.Remove(0, 3); //remove $1$
                string token         = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
                UUID   secureSession = UUID.Zero;
                if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: authentication failed",
                        firstName, lastName);
                    return(LLFailedLoginResponse.UserProblem);
                }

                //
                // Get the user's inventory
                //
                if (m_RequireInventory && m_InventoryService == null)
                {
                    m_log.WarnFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: inventory service not set up",
                        firstName, lastName);
                    return(LLFailedLoginResponse.InventoryProblem);
                }

                if (m_HGInventoryService != null)
                {
                    // Give the Suitcase service a chance to create the suitcase folder.
                    // (If we're not using the Suitcase inventory service then this won't do anything.)
                    m_HGInventoryService.GetRootFolder(account.PrincipalID);
                }

                List <InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
                if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed, for {0} {1}, reason: unable to retrieve user inventory",
                        firstName, lastName);
                    return(LLFailedLoginResponse.InventoryProblem);
                }

                // Get active gestures
                List <InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
                //                m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);

                //
                // Login the presence
                //
                if (m_PresenceService != null)
                {
                    success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);

                    if (!success)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: could not login presence",
                            firstName, lastName);
                        return(LLFailedLoginResponse.GridProblem);
                    }
                }

                //
                // Change Online status and get the home region
                //
                GridRegion   home   = null;
                GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString());

                // We are only going to complain about no home if the user actually tries to login there, to avoid
                // spamming the console.
                if (guinfo != null)
                {
                    if (guinfo.HomeRegionID == UUID.Zero && startLocation == "home")
                    {
                        m_log.WarnFormat(
                            "[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location but they have none set",
                            account.Name);
                    }
                    else if (m_GridService != null)
                    {
                        home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);

                        if (home == null && startLocation == "home")
                        {
                            m_log.WarnFormat(
                                "[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location with ID {1} but this was not found.",
                                account.Name, guinfo.HomeRegionID);
                        }
                    }
                }
                else
                {
                    // something went wrong, make something up, so that we don't have to test this anywhere else
                    m_log.DebugFormat("{0} Failed to fetch GridUserInfo. Creating empty GridUserInfo as home", LogHeader);
                    guinfo = new GridUserInfo();
                    guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
                }

                //
                // Find the destination region/grid
                //
                string where = string.Empty;
                Vector3       position   = Vector3.Zero;
                Vector3       lookAt     = Vector3.Zero;
                GridRegion    gatekeeper = null;
                TeleportFlags flags;
                GridRegion    destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags);
                if (destination == null)
                {
                    m_PresenceService.LogoutAgent(session);

                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: destination not found",
                        firstName, lastName);
                    return(LLFailedLoginResponse.GridProblem);
                }
                else
                {
                    m_log.DebugFormat(
                        "[LLOGIN SERVICE]: Found destination {0}, endpoint {1} for {2} {3}",
                        destination.RegionName, destination.ExternalEndPoint, firstName, lastName);
                }

                if (account.UserLevel >= 200)
                {
                    flags |= TeleportFlags.Godlike;
                }
                //
                // Get the avatar
                //
                AvatarAppearance avatar = null;
                if (m_AvatarService != null)
                {
                    avatar = m_AvatarService.GetAppearance(account.PrincipalID);
                }

                //
                // Instantiate/get the simulation interface and launch an agent at the destination
                //
                string           reason = string.Empty;
                GridRegion       dest;
                AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where,
                                                              clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest);
                destination = dest;
                if (aCircuit == null)
                {
                    m_PresenceService.LogoutAgent(session);
                    m_log.InfoFormat("[LLOGIN SERVICE]: Login failed for {0} {1}, reason: {2}", firstName, lastName, reason);
                    return(new LLFailedLoginResponse("key", reason, "false"));
                }
                // Get Friends list
                FriendInfo[] friendsList = new FriendInfo[0];
                if (m_FriendsService != null)
                {
                    friendsList = m_FriendsService.GetFriends(account.PrincipalID);
                    //                    m_log.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
                }

                //
                // Finally, fill out the response and return it
                //
                LLLoginResponse response
                    = new LLLoginResponse(
                          account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
                          where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP,
                          m_MapTileURL, m_ProfileURL, m_OpenIDURL, m_SearchURL, m_Currency, m_DSTZone,
                          m_DestinationGuide, m_AvatarPicker, m_ClassifiedFee);

                m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to {0} {1}", firstName, lastName);

                return(response);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace);
                if (m_PresenceService != null)
                {
                    m_PresenceService.LogoutAgent(session);
                }
                return(LLFailedLoginResponse.InternalError);
            }
        }
Exemplo n.º 10
0
 private bool CanTeleport(UUID userID, Scene scene, Vector3 Position, AgentCircuitData ACD, out Vector3 newPosition, out string reason)
 {
     newPosition = Position;
     reason = "";
     DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
     if (m_bypassPermissions) return m_bypassPermissionsValue;
     return true;
 }
Exemplo n.º 11
0
 protected bool LaunchAgentDirectly(GridRegion region, ref AgentCircuitData aCircuit, out string reason)
 {
     return m_registry.RequestModuleInterface<IAgentProcessing> ().LoginAgent (region, ref aCircuit, out reason);
 }
        public void TestCrossOnSameSimulator()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            UUID userId = TestHelpers.ParseTail(0x1);

//            TestEventQueueGetModule eqmA = new TestEventQueueGetModule();
            EntityTransferModule           etmA = new EntityTransferModule();
            EntityTransferModule           etmB = new EntityTransferModule();
            LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);
//            IConfig entityTransferConfig = config.AddConfig("EntityTransfer");

            // In order to run a single threaded regression test we do not want the entity transfer module waiting
            // for a callback from the destination scene before removing its avatar data.
//            entityTransferConfig.Set("wait_for_callback", false);

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA);
//            SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA, eqmA);
            SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB);

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(userId);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence originalSp = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            originalSp.AbsolutePosition = new Vector3(128, 32, 10);

//            originalSp.Flying = true;

//            Console.WriteLine("First pos {0}", originalSp.AbsolutePosition);

//            eqmA.ClearEvents();

            AgentUpdateArgs moveArgs = new AgentUpdateArgs();

            //moveArgs.BodyRotation = Quaternion.CreateFromEulers(Vector3.Zero);
            moveArgs.BodyRotation = Quaternion.CreateFromEulers(new Vector3(0, 0, (float)-(Math.PI / 2)));
            moveArgs.ControlFlags = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS;
            moveArgs.SessionID    = acd.SessionID;

            originalSp.HandleAgentUpdate(originalSp.ControllingClient, moveArgs);

            sceneA.Update(1);

//            Console.WriteLine("Second pos {0}", originalSp.AbsolutePosition);

            // FIXME: This is a sufficient number of updates to for the presence to reach the northern border.
            // But really we want to do this in a more robust way.
            for (int i = 0; i < 100; i++)
            {
                sceneA.Update(1);
//                Console.WriteLine("Pos {0}", originalSp.AbsolutePosition);
            }

            // Need to sort processing of EnableSimulator message on adding scene presences before we can test eqm
            // messages
//            Dictionary<UUID, List<TestEventQueueGetModule.Event>> eqmEvents = eqmA.Events;
//
//            Assert.That(eqmEvents.Count, Is.EqualTo(1));
//            Assert.That(eqmEvents.ContainsKey(originalSp.UUID), Is.True);
//
//            List<TestEventQueueGetModule.Event> spEqmEvents = eqmEvents[originalSp.UUID];
//
//            Assert.That(spEqmEvents.Count, Is.EqualTo(1));
//            Assert.That(spEqmEvents[0].Name, Is.EqualTo("CrossRegion"));

            // sceneA should now only have a child agent
            ScenePresence spAfterCrossSceneA = sceneA.GetScenePresence(originalSp.UUID);

            Assert.That(spAfterCrossSceneA.IsChildAgent, Is.True);

            ScenePresence spAfterCrossSceneB = sceneB.GetScenePresence(originalSp.UUID);

            // Agent remains a child until the client triggers complete movement
            Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True);

            TestClient sceneBTc = ((TestClient)spAfterCrossSceneB.ControllingClient);

            int agentMovementCompleteReceived = 0;

            sceneBTc.OnReceivedMoveAgentIntoRegion += (ri, pos, look) => agentMovementCompleteReceived++;

            sceneBTc.CompleteMovement();

            Assert.That(agentMovementCompleteReceived, Is.EqualTo(1));
            Assert.That(spAfterCrossSceneB.IsChildAgent, Is.False);
        }
Exemplo n.º 13
0
        public void TestSameSimulatorNeighbouringRegionsV1()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            UUID userId = TestHelpers.ParseTail(0x1);

            EntityTransferModule           etmA = new EntityTransferModule();
            EntityTransferModule           etmB = new EntityTransferModule();
            LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);
            IConfig entityTransferConfig = config.AddConfig("EntityTransfer");

            // In order to run a single threaded regression test we do not want the entity transfer module waiting
            // for a callback from the destination scene before removing its avatar data.
            entityTransferConfig.Set("wait_for_callback", false);

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA);
            SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB);

            // FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour
            lscm.ServiceVersion = "SIMULATION/0.1";

            Vector3 teleportPosition = new Vector3(10, 11, 12);
            Vector3 teleportLookAt   = new Vector3(20, 21, 22);

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(userId);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence beforeSceneASp = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            beforeSceneASp.AbsolutePosition = new Vector3(30, 31, 32);

            Assert.That(beforeSceneASp, Is.Not.Null);
            Assert.That(beforeSceneASp.IsChildAgent, Is.False);

            ScenePresence beforeSceneBSp = sceneB.GetScenePresence(userId);

            Assert.That(beforeSceneBSp, Is.Not.Null);
            Assert.That(beforeSceneBSp.IsChildAgent, Is.True);

            // In this case, we will not receieve a second InformClientOfNeighbour since the viewer already knows
            // about the neighbour region it is teleporting to.
            sceneA.RequestTeleportLocation(
                beforeSceneASp.ControllingClient,
                sceneB.RegionInfo.RegionHandle,
                teleportPosition,
                teleportLookAt,
                (uint)TeleportFlags.ViaLocation);

            destinationTestClients[0].CompleteMovement();

            ScenePresence afterSceneASp = sceneA.GetScenePresence(userId);

            Assert.That(afterSceneASp, Is.Not.Null);
            Assert.That(afterSceneASp.IsChildAgent, Is.True);

            ScenePresence afterSceneBSp = sceneB.GetScenePresence(userId);

            Assert.That(afterSceneBSp, Is.Not.Null);
            Assert.That(afterSceneBSp.IsChildAgent, Is.False);
            Assert.That(afterSceneBSp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneB.RegionInfo.RegionName));
            Assert.That(afterSceneBSp.AbsolutePosition, Is.EqualTo(teleportPosition));

            Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(0));
            Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(1));
            Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(1));
            Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0));

            // TODO: Add assertions to check correct circuit details in both scenes.

            // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera
            // position instead).
//            Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt));

//            TestHelpers.DisableLogging();
        }
Exemplo n.º 14
0
        public bool LoginAgentToGrid(AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, IPEndPoint clientIP, out string reason)
        {
            MainConsole.Instance.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} (@{1}) to grid {2}",
                                             agentCircuit.AgentID, ((clientIP == null) ? "stored IP" : clientIP.Address.ToString()), gatekeeper.ServerURI);
            // Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
            GridRegion region = new GridRegion();

            region.FromOSD(gatekeeper.ToOSD());
            region.ServerURI        = gatekeeper.ServerURI;
            region.ExternalHostName = finalDestination.ExternalHostName;
            region.InternalEndPoint = finalDestination.InternalEndPoint;
            region.RegionName       = finalDestination.RegionName;
            region.RegionID         = finalDestination.RegionID;
            region.RegionLocX       = finalDestination.RegionLocX;
            region.RegionLocY       = finalDestination.RegionLocY;

            // Generate a new service session
            agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
            TravelingAgentInfo old = UpdateTravelInfo(agentCircuit, region);

            bool   success      = false;
            string myExternalIP = string.Empty;
            string gridName     = gatekeeper.ServerURI;

            MainConsole.Instance.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}", m_GridName, gridName);

            if (m_GridName == gridName)
            {
                success = m_GatekeeperService.LoginAgent(agentCircuit, finalDestination, out reason);
            }
            else
            {
                success = m_GatekeeperConnector.CreateAgent(region, agentCircuit, (uint)TeleportFlags.ViaLogin, out myExternalIP, out reason);
                if (success)
                {
                    // Report them as nowhere with the LOGIN_STATUS_LOCKED so that they don't get logged out automatically after an hour of not responding via HG
                    m_PresenceService.SetLastPosition(agentCircuit.AgentID.ToString(), AgentInfoHelpers.LOGIN_STATUS_LOCKED, Vector3.Zero, Vector3.Zero);
                }
            }

            if (!success)
            {
                MainConsole.Instance.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} to grid {1}, reason: {2}",
                                                 agentCircuit.AgentID, region.ServerURI, reason);

                // restore the old travel info
                lock (m_TravelingAgents)
                {
                    if (old == null)
                    {
                        m_TravelingAgents.Remove(agentCircuit.SessionID);
                    }
                    else
                    {
                        m_TravelingAgents[agentCircuit.SessionID] = old;
                    }
                }

                return(false);
            }
            else
            {
                reason = "";
            }

            MainConsole.Instance.DebugFormat("[USER AGENT SERVICE]: Gatekeeper sees me as {0}", myExternalIP);
            // else set the IP addresses associated with this client
            if (clientIP != null)
            {
                m_TravelingAgents[agentCircuit.SessionID].ClientIPAddress = clientIP.Address.ToString();
            }
            m_TravelingAgents[agentCircuit.SessionID].MyIpAddress = myExternalIP;

            return(true);
        }
Exemplo n.º 15
0
 public bool LoginAgentToGrid(AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
 {
     reason = string.Empty;
     return(LoginAgentToGrid(agentCircuit, gatekeeper, finalDestination, null, out reason));
 }
Exemplo n.º 16
0
 private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, IPEndPoint clientIP, out string reason)
 {
     m_log.Debug("[LLOGIN SERVICE] Launching agent at " + destination.RegionName);
     if (m_UserAgentService.LoginAgentToGrid(null, aCircuit, gatekeeper, destination, true, out reason))
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 17
0
 private bool LaunchAgentDirectly(ISimulationService simConnector, GridRegion region, AgentCircuitData aCircuit, TeleportFlags flags, out string reason)
 {
     return(simConnector.CreateAgent(null, region, aCircuit, (uint)flags, out reason));
 }
Exemplo n.º 18
0
        protected AgentCircuitData LaunchAgentAtGrid(GridRegion gatekeeper, GridRegion destination, UserAccount account, AvatarAppearance avatar,
                                                     UUID session, UUID secureSession, Vector3 position, string currentWhere, string viewer, string channel, string mac, string id0,
                                                     IPEndPoint clientIP, TeleportFlags flags, out string where, out string reason, out GridRegion dest)
        {
            where = currentWhere;
            ISimulationService simConnector = null;

            reason = string.Empty;
            uint             circuitCode = 0;
            AgentCircuitData aCircuit    = null;

            if (m_UserAgentService == null)
            {
                // HG standalones have both a localSimulatonDll and a remoteSimulationDll
                // non-HG standalones have just a localSimulationDll
                // independent login servers have just a remoteSimulationDll
                if (m_LocalSimulationService != null)
                {
                    simConnector = m_LocalSimulationService;
                }
                else if (m_RemoteSimulationService != null)
                {
                    simConnector = m_RemoteSimulationService;
                }
            }
            else // User Agent Service is on
            {
                if (gatekeeper == null) // login to local grid
                {
                    if (hostName == string.Empty)
                    {
                        SetHostAndPort(m_GatekeeperURL);
                    }

                    gatekeeper = new GridRegion(destination);
                    gatekeeper.ExternalHostName = hostName;
                    gatekeeper.HttpPort         = (uint)port;
                    gatekeeper.ServerURI        = m_GatekeeperURL;
                }
                m_log.Debug("[LLLOGIN SERVICE]: no gatekeeper detected..... using " + m_GatekeeperURL);
            }

            bool success = false;

            if (m_UserAgentService == null && simConnector != null)
            {
                circuitCode = (uint)Util.RandomClass.Next();;
                aCircuit    = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0);
                success     = LaunchAgentDirectly(simConnector, destination, aCircuit, flags, out reason);
                if (!success && m_GridService != null)
                {
                    // Try the fallback regions
                    List <GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
                    if (fallbacks != null)
                    {
                        foreach (GridRegion r in fallbacks)
                        {
                            success = LaunchAgentDirectly(simConnector, r, aCircuit, flags | TeleportFlags.ViaRegionID, out reason);
                            if (success)
                            {
                                where       = "safe";
                                destination = r;
                                break;
                            }
                        }
                    }
                }
            }

            if (m_UserAgentService != null)
            {
                circuitCode             = (uint)Util.RandomClass.Next();;
                aCircuit                = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0);
                aCircuit.teleportFlags |= (uint)flags;
                success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, clientIP, out reason);
                if (!success && m_GridService != null)
                {
                    // Try the fallback regions
                    List <GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
                    if (fallbacks != null)
                    {
                        foreach (GridRegion r in fallbacks)
                        {
                            success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, clientIP, out reason);
                            if (success)
                            {
                                where       = "safe";
                                destination = r;
                                break;
                            }
                        }
                    }
                }
            }
            dest = destination;
            if (success)
            {
                return(aCircuit);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 19
0
        public void TestCrossOnSameSimulatorPrimLimitsOkay()
        {
            TestHelpers.InMethod();
            //            TestHelpers.EnableLogging();

            UUID userId            = TestHelpers.ParseTail(0x1);
            int  sceneObjectIdTail = 0x2;

            EntityTransferModule           etmA = new EntityTransferModule();
            EntityTransferModule           etmB = new EntityTransferModule();
            LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
            LandManagementModule           lmmA = new LandManagementModule();
            LandManagementModule           lmmB = new LandManagementModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);

            IConfig permissionsConfig = config.AddConfig("Permissions");

            permissionsConfig.Set("permissionmodules", "PrimLimitsModule");

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(
                sceneA, config, etmA, lmmA, new PrimLimitsModule(), new PrimCountModule());
            SceneHelpers.SetupSceneModules(
                sceneB, config, etmB, lmmB, new PrimLimitsModule(), new PrimCountModule());

            // We must set up the parcel for this to work.  Normally this is taken care of by OpenSimulator startup
            // code which is not yet easily invoked by tests.
            lmmA.EventManagerOnNoLandDataFromStorage();
            lmmB.EventManagerOnNoLandDataFromStorage();

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(userId);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);
            ScenePresence sp1SceneA = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            SceneObjectGroup so1   = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
            UUID             so1Id = so1.UUID;

            so1.AbsolutePosition = new Vector3(128, 10, 20);

            // Cross with a negative value.  We must make this call rather than setting AbsolutePosition directly
            // because only this will execute permission checks in the source region.
            sceneA.SceneGraph.UpdatePrimGroupPosition(so1.LocalId, new Vector3(128, -10, 20), sp1SceneA.ControllingClient);

            // crossing is async
            Thread.Sleep(500);

            Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id));
            Assert.NotNull(sceneB.GetSceneObjectGroup(so1Id));
        }
Exemplo n.º 20
0
        public void TestSameSimulatorNeighbouringRegionsV2()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            UUID userId = TestHelpers.ParseTail(0x1);

            EntityTransferModule           etmA = new EntityTransferModule();
            EntityTransferModule           etmB = new EntityTransferModule();
            LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA);
            SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB);

            Vector3 teleportPosition = new Vector3(10, 11, 12);
            Vector3 teleportLookAt   = new Vector3(20, 21, 22);

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(userId);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence beforeSceneASp = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            beforeSceneASp.AbsolutePosition = new Vector3(30, 31, 32);

            Assert.That(beforeSceneASp, Is.Not.Null);
            Assert.That(beforeSceneASp.IsChildAgent, Is.False);

            ScenePresence beforeSceneBSp = sceneB.GetScenePresence(userId);

            Assert.That(beforeSceneBSp, Is.Not.Null);
            Assert.That(beforeSceneBSp.IsChildAgent, Is.True);

            // Here, we need to make clientA's receipt of SendRegionTeleport trigger clientB's CompleteMovement().  This
            // is to operate the teleport V2 mechanism where the EntityTransferModule will first request the client to
            // CompleteMovement to the region and then call UpdateAgent to the destination region to confirm the receipt
            // Both these operations will occur on different threads and will wait for each other.
            // We have to do this via ThreadPool directly since FireAndForget has been switched to sync for the V1
            // test protocol, where we are trying to avoid unpredictable async operations in regression tests.
            tc.OnTestClientSendRegionTeleport
                += (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL)
                   => ThreadPool.UnsafeQueueUserWorkItem(o => destinationTestClients[0].CompleteMovement(), null);

            sceneA.RequestTeleportLocation(
                beforeSceneASp.ControllingClient,
                sceneB.RegionInfo.RegionHandle,
                teleportPosition,
                teleportLookAt,
                (uint)TeleportFlags.ViaLocation);

            ScenePresence afterSceneASp = sceneA.GetScenePresence(userId);

            Assert.That(afterSceneASp, Is.Not.Null);
            Assert.That(afterSceneASp.IsChildAgent, Is.True);

            ScenePresence afterSceneBSp = sceneB.GetScenePresence(userId);

            Assert.That(afterSceneBSp, Is.Not.Null);
            Assert.That(afterSceneBSp.IsChildAgent, Is.False);
            Assert.That(afterSceneBSp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneB.RegionInfo.RegionName));
            Assert.That(afterSceneBSp.AbsolutePosition, Is.EqualTo(teleportPosition));

            Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(0));
            Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(1));
            Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(1));
            Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0));

            // TODO: Add assertions to check correct circuit details in both scenes.

            // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera
            // position instead).
//            Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt));

//            TestHelpers.DisableLogging();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Add a new Caps Service for the given region if one does not already exist
        /// </summary>
        /// <param name="regionHandle"></param>
        protected void AddCapsServiceForRegion(ulong regionHandle, string CAPSBase, AgentCircuitData circuitData)
        {
            if (!m_RegionCapsServices.ContainsKey(regionHandle))
            {
                //Now add this client to the region caps
                //Create if needed
                m_CapsService.AddCapsForRegion(regionHandle);
                IRegionCapsService regionCaps = m_CapsService.GetCapsForRegion(regionHandle);

                PerRegionClientCapsService regionClient = new PerRegionClientCapsService();
                regionClient.Initialise(this, regionCaps, CAPSBase, circuitData);
                m_RegionCapsServices[regionHandle] = regionClient;

                //Now get and add them
                regionCaps.AddClientToRegion(regionClient);
            }
        }
Exemplo n.º 22
0
        private bool OnAllowedIncomingAgent(IScene scene, AgentCircuitData agent, bool isRootAgent, out string reason)
        {
            #region Incoming Agent Checks

            UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.AllScopeIDs, agent.AgentID);
            if (account == null)
            {
                reason = "No account exists";
                return(false);
            }
            IScenePresence Sp = scene.GetScenePresence(agent.AgentID);

            if (LoginsDisabled)
            {
                reason = "Logins Disabled";
                return(false);
            }

            //Check how long its been since the last TP
            if (m_enabledBlockTeleportSeconds && Sp != null && !Sp.IsChildAgent)
            {
                if (TimeSinceLastTeleport.ContainsKey(Sp.Scene.RegionInfo.RegionID))
                {
                    if (TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] > Util.UnixTimeSinceEpoch())
                    {
                        reason = "Too many teleports. Please try again soon.";
                        return(false); // Too soon since the last TP
                    }
                }
                TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] = Util.UnixTimeSinceEpoch() +
                                                                      ((int)(SecondsBeforeNextTeleport));
            }

            //Gods tp freely
            if ((Sp != null && Sp.GodLevel != 0) || (account != null && account.UserLevel != 0))
            {
                reason = "";
                return(true);
            }

            //Check whether they fit any ban criteria
            if (Sp != null)
            {
                foreach (string banstr in BanCriteria)
                {
                    if (Sp.Name.Contains(banstr))
                    {
                        reason = "You have been banned from this region.";
                        return(false);
                    }
                    else if (((IPEndPoint)Sp.ControllingClient.GetClientEP()).Address.ToString().Contains(banstr))
                    {
                        reason = "You have been banned from this region.";
                        return(false);
                    }
                }
                //Make sure they exist in the grid right now
                IAgentInfoService presence = scene.RequestModuleInterface <IAgentInfoService>();
                if (presence == null)
                {
                    reason =
                        String.Format(
                            "Failed to verify user presence in the grid for {0} in region {1}. Presence service does not exist.",
                            account.Name, scene.RegionInfo.RegionName);
                    return(false);
                }

                UserInfo pinfo = presence.GetUserInfo(agent.AgentID.ToString());

                if (pinfo == null || (!pinfo.IsOnline && ((agent.TeleportFlags & (uint)TeleportFlags.ViaLogin) == 0)))
                {
                    reason =
                        String.Format(
                            "Failed to verify user presence in the grid for {0}, access denied to region {1}.",
                            account.Name, scene.RegionInfo.RegionName);
                    return(false);
                }
            }

            EstateSettings ES = scene.RegionInfo.EstateSettings;

            IEntityCountModule entityCountModule = scene.RequestModuleInterface <IEntityCountModule>();
            if (entityCountModule != null && scene.RegionInfo.RegionSettings.AgentLimit
                < entityCountModule.RootAgents + 1 &&
                scene.RegionInfo.RegionSettings.AgentLimit > 0)
            {
                reason = "Too many agents at this time. Please come back later.";
                return(false);
            }

            List <EstateBan> EstateBans = new List <EstateBan>(ES.EstateBans);
            int i = 0;
            //Check bans
            foreach (EstateBan ban in EstateBans)
            {
                if (ban.BannedUserID == agent.AgentID)
                {
                    if (Sp != null)
                    {
                        string banIP = ((IPEndPoint)Sp.ControllingClient.GetClientEP()).Address.ToString();

                        if (ban.BannedHostIPMask != banIP) //If it changed, ban them again
                        {
                            //Add the ban with the new hostname
                            ES.AddBan(new EstateBan
                            {
                                BannedHostIPMask   = banIP,
                                BannedUserID       = ban.BannedUserID,
                                EstateID           = ban.EstateID,
                                BannedHostAddress  = ban.BannedHostAddress,
                                BannedHostNameMask = ban.BannedHostNameMask
                            });
                            //Update the database
                            Aurora.Framework.Utilities.DataManager.RequestPlugin <IEstateConnector>().
                            SaveEstateSettings(ES);
                        }
                    }

                    reason = "Banned from this region.";
                    return(false);
                }
                if (Sp != null)
                {
                    IPAddress   end  = Sp.ControllingClient.EndPoint;
                    IPHostEntry rDNS = null;
                    try
                    {
                        rDNS = Dns.GetHostEntry(end);
                    }
                    catch (SocketException)
                    {
                        MainConsole.Instance.WarnFormat("[IPBAN] IP address \"{0}\" cannot be resolved via DNS", end);
                        rDNS = null;
                    }
                    if (ban.BannedHostIPMask == agent.IPAddress ||
                        (rDNS != null && rDNS.HostName.Contains(ban.BannedHostIPMask)) ||
                        end.ToString().StartsWith(ban.BannedHostIPMask))
                    {
                        //Ban the new user
                        ES.AddBan(new EstateBan
                        {
                            EstateID           = ES.EstateID,
                            BannedHostIPMask   = agent.IPAddress,
                            BannedUserID       = agent.AgentID,
                            BannedHostAddress  = agent.IPAddress,
                            BannedHostNameMask = agent.IPAddress
                        });
                        Aurora.Framework.Utilities.DataManager.RequestPlugin <IEstateConnector>().
                        SaveEstateSettings(ES);

                        reason = "Banned from this region.";
                        return(false);
                    }
                }
                i++;
            }

            //Estate owners/managers/access list people/access groups tp freely as well
            if (ES.EstateOwner == agent.AgentID ||
                new List <UUID>(ES.EstateManagers).Contains(agent.AgentID) ||
                new List <UUID>(ES.EstateAccess).Contains(agent.AgentID) ||
                CheckEstateGroups(ES, agent))
            {
                reason = "";
                return(true);
            }

            if (ES.DenyAnonymous &&
                ((account.UserFlags & (int)IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile) ==
                 (int)IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile))
            {
                reason = "You may not enter this region.";
                return(false);
            }

            if (ES.DenyIdentified &&
                ((account.UserFlags & (int)IUserProfileInfo.ProfileFlags.PaymentInfoOnFile) ==
                 (int)IUserProfileInfo.ProfileFlags.PaymentInfoOnFile))
            {
                reason = "You may not enter this region.";
                return(false);
            }

            if (ES.DenyTransacted &&
                ((account.UserFlags & (int)IUserProfileInfo.ProfileFlags.PaymentInfoInUse) ==
                 (int)IUserProfileInfo.ProfileFlags.PaymentInfoInUse))
            {
                reason = "You may not enter this region.";
                return(false);
            }

            const long m_Day = 25 * 60 * 60; //Find out day length in seconds
            if (scene.RegionInfo.RegionSettings.MinimumAge != 0 &&
                (account.Created - Util.UnixTimeSinceEpoch()) < (scene.RegionInfo.RegionSettings.MinimumAge * m_Day))
            {
                reason = "You may not enter this region.";
                return(false);
            }

            if (!ES.PublicAccess)
            {
                reason = "You may not enter this region, Public access has been turned off.";
                return(false);
            }

            IAgentConnector AgentConnector = Framework.Utilities.DataManager.RequestPlugin <IAgentConnector>();
            IAgentInfo      agentInfo      = null;
            if (AgentConnector != null)
            {
                agentInfo = AgentConnector.GetAgent(agent.AgentID);
                if (agentInfo == null)
                {
                    AgentConnector.CreateNewAgent(agent.AgentID);
                    agentInfo = AgentConnector.GetAgent(agent.AgentID);
                }
            }

            if (m_checkMaturityLevel)
            {
                if (agentInfo != null &&
                    scene.RegionInfo.AccessLevel > Util.ConvertMaturityToAccessLevel((uint)agentInfo.MaturityRating))
                {
                    reason = "The region has too high of a maturity level. Blocking teleport.";
                    return(false);
                }

                if (agentInfo != null && ES.DenyMinors && (agentInfo.Flags & IAgentFlags.Minor) == IAgentFlags.Minor)
                {
                    reason = "The region has too high of a maturity level. Blocking teleport.";
                    return(false);
                }
            }

            #endregion

            reason = "";
            return(true);
        }
Exemplo n.º 23
0
 protected bool TryFindGridRegionForAgentLogin(List<GridRegion> regions, UserAccount account,
     AvatarAppearance appearance, UUID session, UUID secureSession, uint circuitCode, Vector3 position,
     IPEndPoint clientIP, AgentCircuitData aCircuit, out GridRegion destination)
 {
     foreach (GridRegion r in regions)
     {
         string reason;
         bool success = LaunchAgentDirectly(r, ref aCircuit, out reason);
         if (success)
         {
             aCircuit = MakeAgent(r, account, appearance, session, secureSession, circuitCode, position, clientIP);
             destination = r;
             return true;
         }
         else
             m_GridService.SetRegionUnsafe(r.RegionID);
     }
     destination = null;
     return false;
 }
Exemplo n.º 24
0
        private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint, out AgentCircuitData sessionInfo)
        {
            UUID agentID = useCircuitCode.CircuitCode.ID;
            UUID sessionID = useCircuitCode.CircuitCode.SessionID;
            uint circuitCode = useCircuitCode.CircuitCode.Code;

            sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode, remoteEndPoint);
            return sessionInfo != null;
        }
Exemplo n.º 25
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;
 }
Exemplo n.º 26
0
        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason)
        {
            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateAgent start");

            reason = String.Empty;
            if (destination == null)
            {
                m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Given destination is null");
                return(false);
            }

            string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/";

            try
            {
                OSDMap args = aCircuit.PackAgentCircuitData();

                args["destination_x"]    = OSD.FromString(destination.RegionLocX.ToString());
                args["destination_y"]    = OSD.FromString(destination.RegionLocY.ToString());
                args["destination_name"] = OSD.FromString(destination.RegionName);
                args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
                args["teleport_flags"]   = OSD.FromString(flags.ToString());

                OSDMap result  = WebUtil.PostToServiceCompressed(uri, args, 30000);
                bool   success = result["success"].AsBoolean();
                if (success && result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    reason  = data["reason"].AsString();
                    success = data["success"].AsBoolean();
                    return(success);
                }

                // Try the old version, uncompressed
                result = WebUtil.PostToService(uri, args, 30000);

                if (result["Success"].AsBoolean())
                {
                    if (result.ContainsKey("_Result"))
                    {
                        OSDMap data = (OSDMap)result["_Result"];

                        reason  = data["reason"].AsString();
                        success = data["success"].AsBoolean();
                        m_log.WarnFormat(
                            "[REMOTE SIMULATION CONNECTOR]: Remote simulator {0} did not accept compressed transfer, suggest updating it.", destination.RegionName);
                        return(success);
                    }
                }

                m_log.WarnFormat(
                    "[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {2}",
                    aCircuit.firstname, aCircuit.lastname, destination.RegionName);
                reason = result["Message"] != null ? result["Message"].AsString() : "error";
                return(false);
            }
            catch (Exception e)
            {
                m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString());
                reason = e.Message;
            }

            return(false);
        }
Exemplo n.º 27
0
 // The simulators call this interface
 public bool LoginAgentToGrid(GridRegion source, AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, out string reason)
 {
     return(LoginAgentToGrid(source, aCircuit, gatekeeper, destination, false, out reason));
 }
Exemplo n.º 28
0
/* Ubit not in use
 *      private AveragingClass m_heartbeatList = new AveragingClass (50);
 *      private int GetHeartbeatSleepTime (int timeBeatTook)
 *      {
 *          //Add it to the list of the last 50 heartbeats
 *
 *          m_heartbeatList.Add (timeBeatTook);
 *          int avgHeartBeat = (int)m_heartbeatList.GetAverage ();
 *
 *          //The heartbeat sleep time if time dilation is 1
 *          int normalHeartBeatSleepTime = (int)m_updatetimespan;
 *          if (avgHeartBeat + (m_physicstimespan / m_updatetimespan) > normalHeartBeatSleepTime)//Fudge a bit
 *              return 0;//It doesn't get any sleep
 *          int newAvgSleepTime = normalHeartBeatSleepTime - avgHeartBeat;
 *          //Console.WriteLine (newAvgSleepTime);
 *          return newAvgSleepTime - (int)(m_physicstimespan / m_updatetimespan);//Fudge a bit
 *      }
 */
        #endregion

        #region Add/Remove Avatar Methods

        /// <summary>
        /// Adding a New Client and Create a Presence for it.
        /// Called by the LLClientView when the UseCircuitCode packet comes in
        /// Used by NPCs to add themselves to the Scene
        /// </summary>
        /// <param name="client"></param>
        /// <param name="completed"></param>
        public void AddNewClient(IClientAPI client, BlankHandler completed)
        {
            try
            {
                System.Net.IPEndPoint ep       = (System.Net.IPEndPoint)client.GetClientEP();
                AgentCircuitData      aCircuit = AuthenticateHandler.AuthenticateSession(client.SessionId, client.AgentId, client.CircuitCode, ep);

                if (aCircuit == null) // no good, didn't pass NewUserConnection successfully
                {
                    completed();
                    return;
                }

                m_clientManager.Add(client);

                //Create the scenepresence
                IScenePresence sp = CreateAndAddChildScenePresence(client);
                sp.IsChildAgent = aCircuit.child;
                sp.DrawDistance = aCircuit.DrawDistance;

                //Trigger events
                m_eventManager.TriggerOnNewPresence(sp);

                //Make sure the appearanace is updated
                IAvatarAppearanceModule appearance = sp.RequestModuleInterface <IAvatarAppearanceModule>();
                if (appearance != null)
                {
                    appearance.Appearance = aCircuit.Appearance ?? sp.Scene.AvatarService.GetAppearance(sp.UUID);
                    if (appearance.Appearance == null)
                    {
                        MainConsole.Instance.Error("[Scene]: NO AVATAR APPEARANCE FOUND FOR " + sp.Name);
                        appearance.Appearance = new AvatarAppearance(sp.UUID);
                    }
                }

                if (GetScenePresence(client.AgentId) != null)
                {
                    EventManager.TriggerOnNewClient(client);
                    if ((aCircuit.teleportFlags & (uint)TeleportFlags.ViaLogin) != 0)
                    {
                        EventManager.TriggerOnClientLogin(client);
                    }
                }

                //Add the client to login stats
                ILoginMonitor monitor3 = (ILoginMonitor)RequestModuleInterface <IMonitorModule>().GetMonitor("", MonitorModuleHelper.LoginMonitor);
                if ((aCircuit.teleportFlags & (uint)TeleportFlags.ViaLogin) != 0 && monitor3 != null)
                {
                    monitor3.AddSuccessfulLogin();
                }

                if (sp.IsChildAgent)//If we're a child, trigger this so that we get updated in the modules
                {
                    sp.TriggerSignificantClientMovement();
                }
                completed();
            }
            catch (Exception ex)
            {
                MainConsole.Instance.Warn("[Scene]: Error in AddNewClient: " + ex);
            }
        }
Exemplo n.º 29
0
        public async Task<Tuple<bool, string>> DoCreateChildAgentCallAsync(SimpleRegionInfo regionInfo, AgentCircuitData aCircuit)
        {
            string uri = regionInfo.InsecurePublicHTTPServerURI + "/agent/" + aCircuit.AgentID + "/";

            HttpWebRequest agentCreateRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
            agentCreateRequest.Method = "POST";
            agentCreateRequest.ContentType = "application/json";
            agentCreateRequest.Timeout = AGENT_UPDATE_TIMEOUT;
            agentCreateRequest.ReadWriteTimeout = AGENT_UPDATE_TIMEOUT;
            agentCreateRequest.Headers["authorization"] = GenerateAuthorization();

            OSDMap args = null;
            try
            {
                args = aCircuit.PackAgentCircuitData();
            }
            catch (Exception e)
            {
                m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
                return Tuple.Create(false, "PackAgentCircuitData exception");
            }

            // Add the regionhandle of the destination region
            ulong regionHandle = GetRegionHandle(regionInfo.RegionHandle);
            args["destination_handle"] = OSD.FromString(regionHandle.ToString());

            string strBuffer = "";
            byte[] buffer = new byte[1];
            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                UTF8Encoding str = new UTF8Encoding();
                buffer = str.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
                return Tuple.Create(false, "Exception thrown on serialization of ChildCreate");
            }

            
            try
            { // send the Post
                agentCreateRequest.ContentLength = buffer.Length;   //Count bytes to send
                Stream os = await agentCreateRequest.GetRequestStreamAsync();

                await os.WriteAsync(buffer, 0, strBuffer.Length);         //Send it
                await os.FlushAsync();

                os.Close();
                //m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REST COMMS]: Unable to contact remote region {0}: {1}", regionInfo.RegionHandle, e.Message);
                return Tuple.Create(false, "cannot contact remote region");
            }
            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");

            try
            {
                WebResponse webResponse = await agentCreateRequest.GetResponseAsync(AGENT_UPDATE_TIMEOUT);
                if (webResponse == null)
                {
                    m_log.Warn("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
                    return Tuple.Create(false, "response from remote region was null");
                }

                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                string response = await sr.ReadToEndAsync();
                response.Trim();
                sr.Close();

                //m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response);
                if (String.IsNullOrEmpty(response))
                {
                    m_log.Info("[REST COMMS]: Empty response on DoCreateChildAgentCall post");
                    return Tuple.Create(false, "response from remote region was empty");
                }

                try
                {
                    // we assume we got an OSDMap back
                    OSDMap r = GetOSDMap(response);
                    bool success = r["success"].AsBoolean();
                    string reason = r["reason"].AsString();

                    return Tuple.Create(success, reason);
                }
                catch (NullReferenceException e)
                {
                    m_log.WarnFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message);

                    // check for old style response
                    if (response.ToLower().StartsWith("true"))
                        return Tuple.Create(true, "");

                    return Tuple.Create(false, "exception on reply of DoCreateChildAgentCall");
                }
            }
            catch (WebException ex)
            {
                m_log.WarnFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex);
                return Tuple.Create(false, "web exception");
            }
            catch (Exception ex)
            {
                m_log.WarnFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex);
                return Tuple.Create(false, "web exception");
            }
        }
Exemplo n.º 30
0
        private void OnGridInstantMessage(GridInstantMessage msg)
        {
            // The instant message module will only deliver messages of dialog types:
            // MessageFromAgent, StartTyping, StopTyping, MessageFromObject
            //
            // Any other message type will not be delivered to a client by the
            // Instant Message Module

            UUID regionID = new UUID(msg.RegionID);

            if (m_log.IsDebugEnabled)
            {
                m_log.DebugFormat("[GroupsMessagingModule]: {0} called, IM from region {1}",
                                  System.Reflection.MethodBase.GetCurrentMethod().Name, regionID);

                DebugGridInstantMessage(msg);
            }

            // Incoming message from a group
            if ((msg.fromGroup == true) && (msg.dialog == (byte)InstantMessageDialog.SessionSend))
            {
                // We have to redistribute the message across all members of the group who are here
                // on this sim

                UUID GroupID = new UUID(msg.imSessionID);

                Scene      aScene         = m_sceneList[0];
                GridRegion regionOfOrigin = aScene.GridService.GetRegionByUUID(aScene.RegionInfo.ScopeID, regionID);

                List <GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), GroupID);

                //if (m_log.IsDebugEnabled)
                //    foreach (GroupMembersData m in groupMembers)
                //        m_log.DebugFormat("[GroupsMessagingModule]: member {0}", m.AgentID);

                foreach (Scene s in m_sceneList)
                {
                    s.ForEachScenePresence(sp =>
                    {
                        // If we got this via grid messaging, it's because the caller thinks
                        // that the root agent is here. We should only send the IM to root agents.
                        if (sp.IsChildAgent)
                        {
                            return;
                        }

                        GroupMembersData m = groupMembers.Find(gmd => { return(gmd.AgentID == sp.UUID); });
                        if (m.AgentID == UUID.Zero)
                        {
                            if (m_log.IsDebugEnabled)
                            {
                                m_log.DebugFormat("[GroupsMessagingModule]: skipping agent {0} because he is not a member of the group", sp.UUID);
                            }
                            return;
                        }

                        // Check if the user has an agent in the region where
                        // the IM came from, and if so, skip it, because the IM
                        // was already sent via that agent
                        if (regionOfOrigin != null)
                        {
                            AgentCircuitData aCircuit = s.AuthenticateHandler.GetAgentCircuitData(sp.UUID);
                            if (aCircuit != null)
                            {
                                if (aCircuit.ChildrenCapSeeds.Keys.Contains(regionOfOrigin.RegionHandle))
                                {
                                    if (m_log.IsDebugEnabled)
                                    {
                                        m_log.DebugFormat("[GroupsMessagingModule]: skipping agent {0} because he has an agent in region of origin", sp.UUID);
                                    }
                                    return;
                                }
                                else
                                {
                                    if (m_log.IsDebugEnabled)
                                    {
                                        m_log.DebugFormat("[GroupsMessagingModule]: not skipping agent {0}", sp.UUID);
                                    }
                                }
                            }
                        }

                        UUID AgentID  = sp.UUID;
                        msg.toAgentID = AgentID.Guid;

                        if (!hasAgentDroppedGroupChatSession(AgentID.ToString(), GroupID))
                        {
                            if (!hasAgentBeenInvitedToGroupChatSession(AgentID.ToString(), GroupID))
                            {
                                AddAgentToSession(AgentID, GroupID, msg);
                            }
                            else
                            {
                                if (m_log.IsDebugEnabled)
                                {
                                    m_log.DebugFormat("[GroupsMessagingModule]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", sp.Name);
                                }

                                ProcessMessageFromGroupSession(msg);
                            }
                        }
                    });
                }
            }
        }
Exemplo n.º 31
0
 /// <summary>
 /// Temporarily override session authentication for tests (namely teleport).
 /// </summary>
 /// <remarks>
 /// TODO: This needs to be mocked out properly.
 /// </remarks>
 /// <param name="agent"></param>
 /// <returns></returns>
 public override bool VerifyUserPresence(AgentCircuitData agent, out string reason)
 {
     reason = String.Empty;
     return(true);
 }
Exemplo n.º 32
0
        /// <summary>
        /// Show client stats data
        /// </summary>
        /// <param name="showParams"></param>
        /// <returns></returns>
        protected string HandleClientStatsReport(string[] showParams)
        {
            // NOTE: This writes to m_log on purpose. We want to store this information
            // in case we need to analyze it later.
            //
            if (showParams.Length <= 4)
            {
                m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}", "Region", "Name", "Root", "Time", "Reqs/min", "AgentUpdates");
                foreach (Scene scene in m_scenes.Values)
                {
                    scene.ForEachClient(
                        delegate(IClientAPI client)
                    {
                        if (client is LLClientView)
                        {
                            LLClientView llClient = client as LLClientView;
                            ClientInfo cinfo      = llClient.UDPClient.GetClientInfo();
                            int avg_reqs          = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum();
                            avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1);

                            string childAgentStatus;

                            if (llClient.SceneAgent != null)
                            {
                                childAgentStatus = llClient.SceneAgent.IsChildAgent ? "N" : "Y";
                            }
                            else
                            {
                                childAgentStatus = "Off!";
                            }

                            m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}",
                                             scene.RegionInfo.RegionName, llClient.Name,
                                             childAgentStatus,
                                             (DateTime.Now - cinfo.StartedTime).Minutes,
                                             avg_reqs,
                                             string.Format(
                                                 "{0} ({1:0.00}%)",
                                                 llClient.TotalAgentUpdates,
                                                 (float)cinfo.SyncRequests["AgentUpdate"] / llClient.TotalAgentUpdates * 100));
                        }
                    });
                }
                return(string.Empty);
            }

            string fname = "", lname = "";

            if (showParams.Length > 3)
            {
                fname = showParams[3];
            }
            if (showParams.Length > 4)
            {
                lname = showParams[4];
            }

            foreach (Scene scene in m_scenes.Values)
            {
                scene.ForEachClient(
                    delegate(IClientAPI client)
                {
                    if (client is LLClientView)
                    {
                        LLClientView llClient = client as LLClientView;

                        if (llClient.Name == fname + " " + lname)
                        {
                            ClientInfo cinfo          = llClient.GetClientInfo();
                            AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(llClient.CircuitCode);
                            if (aCircuit == null)     // create a dummy one
                            {
                                aCircuit = new AgentCircuitData();
                            }

                            if (!llClient.SceneAgent.IsChildAgent)
                            {
                                m_log.InfoFormat("[INFO]: {0} # {1} # {2}", llClient.Name, Util.GetViewerName(aCircuit), aCircuit.Id0);
                            }

                            int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum();
                            avg_reqs     = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1);

                            m_log.InfoFormat("[INFO]:");
                            m_log.InfoFormat("[INFO]: {0} # {1} # Time: {2}min # Avg Reqs/min: {3}", scene.RegionInfo.RegionName,
                                             (llClient.SceneAgent.IsChildAgent ? "Child" : "Root"), (DateTime.Now - cinfo.StartedTime).Minutes, avg_reqs);

                            Dictionary <string, int> sortedDict = (from entry in cinfo.AsyncRequests orderby entry.Value descending select entry)
                                                                  .ToDictionary(pair => pair.Key, pair => pair.Value);
                            PrintRequests("TOP ASYNC", sortedDict, cinfo.AsyncRequests.Values.Sum());

                            sortedDict = (from entry in cinfo.SyncRequests orderby entry.Value descending select entry)
                                         .ToDictionary(pair => pair.Key, pair => pair.Value);
                            PrintRequests("TOP SYNC", sortedDict, cinfo.SyncRequests.Values.Sum());

                            sortedDict = (from entry in cinfo.GenericRequests orderby entry.Value descending select entry)
                                         .ToDictionary(pair => pair.Key, pair => pair.Value);
                            PrintRequests("TOP GENERIC", sortedDict, cinfo.GenericRequests.Values.Sum());
                        }
                    }
                });
            }
            return(string.Empty);
        }
Exemplo n.º 33
0
        public void HistoricalAgentCircuitDataOSDConversion()
        {
            string oldSerialization = "{\"agent_id\":\"522675bd-8214-40c1-b3ca-9c7f7fd170be\",\"base_folder\":\"c40b5f5f-476f-496b-bd69-b5a539c434d8\",\"caps_path\":\"http://www.opensimulator.org/Caps/Foo\",\"children_seeds\":[{\"handle\":\"18446744073709551615\",\"seed\":\"http://www.opensimulator.org/Caps/Foo2\"}],\"child\":false,\"circuit_code\":\"949030\",\"first_name\":\"CoolAvatarTest\",\"last_name\":\"test\",\"inventory_folder\":\"c40b5f5f-476f-496b-bd69-b5a539c434d8\",\"secure_session_id\":\"1e608e2b-0ddb-41f6-be0f-926f61cd3e0a\",\"session_id\":\"aa06f798-9d70-4bdb-9bbf-012a02ee2baf\",\"start_pos\":\"<5, 23, 125>\"}";
            AgentCircuitData Agent1Data = new AgentCircuitData();
            Agent1Data.AgentID = new UUID("522675bd-8214-40c1-b3ca-9c7f7fd170be");
            Agent1Data.Appearance = AvAppearance;
            Agent1Data.BaseFolder = new UUID("c40b5f5f-476f-496b-bd69-b5a539c434d8");
            Agent1Data.CapsPath = CapsPath;
            Agent1Data.child = false;
            Agent1Data.ChildrenCapSeeds = ChildrenCapsPaths;
            Agent1Data.circuitcode = circuitcode;
            Agent1Data.firstname = firstname;
            Agent1Data.InventoryFolder = new UUID("c40b5f5f-476f-496b-bd69-b5a539c434d8");
            Agent1Data.lastname = lastname;
            Agent1Data.SecureSessionID = new UUID("1e608e2b-0ddb-41f6-be0f-926f61cd3e0a");
            Agent1Data.SessionID = new UUID("aa06f798-9d70-4bdb-9bbf-012a02ee2baf");
            Agent1Data.startpos = StartPos;


            OSDMap map2;
            try
            {
                map2 = (OSDMap) OSDParser.DeserializeJson(oldSerialization);


                AgentCircuitData Agent2Data = new AgentCircuitData();
                Agent2Data.UnpackAgentCircuitData(map2);

                Assert.That((Agent1Data.AgentID == Agent2Data.AgentID));
                Assert.That((Agent1Data.BaseFolder == Agent2Data.BaseFolder));

                Assert.That((Agent1Data.CapsPath == Agent2Data.CapsPath));
                Assert.That((Agent1Data.child == Agent2Data.child));
                Assert.That((Agent1Data.ChildrenCapSeeds.Count == Agent2Data.ChildrenCapSeeds.Count));
                Assert.That((Agent1Data.circuitcode == Agent2Data.circuitcode));
                Assert.That((Agent1Data.firstname == Agent2Data.firstname));
                Assert.That((Agent1Data.InventoryFolder == Agent2Data.InventoryFolder));
                Assert.That((Agent1Data.lastname == Agent2Data.lastname));
                Assert.That((Agent1Data.SecureSessionID == Agent2Data.SecureSessionID));
                Assert.That((Agent1Data.SessionID == Agent2Data.SessionID));
                Assert.That((Agent1Data.startpos == Agent2Data.startpos));
            }
            catch (LitJson.JsonException)
            {
                //intermittant litjson errors :P
                Assert.That(1 == 1);
            }
            /*
            Enable this once VisualParams go in the packing method
            for (int i=0;i<208;i++)
               Assert.That((Agent1Data.Appearance.VisualParams[i] == Agent2Data.Appearance.VisualParams[i]));
            */
       }
Exemplo n.º 34
0
 // subclasses can override this
 protected bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
 {
     return m_GatekeeperService.LoginAgent (aCircuit, destination, out reason);
 }
 public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent, out string reason)
 {
     reason = String.Empty;
     lock (m_regionsList)
     {
         foreach (RegionInfo regInfo in m_regionsList)
         {
             if (regInfo.RegionHandle == regionHandle)
                 return true;
         }
     }
     reason = "Region not found";
     return false;
 }
Exemplo n.º 36
0
        public void Initialise(IClientCapsService clientCapsService, IRegionCapsService regionCapsService, string capsBase, AgentCircuitData circuitData)
        {
            m_clientCapsService = clientCapsService;
            m_regionCapsService = regionCapsService;
            m_circuitData = circuitData;
            AddSEEDCap(capsBase);

            AddCAPS();
        }
 public System.Threading.Tasks.Task <Tuple <bool, string> > SendCreateRemoteChildAgentAsync(SimpleRegionInfo regionInfo, AgentCircuitData aCircuit)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 38
0
        public void TestCrossOnSameSimulatorWithSittingAvatar()
        {
            TestHelpers.InMethod();
            //            TestHelpers.EnableLogging();

            UUID    userId            = TestHelpers.ParseTail(0x1);
            int     sceneObjectIdTail = 0x2;
            Vector3 so1StartPos       = new Vector3(128, 10, 20);

            EntityTransferModule           etmA = new EntityTransferModule();
            EntityTransferModule           etmB = new EntityTransferModule();
            LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);
            IConfig entityTransferConfig = config.AddConfig("EntityTransfer");

            // In order to run a single threaded regression test we do not want the entity transfer module waiting
            // for a callback from the destination scene before removing its avatar data.
            entityTransferConfig.Set("wait_for_callback", false);

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA);
            SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB);

            SceneObjectGroup so1   = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
            UUID             so1Id = so1.UUID;

            so1.AbsolutePosition = so1StartPos;

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(userId);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence sp1SceneA = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            sp1SceneA.AbsolutePosition = so1StartPos;
            sp1SceneA.HandleAgentRequestSit(sp1SceneA.ControllingClient, sp1SceneA.UUID, so1.UUID, Vector3.Zero);

            sceneA.Update(4);
            sceneB.Update(4);
            // Cross
            sceneA.SceneGraph.UpdatePrimGroupPosition(
                so1.LocalId, new Vector3(so1StartPos.X, so1StartPos.Y - 20, so1StartPos.Z), sp1SceneA.ControllingClient);

            // crossing is async
            sceneA.Update(4);
            sceneB.Update(4);
            Thread.Sleep(500);

            SceneObjectGroup so1PostCross;

            ScenePresence sp1SceneAPostCross = sceneA.GetScenePresence(userId);

            Assert.IsTrue(sp1SceneAPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly false");

            ScenePresence sp1SceneBPostCross = sceneB.GetScenePresence(userId);
            TestClient    sceneBTc           = ((TestClient)sp1SceneBPostCross.ControllingClient);

            sceneBTc.CompleteMovement();

            sceneA.Update(4);
            sceneB.Update(4);

            Assert.IsFalse(sp1SceneBPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
            Assert.IsTrue(sp1SceneBPostCross.IsSatOnObject);

            Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id), "uck");
            so1PostCross = sceneB.GetSceneObjectGroup(so1Id);
            Assert.NotNull(so1PostCross);
            Assert.AreEqual(1, so1PostCross.GetSittingAvatarsCount());


            Vector3 so1PostCrossPos = so1PostCross.AbsolutePosition;

            //            Console.WriteLine("CRISSCROSS");

            // Recross
            sceneB.SceneGraph.UpdatePrimGroupPosition(
                so1PostCross.LocalId, new Vector3(so1PostCrossPos.X, so1PostCrossPos.Y + 20, so1PostCrossPos.Z), sp1SceneBPostCross.ControllingClient);

            sceneA.Update(4);
            sceneB.Update(4);
            // crossing is async
            Thread.Sleep(500);

            {
                ScenePresence sp1SceneBPostReCross = sceneB.GetScenePresence(userId);
                Assert.IsTrue(sp1SceneBPostReCross.IsChildAgent, "sp1SceneBPostReCross.IsChildAgent unexpectedly false");

                ScenePresence sp1SceneAPostReCross = sceneA.GetScenePresence(userId);
                TestClient    sceneATc             = ((TestClient)sp1SceneAPostReCross.ControllingClient);
                sceneATc.CompleteMovement();

                Assert.IsFalse(sp1SceneAPostReCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
                Assert.IsTrue(sp1SceneAPostReCross.IsSatOnObject);

                Assert.IsNull(sceneB.GetSceneObjectGroup(so1Id), "uck2");
                SceneObjectGroup so1PostReCross = sceneA.GetSceneObjectGroup(so1Id);
                Assert.NotNull(so1PostReCross);
                Assert.AreEqual(1, so1PostReCross.GetSittingAvatarsCount());
            }
        }
Exemplo n.º 39
0
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = WebUtils.GetOSDMap ((string)request["body"]);
            if (args == null)
            {
                responsedata["int_response_code"] = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            // retrieve the input arguments
            int x = 0, y = 0;
            UUID uuid = UUID.Zero;
            string regionname = string.Empty;
            uint teleportFlags = 0;
            if (args.ContainsKey ("destination_x") && args["destination_x"] != null)
                Int32.TryParse (args["destination_x"].AsString (), out x);
            else
                m_log.WarnFormat ("  -- request didn't have destination_x");
            if (args.ContainsKey ("destination_y") && args["destination_y"] != null)
                Int32.TryParse (args["destination_y"].AsString (), out y);
            else
                m_log.WarnFormat ("  -- request didn't have destination_y");
            if (args.ContainsKey ("destination_uuid") && args["destination_uuid"] != null)
                UUID.TryParse (args["destination_uuid"].AsString (), out uuid);
            if (args.ContainsKey ("destination_name") && args["destination_name"] != null)
                regionname = args["destination_name"].ToString ();
            if (args.ContainsKey ("teleport_flags") && args["teleport_flags"] != null)
                teleportFlags = args["teleport_flags"].AsUInteger ();

            GridRegion destination = new GridRegion ();
            destination.RegionID = uuid;
            destination.RegionLocX = x;
            destination.RegionLocY = y;
            destination.RegionName = regionname;

            AgentCircuitData aCircuit = new AgentCircuitData ();
            try
            {
                aCircuit.UnpackAgentCircuitData (args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat ("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
                responsedata["int_response_code"] = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            OSDMap resp = new OSDMap (2);
            string reason = String.Empty;

            // This is the meaning of POST agent
            //m_regionClient.AdjustUserInformation(aCircuit);
            //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
            bool result = CreateAgent (destination, aCircuit, teleportFlags, out reason);

            resp["reason"] = OSD.FromString (reason);
            resp["success"] = OSD.FromBoolean (result);
            // Let's also send out the IP address of the caller back to the caller (HG 1.5)
            resp["your_ip"] = OSD.FromString (GetCallerIP (request));

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"] = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString (resp);
        }
Exemplo n.º 40
0
        public bool LoginAgent(AgentCircuitData aCircuit, GridRegion destination, out string reason)
        {
            reason = string.Empty;

            string authURL = string.Empty;

            if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
            {
                authURL = aCircuit.ServiceURLs["HomeURI"].ToString();
            }
            m_log.InfoFormat("[GATEKEEPER SERVICE]: Login request for {0} {1} @ {2} ({3}) at {4} using viewer {5}, channel {6}, IP {7}, Mac {8}, Id0 {9} Teleport Flags {10}",
                             aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionName,
                             aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0, aCircuit.teleportFlags.ToString());

            //
            // Check client
            //
            if (m_AllowedClients != string.Empty)
            {
                Regex arx = new Regex(m_AllowedClients);
                Match am  = arx.Match(aCircuit.Viewer);

                if (!am.Success)
                {
                    m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is not allowed", aCircuit.Viewer);
                    return(false);
                }
            }

            if (m_DeniedClients != string.Empty)
            {
                Regex drx = new Regex(m_DeniedClients);
                Match dm  = drx.Match(aCircuit.Viewer);

                if (dm.Success)
                {
                    m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is denied", aCircuit.Viewer);
                    return(false);
                }
            }

            //
            // Authenticate the user
            //
            if (!Authenticate(aCircuit))
            {
                reason = "Unable to verify identity";
                m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname);
                return(false);
            }
            m_log.DebugFormat("[GATEKEEPER SERVICE]: Identity verified for {0} {1} @ {2}", aCircuit.firstname, aCircuit.lastname, authURL);

            //
            // Check for impersonations
            //
            UserAccount account = null;

            if (m_UserAccountService != null)
            {
                // Check to see if we have a local user with that UUID
                account = m_UserAccountService.GetUserAccount(m_ScopeID, aCircuit.AgentID);
                if (account != null)
                {
                    // Make sure this is the user coming home, and not a foreign user with same UUID as a local user
                    if (m_UserAgentService != null)
                    {
                        if (!m_UserAgentService.IsAgentComingHome(aCircuit.SessionID, m_ExternalName))
                        {
                            // Can't do, sorry
                            reason = "Unauthorized";
                            m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agent {0} {1} has same ID as local user. Refusing service.",
                                             aCircuit.firstname, aCircuit.lastname);
                            return(false);
                        }
                    }
                }
            }
            m_log.DebugFormat("[GATEKEEPER SERVICE]: User is ok");

            //
            // Foreign agents allowed? Exceptions?
            //
            if (account == null)
            {
                bool allowed = m_ForeignAgentsAllowed;

                if (m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsAllowedExceptions))
                {
                    allowed = false;
                }

                if (!m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsDisallowedExceptions))
                {
                    allowed = true;
                }

                if (!allowed)
                {
                    reason = "Destination does not allow visitors from your world";
                    m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agents are not permitted {0} {1} @ {2}. Refusing service.",
                                     aCircuit.firstname, aCircuit.lastname, aCircuit.ServiceURLs["HomeURI"]);
                    return(false);
                }
            }

            bool isFirstLogin = false;
            //
            // Login the presence, if it's not there yet (by the login service)
            //
            PresenceInfo presence = m_PresenceService.GetAgent(aCircuit.SessionID);

            if (presence != null) // it has been placed there by the login service
            {
                isFirstLogin = true;
            }

            else
            {
                if (!m_PresenceService.LoginAgent(aCircuit.AgentID.ToString(), aCircuit.SessionID, aCircuit.SecureSessionID))
                {
                    reason = "Unable to login presence";
                    m_log.InfoFormat("[GATEKEEPER SERVICE]: Presence login failed for foreign agent {0} {1}. Refusing service.",
                                     aCircuit.firstname, aCircuit.lastname);
                    return(false);
                }
                m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence ok");

                // Also login foreigners with GridUser service
                if (m_GridUserService != null && account == null)
                {
                    string userId = aCircuit.AgentID.ToString();
                    string first = aCircuit.firstname, last = aCircuit.lastname;
                    if (last.StartsWith("@"))
                    {
                        string[] parts = aCircuit.firstname.Split('.');
                        if (parts.Length >= 2)
                        {
                            first = parts[0];
                            last  = parts[1];
                        }
                    }

                    userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last;
                    m_GridUserService.LoggedIn(userId);
                }
            }

            //
            // Get the region
            //
            destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
            if (destination == null)
            {
                reason = "Destination region not found";
                return(false);
            }
            m_log.DebugFormat("[GATEKEEPER SERVICE]: destination ok: {0}", destination.RegionName);

            //
            // Adjust the visible name
            //
            if (account != null)
            {
                aCircuit.firstname = account.FirstName;
                aCircuit.lastname  = account.LastName;
            }
            if (account == null)
            {
                if (!aCircuit.lastname.StartsWith("@"))
                {
                    aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
                }
                try
                {
                    Uri uri = new Uri(aCircuit.ServiceURLs["HomeURI"].ToString());
                    aCircuit.lastname = "@" + uri.Host; // + ":" + uri.Port;
                }
                catch
                {
                    m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
                    aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
                }
            }

            //
            // Finally launch the agent at the destination
            //
            Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;

            // Preserve our TeleportFlags we have gathered so-far
            loginFlag |= (Constants.TeleportFlags)aCircuit.teleportFlags;

            m_log.DebugFormat("[GATEKEEPER SERVICE]: launching agent {0}", loginFlag);
            return(m_SimulationService.CreateAgent(destination, aCircuit, (uint)loginFlag, out reason));
        }
Exemplo n.º 41
0
        public bool AllowTeleport(UUID userID, Scene scene, Vector3 Position, AgentCircuitData ACD, out Vector3 newPosition, out string reason)
        {
            newPosition = Position;
            
            UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userID);

            ScenePresence Sp = scene.GetScenePresence(userID);
            if (account == null)
            {
                reason = "Failed authentication.";
                return false; //NO!
            }

            //Check how long its been since the last TP
            if (m_enabledBlockTeleportSeconds && Sp != null && !Sp.IsChildAgent)
            {
                if (TimeSinceLastTeleport.ContainsKey(Sp.Scene.RegionInfo.RegionID))
                {
                    if (TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] > Util.UnixTimeSinceEpoch())
                    {
                        reason = "Too many teleports. Please try again soon.";
                        return false; // Too soon since the last TP
                    }
                }
                TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] = Util.UnixTimeSinceEpoch() + ((int)(SecondsBeforeNextTeleport));
            }

            //Gods tp freely
            if ((Sp != null && Sp.GodLevel != 0) || account.UserLevel != 0)
            {
                reason = "";
                return true;
            }

            //Check whether they fit any ban criteria
            if (Sp != null)
            {
                foreach (string banstr in BanCriteria)
                {
                    if (Sp.Name.Contains(banstr))
                    {
                        reason = "You have been banned from this region.";
                        return false;
                    }
                    else if (((System.Net.IPEndPoint)Sp.ControllingClient.GetClientEP()).Address.ToString().Contains(banstr))
                    {
                        reason = "You have been banned from this region.";
                        return false;
                    }
                }
            }

            EstateSettings ES = scene.RegionInfo.EstateSettings;

            if (scene.RegionInfo.RegionSettings.AgentLimit < scene.GetRootAgentCount() + 1)
            {
                reason = "Too many agents at this time. Please come back later.";
                return false;
            }

            List<EstateBan> EstateBans = new List<EstateBan>(ES.EstateBans);
            int i = 0;
            //Check bans
            foreach (EstateBan ban in EstateBans)
            {
                if (ban.BannedUserID == userID)
                {
                    string banIP = ((System.Net.IPEndPoint)Sp.ControllingClient.GetClientEP()).Address.ToString();

                    if (ban.BannedHostIPMask != banIP) //If it changed, ban them again
                    {
                        //Add the ban with the new hostname
                        ES.AddBan(new EstateBan()
                        {
                            BannedHostIPMask = banIP,
                            BannedUserID = ban.BannedUserID,
                            EstateID = ban.EstateID,
                            BannedHostAddress = ban.BannedHostAddress,
                            BannedHostNameMask = ban.BannedHostNameMask
                        });
                        //Update the database
                        ES.Save();
                    }

                    reason = "Banned from this region.";
                    return false;
                }
                if (ban.BannedHostIPMask == ACD.IPAddress)
                {
                    //Ban the new user
                    ES.AddBan(new EstateBan()
                    {
                        EstateID = ES.EstateID,
                        BannedHostIPMask = ACD.IPAddress,
                        BannedUserID = userID,
                        BannedHostAddress = ACD.IPAddress,
                        BannedHostNameMask = ACD.IPAddress
                    });
                    ES.Save();

                    reason = "Banned from this region.";
                    return false;
                }
                i++;
            }
            
            //Estate owners/managers/access list people/access groups tp freely as well
            if (ES.EstateOwner == userID ||
                new List<UUID>(ES.EstateManagers).Contains(userID) ||
                new List<UUID>(ES.EstateAccess).Contains(userID) ||
                (Sp != null && new List<UUID>(ES.EstateGroups).Contains(Sp.ControllingClient.ActiveGroupId)))
            {
                reason = "";
                return true;
            }

            if (ES.DenyAnonymous && ((account.UserFlags & (int)ProfileFlags.NoPaymentInfoOnFile) == (int)ProfileFlags.NoPaymentInfoOnFile))
            {
                reason = "You may not enter this region.";
                return false;
            }

            if (ES.DenyIdentified && ((account.UserFlags & (int)ProfileFlags.PaymentInfoOnFile) == (int)ProfileFlags.PaymentInfoOnFile))
            {
                reason = "You may not enter this region.";
                return false;
            }

            if (ES.DenyTransacted && ((account.UserFlags & (int)ProfileFlags.PaymentInfoInUse) == (int)ProfileFlags.PaymentInfoInUse))
            {
                reason = "You may not enter this region.";
                return false;
            }

            long m_Day = 25 * 60 * 60; //Find out day length in seconds
            if (scene.RegionInfo.RegionSettings.MinimumAge != 0 && (account.Created - Util.UnixTimeSinceEpoch()) < (scene.RegionInfo.RegionSettings.MinimumAge * m_Day))
            {
                reason = "You may not enter this region.";
                return false;
            }

            if (!ES.PublicAccess)
            {
                reason = "You may not enter this region.";
                return false;
            }

            IAgentConnector AgentConnector = DataManager.DataManager.RequestPlugin<IAgentConnector>();
            IAgentInfo agentInfo = null;
            if (AgentConnector != null)
            {
                agentInfo = AgentConnector.GetAgent(userID);
                if (agentInfo == null)
                {
                    AgentConnector.CreateNewAgent(userID);
                    agentInfo = AgentConnector.GetAgent(userID);
                }
            }
            

            if (agentInfo != null && scene.RegionInfo.RegionSettings.Maturity > agentInfo.MaturityRating)
            {
                reason = "The region has too high of a maturity level. Blocking teleport.";
                return false;
            }

            if (agentInfo != null && ES.DenyMinors && (agentInfo.Flags & IAgentFlags.Minor) == IAgentFlags.Minor)
            {
                reason = "The region has too high of a maturity level. Blocking teleport.";
                return false;
            }

            ILandObject ILO = scene.LandChannel.GetLandObject(Position.X, Position.Y);
            if (ILO == null) // Can't teleport into a parcel that doesn't exist
            {
                reason = "Failed authentication.";
                return false;
            }

            //parcel permissions
            if (ILO.IsEitherBannedOrRestricted(userID))
            {
                if (Sp == null)
                {
                    reason = "Banned from this parcel.";
                    return true;
                }

                if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason))
                {
                    //We found a place for them, but we don't need to check any further
                    return true;
                }
            }
            //Move them out of banned parcels
            ParcelFlags parcelflags = (ParcelFlags)ILO.LandData.Flags;
            if ((parcelflags & ParcelFlags.UseAccessGroup) == ParcelFlags.UseAccessGroup &&
                (parcelflags & ParcelFlags.UseAccessList) == ParcelFlags.UseAccessList &&
                (parcelflags & ParcelFlags.UsePassList) == ParcelFlags.UsePassList)
            {
                //One of these is in play then
                if ((parcelflags & ParcelFlags.UseAccessGroup) == ParcelFlags.UseAccessGroup)
                {
                    if (Sp == null)
                    {
                        reason = "Banned from this parcel.";
                        return true;
                    }
                    if (Sp.ControllingClient.ActiveGroupId != ILO.LandData.GroupID)
                    {
                        if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason))
                            //We found a place for them, but we don't need to check any further
                            return true;
                    }
                }
                else if ((parcelflags & ParcelFlags.UseAccessList) == ParcelFlags.UseAccessList)
                {
                    if (Sp == null)
                    {
                        reason = "Banned from this parcel.";
                        return true;
                    }
                    //All but the people on the access list are banned
                    if (!ILO.CreateAccessListArrayByFlag(AccessList.Access).Contains(Sp.UUID))
                        if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason))
                            //We found a place for them, but we don't need to check any further
                            return true;
                }
                else if ((parcelflags & ParcelFlags.UsePassList) == ParcelFlags.UsePassList)
                {
                    if (Sp == null)
                    {
                        reason = "Banned from this parcel.";
                        return true;
                    }
                    //All but the people on the pass/access list are banned
                    if (!ILO.CreateAccessListArrayByFlag(AccessList.Access).Contains(Sp.UUID))
                        if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason))
                            //We found a place for them, but we don't need to check any further
                            return true;
                }
            }

            //Move them to the nearest landing point
            if (!ES.AllowDirectTeleport)
            {
                Telehub telehub = RegionConnector.FindTelehub(scene.RegionInfo.RegionID);
                if (telehub != null)
                {
                    if (telehub.SpawnPos.Count == 0)
                    {
                        newPosition = new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ);
                    }
                    else
                    {
                        int LastTelehubNum = 0;
                        if (!LastTelehub.TryGetValue(scene.RegionInfo.RegionID, out LastTelehubNum))
                            LastTelehubNum = 0;
                        newPosition = telehub.SpawnPos[LastTelehubNum] + new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ);
                        LastTelehubNum++;
                        if (LastTelehubNum == telehub.SpawnPos.Count)
                            LastTelehubNum = 0;
                        LastTelehub[scene.RegionInfo.RegionID] = LastTelehubNum;
                    }
                }
                else
                {
                    reason = "Teleport has been blocked for this region.";
                    return false;
                }
            }
            else
            {
                //If they are owner, they don't have to have permissions checked
                if (!m_scene.Permissions.GenericParcelPermission(userID, ILO, (ulong)GroupPowers.None))
                {
                    if (ILO.LandData.LandingType == 2) //Blocked, force this person off this land
                    {
                        //Find a new parcel for them
                        List<ILandObject> Parcels = m_scene.LandChannel.ParcelsNearPoint(Position);
                        if (Parcels.Count == 0)
                        {
                            ScenePresence SP;
                            scene.TryGetScenePresence(userID, out SP);
                            newPosition = m_scene.LandChannel.GetNearestRegionEdgePosition(SP);
                        }
                        else
                        {
                            bool found = false;
                            //We need to check here as well for bans, can't toss someone into a parcel they are banned from
                            foreach (ILandObject Parcel in Parcels)
                            {
                                if (!Parcel.IsBannedFromLand(userID))
                                {
                                    //Now we have to check their userloc
                                    if (ILO.LandData.LandingType == 2)
                                        continue; //Blocked, check next one
                                    else if (ILO.LandData.LandingType == 1) //Use their landing spot
                                        newPosition = Parcel.LandData.UserLocation;
                                    else //They allow for anywhere, so dump them in the center at the ground
                                        newPosition = m_scene.LandChannel.GetParcelCenterAtGround(Parcel);
                                    found = true;
                                }
                            }
                            if (!found) //Dump them at the edge
                            {
                                if(Sp != null)
                                    newPosition = m_scene.LandChannel.GetNearestRegionEdgePosition(Sp);
                                else
                                {
                                    reason = "Banned from this parcel.";
                                    return true;
                                }
                            }
                        }
                    }
                    else if (ILO.LandData.LandingType == 1) //Move to tp spot
                        newPosition = ILO.LandData.UserLocation;
                }
            }

            //Can only enter prelude regions once!
            int flags = m_scene.GridService.GetRegionFlags(m_scene.RegionInfo.ScopeID, m_scene.RegionInfo.RegionID);
            //We assume that our own region isn't null....
            if (((flags & (int)OpenSim.Data.RegionFlags.Prelude) == (int)OpenSim.Data.RegionFlags.Prelude) && agentInfo != null)
            {
                if (((agentInfo.Flags & IAgentFlags.PastPrelude) == IAgentFlags.PastPrelude))
                {
                    reason = "You may not enter this region as you have already been to a prelude region.";
                    return false;
                }
                else
                {
                    agentInfo.Flags |= IAgentFlags.PastPrelude;
                    AgentConnector.UpdateAgent(agentInfo); //This only works for standalones... and thats ok
                }
            }


            if ((ILO.LandData.Flags & (int)ParcelFlags.DenyAnonymous) != 0)
            {
                if ((account.UserFlags & (int)ProfileFlags.NoPaymentInfoOnFile) == (int)ProfileFlags.NoPaymentInfoOnFile)
                {
                    reason = "You may not enter this region.";
                    return false;
                }
            }

            if ((ILO.LandData.Flags & (uint)ParcelFlags.DenyAgeUnverified) != 0 && agentInfo != null)
            {
                if ((agentInfo.Flags & IAgentFlags.Minor) == IAgentFlags.Minor)
                {
                    reason = "You may not enter this region.";
                    return false;
                }
            }

            reason = "";
            return true;
        }
Exemplo n.º 42
0
 /// <summary>
 /// Add a root agent.
 /// </summary>
 /// <remarks>
 /// This function
 ///
 /// 1)  Tells the scene that an agent is coming.  Normally, the login service (local if standalone, from the
 /// userserver if grid) would give initial login data back to the client and separately tell the scene that the
 /// agent was coming.
 ///
 /// 2)  Connects the agent with the scene
 ///
 /// This function performs actions equivalent with notifying the scene that an agent is
 /// coming and then actually connecting the agent to the scene.  The one step missed out is the very first
 /// </remarks>
 /// <param name="scene"></param>
 /// <param name="agentData"></param>
 /// <returns></returns>
 public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData)
 {
     return AddScenePresence(scene, agentData, null);
 }
Exemplo n.º 43
0
 /// <summary>
 /// Find, or create if one does not exist, a Caps Service for the given region
 /// </summary>
 /// <param name="regionID"></param>
 /// <returns></returns>
 public IRegionClientCapsService GetOrCreateCapsService(ulong regionID, string CAPSBase, AgentCircuitData circuitData)
 {
     //If one already exists, don't add a new one
     if (m_RegionCapsServices.ContainsKey(regionID))
     {
         m_RegionCapsServices[regionID].InformModulesOfRequest();
         return m_RegionCapsServices[regionID];
     }
     //Create a new one, and then call Get to find it
     AddCapsServiceForRegion(regionID, CAPSBase, circuitData);
     return GetCapsService(regionID);
 }
Exemplo n.º 44
0
        public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, bool fromLogin, out string reason)
        {
            m_log.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} {1} (@{2}) to grid {3}",
                              agentCircuit.firstname, agentCircuit.lastname, (fromLogin ? agentCircuit.IPAddress : "stored IP"), gatekeeper.ServerURI);

            string gridName = gatekeeper.ServerURI.ToLowerInvariant();

            UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, agentCircuit.AgentID);

            if (account == null)
            {
                m_log.WarnFormat("[USER AGENT SERVICE]: Someone attempted to lauch a foreign user from here {0} {1}", agentCircuit.firstname, agentCircuit.lastname);
                reason = "Forbidden to launch your agents from here";
                return(false);
            }

            // Is this user allowed to go there?
            if (m_GridName != gridName)
            {
                if (m_ForeignTripsAllowed.ContainsKey(account.UserLevel))
                {
                    bool allowed = m_ForeignTripsAllowed[account.UserLevel];

                    if (m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsAllowedExceptions))
                    {
                        allowed = false;
                    }

                    if (!m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsDisallowedExceptions))
                    {
                        allowed = true;
                    }

                    if (!allowed)
                    {
                        reason = "Your world does not allow you to visit the destination";
                        m_log.InfoFormat("[USER AGENT SERVICE]: Agents not permitted to visit {0}. Refusing service.", gridName);
                        return(false);
                    }
                }
            }

            // Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
            GridRegion region = new GridRegion(gatekeeper);

            region.ServerURI        = gatekeeper.ServerURI;
            region.ExternalHostName = finalDestination.ExternalHostName;
            region.InternalEndPoint = finalDestination.InternalEndPoint;
            region.RegionName       = finalDestination.RegionName;
            region.RegionID         = finalDestination.RegionID;
            region.RegionLocX       = finalDestination.RegionLocX;
            region.RegionLocY       = finalDestination.RegionLocY;

            // Generate a new service session
            agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
            TravelingAgentInfo old    = null;
            TravelingAgentInfo travel = CreateTravelInfo(agentCircuit, region, fromLogin, out old);

            if (!fromLogin && old != null && !string.IsNullOrEmpty(old.ClientIPAddress))
            {
                m_log.DebugFormat("[USER AGENT SERVICE]: stored IP = {0}. Old circuit IP: {1}", old.ClientIPAddress, agentCircuit.IPAddress);
                agentCircuit.IPAddress = old.ClientIPAddress;
            }

            bool success = false;

            m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}, desired region: {2}", m_GridName, gridName, region.RegionID);

            if (m_GridName.Equals(gridName, StringComparison.InvariantCultureIgnoreCase))
            {
                success = m_GatekeeperService.LoginAgent(source, agentCircuit, finalDestination, out reason);
            }
            else
            {
                //TODO: Should there not be a call to QueryAccess here?
                EntityTransferContext ctx = new EntityTransferContext();
                success = m_GatekeeperConnector.CreateAgent(source, region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, ctx, out reason);
            }

            if (!success)
            {
                m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
                                  agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);

                if (old != null)
                {
                    StoreTravelInfo(old);
                }
                else
                {
                    m_Database.Delete(agentCircuit.SessionID);
                }

                return(false);
            }

            // Everything is ok

            StoreTravelInfo(travel);

            return(true);
        }
        public void Initialise(IClientCapsService clientCapsService, IRegionCapsService regionCapsService, string capsBase, AgentCircuitData circuitData, uint port)
        {
            m_clientCapsService = clientCapsService;
            m_regionCapsService = regionCapsService;
            m_circuitData = circuitData;
            if (port != 0)//Someone requested a non standard port, probably for OpenSim
            {
                ISimulationBase simBase = Registry.RequestModuleInterface<ISimulationBase> ();
                Server = simBase.GetHttpServer (port);
            }
            AddSEEDCap(capsBase);

            AddCAPS();
        }
Exemplo n.º 46
0
 public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
 {
     reason = string.Empty;
     return(LoginAgentToGrid(source, agentCircuit, gatekeeper, finalDestination, false, out reason));
 }
Exemplo n.º 47
0
        protected AgentCircuitData MakeAgent(GridRegion region, UserAccount account,
            AvatarAppearance appearance, UUID session, UUID secureSession, uint circuit, Vector3 position,
            IPEndPoint clientIP)
        {
            AgentCircuitData aCircuit = new AgentCircuitData();

            aCircuit.AgentID = account.PrincipalID;
            if (appearance != null)
                aCircuit.Appearance = appearance;
            else
                aCircuit.Appearance = new AvatarAppearance(account.PrincipalID);

            aCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
            aCircuit.child = false; // the first login agent is root
            aCircuit.circuitcode = circuit;
            aCircuit.SecureSessionID = secureSession;
            aCircuit.SessionID = session;
            aCircuit.startpos = position;
            aCircuit.IPAddress = clientIP.Address.ToString();
            aCircuit.ClientIPEndPoint = clientIP;

            return aCircuit;
        }
Exemplo n.º 48
0
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            EntityTransferContext ctx = new EntityTransferContext();

            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            if (args == null)
            {
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            if (args.ContainsKey("context"))
            {
                ctx.Unpack((OSDMap)args["context"]);
            }

            AgentDestinationData data = CreateAgentDestinationData();

            UnpackData(args, data, request);

            GridRegion destination = new GridRegion();

            destination.RegionID   = data.uuid;
            destination.RegionLocX = data.x;
            destination.RegionLocY = data.y;
            destination.RegionName = data.name;

            GridRegion gatekeeper = ExtractGatekeeper(data);

            AgentCircuitData aCircuit = new AgentCircuitData();

            try
            {
                aCircuit.UnpackAgentCircuitData(args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            GridRegion source = null;

            if (args.ContainsKey("source_uuid"))
            {
                source            = new GridRegion();
                source.RegionLocX = Int32.Parse(args["source_x"].AsString());
                source.RegionLocY = Int32.Parse(args["source_y"].AsString());
                source.RegionName = args["source_name"].AsString();
                source.RegionID   = UUID.Parse(args["source_uuid"].AsString());

                if (args.ContainsKey("source_server_uri"))
                {
                    source.RawServerURI = args["source_server_uri"].AsString();
                }
                else
                {
                    source.RawServerURI = null;
                }
            }

            OSDMap resp   = new OSDMap(2);
            string reason = String.Empty;

            // This is the meaning of POST agent
            //m_regionClient.AdjustUserInformation(aCircuit);
            //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);

            bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, ctx, out reason);

            resp["reason"]  = OSD.FromString(reason);
            resp["success"] = OSD.FromBoolean(result);
            // Let's also send out the IP address of the caller back to the caller (HG 1.5)
            resp["your_ip"] = OSD.FromString(GetCallerIP(request));

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
Exemplo n.º 49
0
 protected string FillOutSeedCap(AgentCircuitData aCircuit, GridRegion destination, IPEndPoint ipepClient, UUID AgentID)
 {
     if(m_CapsService != null)
     {
         //Remove any previous users
         string CapsBase = CapsUtil.GetRandomCapsObjectPath();
         return m_CapsService.CreateCAPS(AgentID, CapsUtil.GetCapsSeedPath(CapsBase), destination.RegionHandle, true, aCircuit);
     }
     return "";
 }
        public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, EntityTransferContext ctx, out string reason)
        {
            reason = String.Empty;

            if (destination == null)
            {
                reason = "Destination not found";
                m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Create agent destination is null");
                return(false);
            }

            m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: Creating agent at {0}", destination.ServerURI);

            string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/";

            try
            {
                OSDMap args = aCircuit.PackAgentCircuitData(ctx);
                args["context"] = ctx.Pack();
                PackData(args, source, aCircuit, destination, flags);

                OSDMap result  = WebUtil.PostToServiceCompressed(uri, args, 30000);
                bool   success = result["success"].AsBoolean();
                if (success && result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    reason  = data["reason"].AsString();
                    success = data["success"].AsBoolean();
                    return(success);
                }

                // Try the old version, uncompressed
                result = WebUtil.PostToService(uri, args, 30000, false);

                if (result["Success"].AsBoolean())
                {
                    if (result.ContainsKey("_Result"))
                    {
                        OSDMap data = (OSDMap)result["_Result"];

                        reason  = data["reason"].AsString();
                        success = data["success"].AsBoolean();
                        m_log.WarnFormat(
                            "[REMOTE SIMULATION CONNECTOR]: Remote simulator {0} did not accept compressed transfer, suggest updating it.", destination.RegionName);
                        return(success);
                    }
                }

                m_log.WarnFormat(
                    "[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {2}",
                    aCircuit.firstname, aCircuit.lastname, destination.RegionName);
                reason = result["Message"] != null ? result["Message"].AsString() : "error";
                return(false);
            }
            catch (Exception e)
            {
                m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString());
                reason = e.Message;
            }

            return(false);
        }
Exemplo n.º 51
0
        private bool OnAllowedIncomingAgent(IScene scene, AgentCircuitData agent, bool isRootAgent, out string reason)
        {
            #region Incoming Agent Checks

            UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, agent.AgentID);
            bool foreign = false;
            IScenePresence Sp = scene.GetScenePresence(agent.AgentID);
            if (account == null)
            {
                IUserAgentService uas = scene.RequestModuleInterface<IUserAgentService> ();
                if (uas != null)//SOO hate doing this...
                    foreign = true;
            }

            if (LoginsDisabled)
            {
                reason = "Logins Disabled";
                return false;
            }

            //Check how long its been since the last TP
            if (m_enabledBlockTeleportSeconds && Sp != null && !Sp.IsChildAgent)
            {
                if (TimeSinceLastTeleport.ContainsKey(Sp.Scene.RegionInfo.RegionID))
                {
                    if (TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] > Util.UnixTimeSinceEpoch())
                    {
                        reason = "Too many teleports. Please try again soon.";
                        return false; // Too soon since the last TP
                    }
                }
                TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] = Util.UnixTimeSinceEpoch() + ((int)(SecondsBeforeNextTeleport));
            }

            //Gods tp freely
            if ((Sp != null && Sp.GodLevel != 0) || (account != null && account.UserLevel != 0))
            {
                reason = "";
                return true;
            }

            //Check whether they fit any ban criteria
            if (Sp != null)
            {
                foreach (string banstr in BanCriteria)
                {
                    if (Sp.Name.Contains(banstr))
                    {
                        reason = "You have been banned from this region.";
                        return false;
                    }
                    else if (((System.Net.IPEndPoint)Sp.ControllingClient.GetClientEP()).Address.ToString().Contains(banstr))
                    {
                        reason = "You have been banned from this region.";
                        return false;
                    }
                }
                //Make sure they exist in the grid right now
                OpenSim.Services.Interfaces.IAgentInfoService presence = scene.RequestModuleInterface<IAgentInfoService>();
                if (presence == null)
                {
                    reason = String.Format("Failed to verify user presence in the grid for {0} in region {1}. Presence service does not exist.", account.Name, scene.RegionInfo.RegionName);
                    return false;
                }

                OpenSim.Services.Interfaces.UserInfo pinfo = presence.GetUserInfo(agent.AgentID.ToString());

                if (!foreign && (pinfo == null || (!pinfo.IsOnline && ((agent.teleportFlags & (uint)TeleportFlags.ViaLogin) == 0))))
                {
                    reason = String.Format("Failed to verify user presence in the grid for {0}, access denied to region {1}.", account.Name, scene.RegionInfo.RegionName);
                    return false;
                }
            }

            EstateSettings ES = scene.RegionInfo.EstateSettings;

            IEntityCountModule entityCountModule = scene.RequestModuleInterface<IEntityCountModule>();
            if (entityCountModule != null && scene.RegionInfo.RegionSettings.AgentLimit 
                < entityCountModule.RootAgents + 1)
            {
                reason = "Too many agents at this time. Please come back later.";
                return false;
            }

            List<EstateBan> EstateBans = new List<EstateBan>(ES.EstateBans);
            int i = 0;
            //Check bans
            foreach (EstateBan ban in EstateBans)
            {
                if (ban.BannedUserID == agent.AgentID)
                {
                    if (Sp != null)
                    {
                        string banIP = ((System.Net.IPEndPoint)Sp.ControllingClient.GetClientEP()).Address.ToString();

                        if (ban.BannedHostIPMask != banIP) //If it changed, ban them again
                        {
                            //Add the ban with the new hostname
                            ES.AddBan(new EstateBan()
                            {
                                BannedHostIPMask = banIP,
                                BannedUserID = ban.BannedUserID,
                                EstateID = ban.EstateID,
                                BannedHostAddress = ban.BannedHostAddress,
                                BannedHostNameMask = ban.BannedHostNameMask
                            });
                            //Update the database
                            ES.Save();
                        }
                    }

                    reason = "Banned from this region.";
                    return false;
                }
                if (Sp != null)
                {
                    IPAddress end = Sp.ControllingClient.EndPoint;
                    IPHostEntry rDNS = null;
                    try
                    {
                        rDNS = Dns.GetHostEntry(end);
                    }
                    catch (System.Net.Sockets.SocketException)
                    {
                        m_log.WarnFormat("[IPBAN] IP address \"{0}\" cannot be resolved via DNS", end);
                        rDNS = null;
                    }
                    if (ban.BannedHostIPMask == agent.IPAddress ||
                            (rDNS != null && rDNS.HostName.Contains(ban.BannedHostIPMask)) ||
                                end.ToString().StartsWith(ban.BannedHostIPMask))
                    {
                        //Ban the new user
                        ES.AddBan(new EstateBan()
                        {
                            EstateID = ES.EstateID,
                            BannedHostIPMask = agent.IPAddress,
                            BannedUserID = agent.AgentID,
                            BannedHostAddress = agent.IPAddress,
                            BannedHostNameMask = agent.IPAddress
                        });
                        ES.Save();

                        reason = "Banned from this region.";
                        return false;
                    }
                }
                i++;
            }
            
            //Estate owners/managers/access list people/access groups tp freely as well
            if (ES.EstateOwner == agent.AgentID ||
                new List<UUID>(ES.EstateManagers).Contains(agent.AgentID) ||
                new List<UUID>(ES.EstateAccess).Contains(agent.AgentID) ||
                CheckEstateGroups(ES, agent))
            {
                reason = "";
                return true;
            }

            if (account != null && ES.DenyAnonymous && ((account.UserFlags & (int)IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile) == (int)IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile))
            {
                reason = "You may not enter this region.";
                return false;
            }

            if (account != null && ES.DenyIdentified && ((account.UserFlags & (int)IUserProfileInfo.ProfileFlags.PaymentInfoOnFile) == (int)IUserProfileInfo.ProfileFlags.PaymentInfoOnFile))
            {
                reason = "You may not enter this region.";
                return false;
            }

            if (account != null && ES.DenyTransacted && ((account.UserFlags & (int)IUserProfileInfo.ProfileFlags.PaymentInfoInUse) == (int)IUserProfileInfo.ProfileFlags.PaymentInfoInUse))
            {
                reason = "You may not enter this region.";
                return false;
            }

            long m_Day = 25 * 60 * 60; //Find out day length in seconds
            if (account != null && scene.RegionInfo.RegionSettings.MinimumAge != 0 && (account.Created - Util.UnixTimeSinceEpoch ()) < (scene.RegionInfo.RegionSettings.MinimumAge * m_Day))
            {
                reason = "You may not enter this region.";
                return false;
            }

            if (!ES.PublicAccess)
            {
                reason = "You may not enter this region, Public access has been turned off.";
                return false;
            }

            IAgentConnector AgentConnector = DataManager.DataManager.RequestPlugin<IAgentConnector>();
            IAgentInfo agentInfo = null;
            if (AgentConnector != null)
            {
                agentInfo = AgentConnector.GetAgent(agent.AgentID);
                if (agentInfo == null)
                {
                    AgentConnector.CreateNewAgent(agent.AgentID);
                    agentInfo = AgentConnector.GetAgent(agent.AgentID);
                }
            }
            

            if (agentInfo != null && scene.RegionInfo.AccessLevel > Util.ConvertMaturityToAccessLevel((uint)agentInfo.MaturityRating))
            {
                reason = "The region has too high of a maturity level. Blocking teleport.";
                return false;
            }

            if (agentInfo != null && ES.DenyMinors && (agentInfo.Flags & IAgentFlags.Minor) == IAgentFlags.Minor)
            {
                reason = "The region has too high of a maturity level. Blocking teleport.";
                return false;
            }

            #endregion

            reason = "";
            return true;
        }
Exemplo n.º 52
0
        private byte[] TeleportLocation(Stream request, UUID agentID)
        {
            OSDMap retVal = new OSDMap();

            if (_isInTeleportCurrently)
            {
                retVal.Add("reason", "Duplicate teleport request.");
                retVal.Add("success", OSD.FromBoolean(false));
                return(OSDParser.SerializeLLSDXmlBytes(retVal));
            }
            _isInTeleportCurrently = true;

            OSDMap  rm       = (OSDMap)OSDParser.DeserializeLLSDXml(request);
            OSDMap  pos      = rm["LocationPos"] as OSDMap;
            Vector3 position = new Vector3((float)pos["X"].AsReal(),
                                           (float)pos["Y"].AsReal(),
                                           (float)pos["Z"].AsReal());

            /*OSDMap lookat = rm["LocationLookAt"] as OSDMap;
             * Vector3 lookAt = new Vector3((float)lookat["X"].AsReal(),
             *  (float)lookat["Y"].AsReal(),
             *  (float)lookat["Z"].AsReal());*/
            ulong      RegionHandle = rm["RegionHandle"].AsULong();
            const uint tpFlags      = 16;

            if (m_service.ClientCaps.GetRootCapsService().RegionHandle != m_service.RegionHandle)
            {
                retVal.Add("reason", "Contacted by non-root region for teleport. Protocol implemention is wrong.");
                retVal.Add("success", OSD.FromBoolean(false));
                return(OSDParser.SerializeLLSDXmlBytes(retVal));
            }

            string reason = "";
            int    x, y;

            Util.UlongToInts(RegionHandle, out x, out y);
            GridRegion destination = m_service.Registry.RequestModuleInterface <IGridService>().GetRegionByPosition(
                m_service.ClientCaps.AccountInfo.AllScopeIDs, x, y);
            ISimulationService simService  = m_service.Registry.RequestModuleInterface <ISimulationService>();
            AgentData          ad          = new AgentData();
            AgentCircuitData   circuitData = null;

            if (destination != null)
            {
                simService.RetrieveAgent(m_service.Region, m_service.AgentID, true, out ad, out circuitData);
                if (ad != null)
                {
                    ad.Position = position;
                    ad.Center   = position;
                    circuitData.StartingPosition = position;
                }
            }
            if (destination == null || circuitData == null)
            {
                retVal.Add("reason", "Could not find the destination region.");
                retVal.Add("success", OSD.FromBoolean(false));
                return(OSDParser.SerializeLLSDXmlBytes(retVal));
            }
            circuitData.IsChildAgent = false;

            if (m_agentProcessing.TeleportAgent(ref destination, tpFlags, circuitData, ad,
                                                m_service.AgentID, m_service.RegionID, out reason) || reason == "")
            {
                retVal.Add("success", OSD.FromBoolean(true));
            }
            else
            {
                if (reason != "Already in a teleport")
                {
                    //If this error occurs... don't kick them out of their current region
                    simService.FailedToMoveAgentIntoNewRegion(m_service.AgentID, destination);
                }
                retVal.Add("reason", reason);
                retVal.Add("success", OSD.FromBoolean(false));
            }

            //Send back data
            _isInTeleportCurrently = false;
            return(OSDParser.SerializeLLSDXmlBytes(retVal));
        }
Exemplo n.º 53
0
        /// <summary>
        /// Creates a new bot inworld
        /// </summary>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <param name="cloneAppearanceFrom">UUID of the avatar whos appearance will be copied to give this bot an appearance</param>
        /// <returns>ID of the bot</returns>
        public UUID CreateAvatar (string FirstName, string LastName, IScene s, UUID cloneAppearanceFrom, UUID creatorID, Vector3 startPos)
        {
            Scene scene = (Scene)s;
            AgentCircuitData m_aCircuitData = new AgentCircuitData ();
            m_aCircuitData.child = false;

            //Add the circuit data so they can login
            m_aCircuitData.circuitcode = (uint)Util.RandomClass.Next();

            m_aCircuitData.Appearance = GetAppearance (cloneAppearanceFrom, s);//Sets up appearance
            if (m_aCircuitData.Appearance == null)
            {
                m_aCircuitData.Appearance = new AvatarAppearance ();
                m_aCircuitData.Appearance.Wearables = AvatarWearable.DefaultWearables;
            }
            //Create the new bot data
            Bot m_character = new Bot (scene, m_aCircuitData, creatorID);

            m_character.FirstName = FirstName;
            m_character.LastName = LastName;
            m_aCircuitData.AgentID = m_character.AgentId;
            m_aCircuitData.Appearance.Owner = m_character.AgentId;
            List<AvatarAttachment> attachments = m_aCircuitData.Appearance.GetAttachments ();

            m_aCircuitData.Appearance.ClearAttachments ();
            for (int i = 0; i < attachments.Count; i++)
            {
                InventoryItemBase item = scene.InventoryService.GetItem (new InventoryItemBase (attachments[i].ItemID));
                if (item != null)
                {
                    item.ID = UUID.Random ();
                    item.Owner = m_character.AgentId;
                    item.Folder = UUID.Zero;
                    scene.InventoryService.AddItem (item);
                    //Now fix the ItemID
                    m_aCircuitData.Appearance.SetAttachment (attachments[i].AttachPoint, item.ID, attachments[i].AssetID);
                }
            }

            scene.AuthenticateHandler.AgentCircuits.Add (m_character.CircuitCode, m_aCircuitData);
            //This adds them to the scene and sets them inworld
            scene.AddNewClient (m_character);
            m_character.Initialize ();
            IScenePresence SP = scene.GetScenePresence (m_character.AgentId);
            SP.MakeRootAgent (m_character.StartPos, false);
            //Move them
            SP.Teleport (startPos);

            IAvatarAppearanceModule appearance = SP.RequestModuleInterface<IAvatarAppearanceModule> ();
            appearance.Appearance.SetAppearance (appearance.Appearance.Texture, appearance.Appearance.VisualParams);
            appearance.SendAvatarDataToAllAgents (true);
            appearance.SendAppearanceToAllOtherAgents ();
            appearance.SendOtherAgentsAppearanceToMe ();
            IAvatarFactory avFactory = scene.RequestModuleInterface<IAvatarFactory> ();
            if (avFactory != null)
                avFactory.QueueInitialAppearanceSend (SP.UUID);

            //Save them in the bots list
            m_bots.Add(m_character.AgentId, m_character);

            m_log.Info("[RexBotManager]: Added bot " + m_character.Name + " to scene.");

            //Return their UUID
            return m_character.AgentId;
        }
        public void TestSameSimulatorNeighbouringRegionsTeleportV1()
        {
            TestHelpers.InMethod();
            //            TestHelpers.EnableLogging();

            BaseHttpServer httpServer = new BaseHttpServer(99999);

            MainServer.AddHttpServer(httpServer);
            MainServer.Instance = httpServer;

            AttachmentsModule              attModA = new AttachmentsModule();
            AttachmentsModule              attModB = new AttachmentsModule();
            EntityTransferModule           etmA    = new EntityTransferModule();
            EntityTransferModule           etmB    = new EntityTransferModule();
            LocalSimulationConnectorModule lscm    = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);
            IConfig entityTransferConfig = config.AddConfig("EntityTransfer");

            // In order to run a single threaded regression test we do not want the entity transfer module waiting
            // for a callback from the destination scene before removing its avatar data.
            entityTransferConfig.Set("wait_for_callback", false);

            modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule");

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(
                sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule());
            SceneHelpers.SetupSceneModules(
                sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule());

            // FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour
            lscm.ServiceVersion = "SIMULATION/0.1";

            UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1);

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32);

            InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20);

            sceneA.AttachmentsModule.RezSingleAttachmentFromInventory(
                beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest);

            Vector3 teleportPosition = new Vector3(10, 11, 12);
            Vector3 teleportLookAt   = new Vector3(20, 21, 22);

            m_numberOfAttachEventsFired = 0;
            sceneA.RequestTeleportLocation(
                beforeTeleportSp.ControllingClient,
                sceneB.RegionInfo.RegionHandle,
                teleportPosition,
                teleportLookAt,
                (uint)TeleportFlags.ViaLocation);

            destinationTestClients[0].CompleteMovement();

            // Check attachments have made it into sceneB
            ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID);

            // This is appearance data, as opposed to actually rezzed attachments
            List <AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments();

            Assert.That(sceneBAttachments.Count, Is.EqualTo(1));
            Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest));
            Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID));
            Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID));
            Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));

            // This is the actual attachment
            List <SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments();

            Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1));
            SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0];

            Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name));
            Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest));

            Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1));

            // Check attachments have been removed from sceneA
            ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID);

            // Since this is appearance data, it is still present on the child avatar!
            List <AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments();

            Assert.That(sceneAAttachments.Count, Is.EqualTo(1));
            Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));

            // This is the actual attachment, which should no longer exist
            List <SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments();

            Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0));

            Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0));

            // Check events
            Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
        }
Exemplo n.º 55
0
        /// <summary>
        /// Creates a new bot inworld
        /// </summary>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <param name="cloneAppearanceFrom">UUID of the avatar whos appearance will be copied to give this bot an appearance</param>
        /// <returns>ID of the bot</returns>
        public UUID CreateAStarAvatar(string FirstName, string LastName, UUID cloneAppearanceFrom)
        {
            //Create the new bot data
            AStarBot m_character = new AStarBot(m_scene);

            m_character.FirstName = FirstName;
            m_character.LastName = LastName;

            AgentCircuitData m_aCircuitData = new AgentCircuitData();
            m_aCircuitData.child = false;

            m_aCircuitData.firstname = m_character.FirstName;
            m_aCircuitData.lastname = m_character.LastName;

            //Add the circuit data so they can login
            m_aCircuitData.circuitcode = m_character.CircuitCode;

            m_aCircuitData.Appearance = GetAppearance(cloneAppearanceFrom);//Sets up appearance

            m_scene.AuthenticateHandler.AgentCircuits.Add(m_character.CircuitCode, m_aCircuitData);
            //This adds them to the scene and sets them inworld
            m_scene.AddNewClient(m_character);

            m_character.Initialize();

            ScenePresence SP = m_scene.GetScenePresence(m_character.AgentId);
            SP.Appearance.SetAppearance(SP.Appearance.Texture, SP.Appearance.VisualParams);
            SP.SendAppearanceToAllOtherAgents();
            SP.SendAvatarDataToAllAgents();
            m_character.Initialize(SP);//Tell the bot about the SP

            //Save them in the bots list
            m_bots.Add(m_character.AgentId, m_character);

            m_log.Info("[RexBotManager]: Added AStar bot " + m_character.Name + " to scene.");

            //Return their UUID
            return m_character.AgentId;
        }
        public void TestSameSimulatorNeighbouringRegionsTeleportV2()
        {
            TestHelpers.InMethod();
            //            TestHelpers.EnableLogging();

            BaseHttpServer httpServer = new BaseHttpServer(99999);

            MainServer.AddHttpServer(httpServer);
            MainServer.Instance = httpServer;

            AttachmentsModule              attModA = new AttachmentsModule();
            AttachmentsModule              attModB = new AttachmentsModule();
            EntityTransferModule           etmA    = new EntityTransferModule();
            EntityTransferModule           etmB    = new EntityTransferModule();
            LocalSimulationConnectorModule lscm    = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);

            modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule");

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(
                sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule());
            SceneHelpers.SetupSceneModules(
                sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule());

            UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1);

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32);

            Assert.That(destinationTestClients.Count, Is.EqualTo(1));
            Assert.That(destinationTestClients[0], Is.Not.Null);

            InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20);

            sceneA.AttachmentsModule.RezSingleAttachmentFromInventory(
                beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest);

            Vector3 teleportPosition = new Vector3(10, 11, 12);
            Vector3 teleportLookAt   = new Vector3(20, 21, 22);

            // Here, we need to make clientA's receipt of SendRegionTeleport trigger clientB's CompleteMovement().  This
            // is to operate the teleport V2 mechanism where the EntityTransferModule will first request the client to
            // CompleteMovement to the region and then call UpdateAgent to the destination region to confirm the receipt
            // Both these operations will occur on different threads and will wait for each other.
            // We have to do this via ThreadPool directly since FireAndForget has been switched to sync for the V1
            // test protocol, where we are trying to avoid unpredictable async operations in regression tests.
            tc.OnTestClientSendRegionTeleport
                += (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL)
                   => ThreadPool.UnsafeQueueUserWorkItem(o => destinationTestClients[0].CompleteMovement(), null);

            m_numberOfAttachEventsFired = 0;
            sceneA.RequestTeleportLocation(
                beforeTeleportSp.ControllingClient,
                sceneB.RegionInfo.RegionHandle,
                teleportPosition,
                teleportLookAt,
                (uint)TeleportFlags.ViaLocation);

            // Check attachments have made it into sceneB
            ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID);

            // This is appearance data, as opposed to actually rezzed attachments
            List <AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments();

            Assert.That(sceneBAttachments.Count, Is.EqualTo(1));
            Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest));
            Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID));
            Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID));
            Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));

            // This is the actual attachment
            List <SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments();

            Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1));
            SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0];

            Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name));
            Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest));

            Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1));

            // Check attachments have been removed from sceneA
            ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID);

            // Since this is appearance data, it is still present on the child avatar!
            List <AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments();

            Assert.That(sceneAAttachments.Count, Is.EqualTo(1));
            Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));

            // This is the actual attachment, which should no longer exist
            List <SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments();

            Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0));

            Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0));

            // Check events
            Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
        }
Exemplo n.º 57
0
        protected virtual bool AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AgentCircuitData sessionInfo)
        {
            IScenePresence SP; 
            if (!m_scene.TryGetScenePresence(agentID, out SP))
            {
                // Create the LLUDPClient
                LLUDPClient udpClient =  new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
                // Create the LLClientView
                LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
                client.OnLogout += LogoutHandler;

                client.DisableFacelights = m_disableFacelights;

                // Start the IClientAPI
                m_scene.AddNewClient(client);
                m_currentClients.Add (client);
            }
            else
            {
                m_log.DebugFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode ({0}) from {1} at {2} ",
                    circuitCode, agentID, remoteEndPoint);
            }
            return true;
        }
Exemplo n.º 58
0
        /// <summary>
        /// Login procedure, as copied from superclass.
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="passwd"></param>
        /// <param name="startLocation"></param>
        /// <param name="scopeID"></param>
        /// <param name="clientVersion"></param>
        /// <param name="clientIP">The very important TCP/IP EndPoint of the client</param>
        /// <returns></returns>
        /// <remarks>You need to change bits and pieces of this method</remarks>
        public new LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID,
                                       string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP)
        {
            bool success = false;
            UUID session = UUID.Random();

            try
            {
                //
                // Get the account and check that it exists
                //
                UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName);
                if (account == null)
                {
                    // Account doesn't exist. Is this a user from an external ID provider?
                    //
                    // <your code here>
                    //
                    // After verification, your code should create a UserAccount object, filled out properly.
                    // Do not store that account object persistently; we don't want to be creating local accounts
                    // for external users! Create and fill out a UserAccount object, because it has the information
                    // that the rest of the code needs.

                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: user not found");
                    return(LLFailedLoginResponse.UserProblem);
                }

                if (account.UserLevel < m_MinLoginLevel)
                {
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: login is blocked for user level {0}", account.UserLevel);
                    return(LLFailedLoginResponse.LoginBlockedProblem);
                }

                // If a scope id is requested, check that the account is in
                // that scope, or unscoped.
                //
                if (scopeID != UUID.Zero)
                {
                    if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero)
                    {
                        m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: user not found");
                        return(LLFailedLoginResponse.UserProblem);
                    }
                }
                else
                {
                    scopeID = account.ScopeID;
                }

                //
                // Authenticate this user
                //
                // Local users and external users will need completely different authentication procedures.
                // The piece of code below is for local users who authenticate with a password.
                //
                if (!passwd.StartsWith("$1$"))
                {
                    passwd = "$1$" + Util.Md5Hash(passwd);
                }
                passwd = passwd.Remove(0, 3); //remove $1$
                string token         = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
                UUID   secureSession = UUID.Zero;
                if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
                {
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: authentication failed");
                    return(LLFailedLoginResponse.UserProblem);
                }

                //
                // Get the user's inventory
                //
                // m_RequireInventory is set to false in .ini, therefore inventory is not required for login.
                // If you want to change this state of affairs and let external users have local inventory,
                // you need to think carefully about how to do that.
                //
                if (m_RequireInventory && m_InventoryService == null)
                {
                    m_log.WarnFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: inventory service not set up");
                    return(LLFailedLoginResponse.InventoryProblem);
                }
                List <InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
                if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
                {
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: unable to retrieve user inventory");
                    return(LLFailedLoginResponse.InventoryProblem);
                }

                if (inventorySkel == null)
                {
                    inventorySkel = new List <InventoryFolderBase>();
                }

                // Get active gestures
                List <InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
                m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);

                //
                // From here on, things should be exactly the same for all users
                //

                //
                // Login the presence
                //
                if (m_PresenceService != null)
                {
                    success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);
                    if (!success)
                    {
                        m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: could not login presence");
                        return(LLFailedLoginResponse.GridProblem);
                    }
                }

                //
                // Change Online status and get the home region
                //
                GridRegion   home   = null;
                GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString());
                if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null)
                {
                    home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);
                }
                if (guinfo == null)
                {
                    // something went wrong, make something up, so that we don't have to test this anywhere else
                    guinfo = new GridUserInfo();
                    guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
                }

                //
                // Find the destination region/grid
                //
                string where = string.Empty;
                Vector3       position    = Vector3.Zero;
                Vector3       lookAt      = Vector3.Zero;
                GridRegion    gatekeeper  = null;
                TeleportFlags flags       = TeleportFlags.Default;
                GridRegion    destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags);
                if (destination == null)
                {
                    m_PresenceService.LogoutAgent(session);
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: destination not found");
                    return(LLFailedLoginResponse.GridProblem);
                }

                //
                // Get the avatar
                //
                AvatarAppearance avatar = null;
                if (m_AvatarService != null)
                {
                    avatar = m_AvatarService.GetAppearance(account.PrincipalID);
                }

                //
                // Instantiate/get the simulation interface and launch an agent at the destination
                //
                string           reason   = string.Empty;
                GridRegion       dest     = null;
                AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where,
                                                              clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest);

                if (aCircuit == null)
                {
                    m_PresenceService.LogoutAgent(session);
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: {0}", reason);
                    return(new LLFailedLoginResponse("key", reason, "false"));
                }
                // Get Friends list
                FriendInfo[] friendsList = new FriendInfo[0];
                if (m_FriendsService != null)
                {
                    friendsList = m_FriendsService.GetFriends(account.PrincipalID);
                    m_log.DebugFormat("[DIVA LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
                }

                //
                // Finally, fill out the response and return it
                //
                LLLoginResponse response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
                                                               where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP, m_MapTileURL, m_SearchURL, m_Currency, m_DSTZone,
                                                               string.Empty, string.Empty, string.Empty);

                m_log.DebugFormat("[DIVA LLOGIN SERVICE]: All clear. Sending login response to client.");
                return(response);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[DIVA LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace);
                if (m_PresenceService != null)
                {
                    m_PresenceService.LogoutAgent(session);
                }
                return(LLFailedLoginResponse.InternalError);
            }
        }
Exemplo n.º 59
0
        public bool DoCreateChildAgentCall(RegionInfo region, AgentCircuitData aCircuit, string authKey, out string reason)
        {
            // Eventually, we want to use a caps url instead of the agentID
            string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + aCircuit.AgentID + "/";
            //Console.WriteLine("   >>> DoCreateChildAgentCall <<< " + uri);

            HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
            AgentCreateRequest.Method = "POST";
            AgentCreateRequest.ContentType = "application/json";
            AgentCreateRequest.Timeout = 10000;
            //AgentCreateRequest.KeepAlive = false;

            AgentCreateRequest.Headers["authorization"] = GenerateAuthorization();

            reason = String.Empty;

            // Fill it in
            OSDMap args = null;
            try
            {
                args = aCircuit.PackAgentCircuitData();
            }
            catch (Exception e)
            {
                m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
                reason = "PackAgentCircuitData exception";
                return false;
            }

            // Add the regionhandle of the destination region
            ulong regionHandle = GetRegionHandle(region.RegionHandle);
            args["destination_handle"] = OSD.FromString(regionHandle.ToString());

            string strBuffer = "";
            byte[] buffer = new byte[1];
            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                UTF8Encoding str = new UTF8Encoding();
                buffer = str.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
                // ignore. buffer will be empty, caller should check.
            }

            Stream os = null;
            try
            { // send the Post
                AgentCreateRequest.ContentLength = buffer.Length;   //Count bytes to send
                os = AgentCreateRequest.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);         //Send it
                os.Close();
                //m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
            }
            //catch (WebException ex)
            catch
            {
                //m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
                reason = "cannot contact remote region";
                return false;
            }
            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");

            try
            {
                WebResponse webResponse = AgentCreateRequest.GetResponse();
                if (webResponse == null)
                {
                    m_log.Info("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
                    reason = "response is null";
                    return false;
                }

                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                string response = sr.ReadToEnd().Trim();
                sr.Close();
                m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response);
                if (String.IsNullOrEmpty(response))
                {
                    reason = "response is empty";
                    return false;
                }

                try
                {
                    // we assume we got an OSDMap back
                    OSDMap r = GetOSDMap(response);
                    bool success = r["success"].AsBoolean();
                    reason = r["reason"].AsString();
                    return success;
                }
                catch (NullReferenceException e)
                {
                    m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message);

                    // check for old style response
                    if (response.ToLower().StartsWith("true"))
                        return true;

                    reason = "null reference exception";
                    return false;
                }
            }
            catch (WebException ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
                reason = "web exception";
                return false;
            }
        }
Exemplo n.º 60
0
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            if (args == null)
            {
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            // retrieve the input arguments
            int    x = 0, y = 0;
            UUID   uuid            = UUID.Zero;
            string regionname      = string.Empty;
            string gatekeeper_host = string.Empty;
            int    gatekeeper_port = 0;

            if (args.ContainsKey("gatekeeper_host") && args["gatekeeper_host"] != null)
            {
                gatekeeper_host = args["gatekeeper_host"].AsString();
            }
            if (args.ContainsKey("gatekeeper_port") && args["gatekeeper_port"] != null)
            {
                Int32.TryParse(args["gatekeeper_port"].AsString(), out gatekeeper_port);
            }

            GridRegion gatekeeper = new GridRegion();

            gatekeeper.ExternalHostName = gatekeeper_host;
            gatekeeper.HttpPort         = (uint)gatekeeper_port;
            gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);

            if (args.ContainsKey("destination_x") && args["destination_x"] != null)
            {
                Int32.TryParse(args["destination_x"].AsString(), out x);
            }
            else
            {
                m_log.WarnFormat("  -- request didn't have destination_x");
            }
            if (args.ContainsKey("destination_y") && args["destination_y"] != null)
            {
                Int32.TryParse(args["destination_y"].AsString(), out y);
            }
            else
            {
                m_log.WarnFormat("  -- request didn't have destination_y");
            }
            if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
            {
                UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
            }
            if (args.ContainsKey("destination_name") && args["destination_name"] != null)
            {
                regionname = args["destination_name"].ToString();
            }

            GridRegion destination = new GridRegion();

            destination.RegionID   = uuid;
            destination.RegionLocX = x;
            destination.RegionLocY = y;
            destination.RegionName = regionname;

            AgentCircuitData aCircuit = new AgentCircuitData();

            try
            {
                aCircuit.UnpackAgentCircuitData(args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[HOME AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            OSDMap resp   = new OSDMap(2);
            string reason = String.Empty;

            bool result = m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, out reason);

            resp["reason"]  = OSD.FromString(reason);
            resp["success"] = OSD.FromBoolean(result);

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }