public bool IsAuthorizedForRegion(GridRegion region, AgentCircuitData agent, bool isRootAgent, out string reason)
        {
            ISceneManager manager = m_registry.RequestModuleInterface<ISceneManager>();
            if (manager != null)
            {
#if (!ISWIN)
                foreach (IScene scene in manager.GetAllScenes())
                {
                    if (scene.RegionInfo.RegionID == region.RegionID)
                    {
                        //Found the region, check permissions
                        return scene.Permissions.AllowedIncomingAgent(agent, isRootAgent, out reason);
                    }
                }
#else
                foreach (IScene scene in manager.GetAllScenes().Where(scene => scene.RegionInfo.RegionID == region.RegionID))
                {
                    //Found the region, check permissions
                    return scene.Permissions.AllowedIncomingAgent(agent, isRootAgent, out reason);
                }
#endif
            }
            reason = "Not Authorized as region does not exist.";
            return false;
        }
        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string myipaddress, out string reason)
        {
            // MainConsole.Instance.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: CreateAgent start");

            myipaddress = String.Empty;
            reason = String.Empty;

            if (destination == null)
            {
                MainConsole.Instance.Debug ("[GATEKEEPER SERVICE CONNECTOR]: Given destination is null");
                return false;
            }

            string uri = (destination.ServerURI.EndsWith ("/") ? destination.ServerURI : (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 = WebUtils.PostToService (uri, args, true, true);
                if (result["Success"].AsBoolean ())
                {
                    OSDMap unpacked = (OSDMap)result["_Result"];

                    if (unpacked != null)
                    {
                        reason = unpacked["reason"].AsString ();
                        myipaddress = unpacked["your_ip"].AsString ();
                        return unpacked["success"].AsBoolean ();
                    }
                }

                reason = result["Message"] != null ? result["Message"].AsString () : "error";
                return false;
            }
            catch (Exception e)
            {
                MainConsole.Instance.Warn ("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString ());
                reason = e.Message;
            }

            return false;
        }
 /// <summary>
 ///   Add information about a new circuit so that later on we can authenticate a new client session.
 /// </summary>
 /// <param name = "circuitCode"></param>
 /// <param name = "agentData"></param>
 public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData)
 {
     lock (AgentCircuits)
     {
         AgentCircuits[circuitCode] = agentData;
     }
 }
示例#4
0
        public static OSDMap ArrivedAtDestination(UUID AgentID, int DrawDistance, AgentCircuitData circuit,
                                                  ulong requestingRegion)
        {
            OSDMap llsdBody = new OSDMap
                                  {
                                      {"AgentID", AgentID},
                                      {"DrawDistance", DrawDistance},
                                      {"Circuit", circuit.PackAgentCircuitData()}
                                  };

            return buildEvent("ArrivedAtDestination", llsdBody, AgentID, requestingRegion);
        }
示例#5
0
        /// <summary>
        /// </summary>
        /// <param name = "acircuit"></param>
        /// <returns>uuid[;endpoint[;name]]</returns>
        public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
        {
            if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
            {
                string agentsURI = acircuit.ServiceURLs["HomeURI"].ToString();
                if (!agentsURI.EndsWith("/"))
                    agentsURI += "/";

                // This is ugly, but there's no other way, given that the name is changed
                // in the agent circuit data for foreigners
                if (acircuit.lastname.Contains("@"))
                {
                    string[] parts = acircuit.firstname.Split(new[] {'.'});
                    if (parts.Length == 2)
                        return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
                }
                return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + acircuit.firstname + " " +
                       acircuit.lastname;
            }
            else
                return acircuit.AgentID.ToString();
        }
示例#6
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 UpdateAgentData(AgentCircuitData agentData)
        {
            if (AgentCircuits.ContainsKey(agentData.circuitcode))
            {
                AgentCircuits[agentData.circuitcode].startpos = agentData.startpos;

                // Updated for when we don't know them before calling Scene.NewUserConnection
                AgentCircuits[agentData.circuitcode].SecureSessionID = agentData.SecureSessionID;
                AgentCircuits[agentData.circuitcode].SessionID = agentData.SessionID;

                // MainConsole.Instance.Debug("update user start pos is " + agentData.startpos.X + " , " + agentData.startpos.Y + " , " + agentData.startpos.Z); //Un-Commented for debugging -VS
            }
        }
示例#8
0
        public string CreateCAPS (UUID AgentID, string CAPSBase, ulong regionHandle, bool IsRootAgent, AgentCircuitData circuitData, uint port)
        {
            //Now make sure we didn't use an old one or something
            IClientCapsService service = GetOrCreateClientCapsService(AgentID);
            IRegionClientCapsService clientService = service.GetOrCreateCapsService(regionHandle, CAPSBase, circuitData, port);
            
            //Fix the root agent status
            clientService.RootAgent = IsRootAgent;

            m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UserLogin", AgentID);
            MainConsole.Instance.Debug("[CapsService]: Adding Caps URL " + clientService.CapsUrl + " for agent " + AgentID);
            return clientService.CapsUrl;
        }
示例#9
0
 /// <summary>
 /// Create a Caps URL for the given user/region. Called normally by the EventQueueService or the LLLoginService on login
 /// </summary>
 /// <param name="AgentID"></param>
 /// <param name="CAPSBase"></param>
 /// <param name="regionHandle"></param>
 /// <param name="IsRootAgent">Will this child be a root agent</param>
 /// <param name="circuitData"></param>
 /// <returns></returns>
 public string CreateCAPS(UUID AgentID, string CAPSBase, ulong regionHandle, bool IsRootAgent, AgentCircuitData circuitData)
 {
     return CreateCAPS (AgentID, CAPSBase, regionHandle, IsRootAgent, circuitData, 0);
 }
示例#10
0
        public virtual bool TeleportAgent(ref GridRegion destination, uint TeleportFlags, int DrawDistance,
                                          AgentCircuitData circuit, AgentData agentData, UUID AgentID,
                                          ulong requestingRegion,
                                          out string reason)
        {
            IClientCapsService clientCaps =
                m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
            IRegionClientCapsService regionCaps = clientCaps.GetCapsService(requestingRegion);

            if (regionCaps == null || !regionCaps.RootAgent)
            {
                reason = "";
                ResetFromTransit(AgentID);
                return false;
            }

            bool result = false;
            try
            {
                bool callWasCanceled = false;

                ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
                if (SimulationService != null)
                {
                    //Set the user in transit so that we block duplicate tps and reset any cancelations
                    if (!SetUserInTransit(AgentID))
                    {
                        reason = "Already in a teleport";
                        return false;
                    }

                    bool useCallbacks = false;
                    //Note: we have to pull the new grid region info as the one from the region cannot be trusted
                    GridRegion oldRegion = destination;
                    IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
                    if (GridService != null)
                    {
                        destination = GridService.GetRegionByUUID(clientCaps.AccountInfo.AllScopeIDs, destination.RegionID);
                        if (destination == null) //If its not in this grid
                            destination = oldRegion;
                        //Inform the client of the neighbor if needed
                        circuit.child = false; //Force child status to the correct type
                        circuit.roothandle = destination.RegionHandle;
                        if (!InformClientOfNeighbor(AgentID, requestingRegion, circuit, ref destination, TeleportFlags,
                                                    agentData, out reason, out useCallbacks))
                        {
                            ResetFromTransit(AgentID);
                            return false;
                        }
                    }
                    else
                    {
                        reason = "Could not find the grid service";
                        ResetFromTransit(AgentID);
                        return false;
                    }

                    IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>();

                    IRegionClientCapsService otherRegion = clientCaps.GetCapsService(destination.RegionHandle);

                    EQService.TeleportFinishEvent(destination.RegionHandle, destination.Access,
                                                  otherRegion.LoopbackRegionIP,
                                                  otherRegion.CircuitData.RegionUDPPort,
                                                  otherRegion.CapsUrl,
                                                  4, AgentID, TeleportFlags,
                                                  destination.RegionSizeX, destination.RegionSizeY,
                                                  requestingRegion);

                    // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
                    // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
                    // that the client contacted the destination before we send the attachments and close things here.

                    result = !useCallbacks || WaitForCallback(AgentID, out callWasCanceled);
                    if (!result)
                    {
                        //It says it failed, lets call the sim and check
                        AgentData data = null;
                        AgentCircuitData circuitData;
                        result = SimulationService.RetrieveAgent(destination, AgentID, false, out data, out circuitData);
                    }
                    if (!result)
                    {
                        if (!callWasCanceled)
                        {
                            MainConsole.Instance.Warn("[AgentProcessing]: Callback never came for teleporting agent " +
                                       AgentID + ". Resetting.");
                        }
                        //Close the agent at the place we just created if it isn't a neighbor
                        // 7/22 -- Kill the agent no matter what, it obviously is having issues getting there
                        //if (IsOutsideView (regionCaps.RegionX, destination.RegionLocX, regionCaps.Region.RegionSizeX, destination.RegionSizeX,
                        //    regionCaps.RegionY, destination.RegionLocY, regionCaps.Region.RegionSizeY, destination.RegionSizeY))
                        {
                            SimulationService.CloseAgent(destination, AgentID);
                            clientCaps.RemoveCAPS(destination.RegionHandle);
                        }
                        reason = !callWasCanceled ? "The teleport timed out" : "Cancelled";
                    }
                    else
                    {
                        //Fix the root agent status
                        otherRegion.RootAgent = true;
                        regionCaps.RootAgent = false;

                        // Next, let's close the child agent connections that are too far away.
                        //if (useCallbacks || oldRegion != destination)//Only close it if we are using callbacks (Aurora region)
                        //Why? OpenSim regions need closed too, even if the protocol is kinda stupid
                        CloseNeighborAgents(regionCaps.Region, destination, AgentID);
                        reason = "";
                    }
                }
                else
                    reason = "No SimulationService found!";
            }
            catch (Exception ex)
            {
                MainConsole.Instance.WarnFormat("[AgentProcessing]: Exception occured during agent teleport, {0}", ex);
                reason = "Exception occured.";
            }
            //All done
            ResetFromTransit(AgentID);
            return result;
        }
        protected bool Authenticate(AgentCircuitData aCircuit)
        {
            if (!CheckAddress (aCircuit.ServiceSessionID))
                return false;

            string userURL = string.Empty;
            if (aCircuit.ServiceURLs.ContainsKey ("HomeURI"))
                userURL = aCircuit.ServiceURLs["HomeURI"].ToString ();

            if (userURL == string.Empty)
            {
                MainConsole.Instance.DebugFormat ("[GATEKEEPER SERVICE]: Agent did not provide an authentication server URL");
                return false;
            }

            if (userURL == m_ExternalName)
                return m_UserAgentService.VerifyAgent (aCircuit.SessionID, aCircuit.ServiceSessionID);
            else
            {
                //                Object[] args = new Object[] { userURL };
                IUserAgentService userAgentService = new UserAgentServiceConnector (userURL);
                if (userAgentService != null)
                {
                    try
                    {
                        return userAgentService.VerifyAgent (aCircuit.SessionID, aCircuit.ServiceSessionID);
                    }
                    catch
                    {
                        MainConsole.Instance.DebugFormat ("[GATEKEEPER SERVICE]: Unable to contact authentication service at {0}", userURL);
                        return false;
                    }
                }
            }

            return false;
        }
示例#12
0
        public virtual LoginAgentArgs LoginAgent(GridRegion region, AgentCircuitData aCircuit)
        {
            object retVal = base.DoRemoteByHTTP(_capsURL, region, aCircuit);
            if (retVal != null || m_doRemoteOnly)
            {
                if (retVal == null)
                {
                    ReadRemoteCapsPassword();
                    retVal = base.DoRemoteByHTTP(_capsURL, region, aCircuit);
                }
                return retVal == null ? null : (LoginAgentArgs)retVal;
            }

            bool success = false;
            string seedCap = "";
            string reason = "Could not find the simulation service";
            ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
            ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
            if (SimulationService != null)
            {
                // The client is in the region, we need to make sure it gets the right Caps
                // If CreateAgent is successful, it passes back a OSDMap of params that the client 
                //    wants to inform us about, and it includes the Caps SEED url for the region
                IRegionClientCapsService regionClientCaps = null;
                IClientCapsService clientCaps = null;
                if (capsService != null)
                {
                    //Remove any previous users
                    seedCap = capsService.CreateCAPS(aCircuit.AgentID,
                        CapsUtil.GetCapsSeedPath(aCircuit.CapsPath),
                        region.RegionHandle, true, aCircuit, 0);

                    clientCaps = capsService.GetClientCapsService(aCircuit.AgentID);
                    regionClientCaps = clientCaps.GetCapsService(region.RegionHandle);
                }


                ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService>();
                if (commsService != null)
                    commsService.GetUrlsForUser(region, aCircuit.AgentID);
                        //Make sure that we make userURLs if we need to

                int requestedUDPPort = 0;
                // As we are creating the agent, we must also initialize the CapsService for the agent
                success = CreateAgent(region, regionClientCaps, ref aCircuit, SimulationService, ref requestedUDPPort, out reason);
                if (requestedUDPPort == 0)
                    requestedUDPPort = region.ExternalEndPoint.Port;
                aCircuit.RegionUDPPort = requestedUDPPort;

                if (!success) // If it failed, do not set up any CapsService for the client
                {
                    if (reason != "")
                    {
                        try
                        {
                            OSDMap reasonMap = OSDParser.DeserializeJson(reason) as OSDMap;
                            if (reasonMap != null && reasonMap.ContainsKey("Reason"))
                                reason = reasonMap["Reason"].AsString();
                        }
                        catch
                        {
                            //If its already not JSON, it'll throw an exception, catch it
                        }
                    }
                    //Delete the Caps!
                    IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>();
                    if (agentProcessor != null && capsService != null)
                        agentProcessor.LogoutAgent(regionClientCaps, true);
                    else if (capsService != null)
                        capsService.RemoveCAPS(aCircuit.AgentID);
                    return new LoginAgentArgs { Success = success, CircuitData = aCircuit, Reason = reason, SeedCap = seedCap };
                }

                IPAddress ipAddress = regionClientCaps.Region.ExternalEndPoint.Address;
                if (capsService != null && reason != "")
                {
                    try
                    {
                        OSDMap responseMap = (OSDMap) OSDParser.DeserializeJson(reason);
                        OSDMap SimSeedCaps = (OSDMap) responseMap["CapsUrls"];
                        if (responseMap.ContainsKey("OurIPForClient"))
                        {
                            string ip = responseMap["OurIPForClient"].AsString();
                            if (!IPAddress.TryParse(ip, out ipAddress))
#pragma warning disable 618
                                ipAddress = Dns.GetHostByName(ip).AddressList[0];
#pragma warning restore 618
                        }
                        region.ExternalEndPoint.Address = ipAddress;
                            //Fix this so that it gets sent to the client that way
                        regionClientCaps.AddCAPS(SimSeedCaps);
                        regionClientCaps = clientCaps.GetCapsService(region.RegionHandle);
                        regionClientCaps.LoopbackRegionIP = ipAddress;
                        regionClientCaps.CircuitData.RegionUDPPort = requestedUDPPort;
                        regionClientCaps.RootAgent = true;
                    }
                    catch
                    {
                        //Delete the Caps!
                        IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>();
                        if (agentProcessor != null && capsService != null)
                            agentProcessor.LogoutAgent(regionClientCaps, true);
                        else if (capsService != null)
                            capsService.RemoveCAPS(aCircuit.AgentID);
                        success = false;
                    }
                }
            }
            return new LoginAgentArgs { Success = success, CircuitData = aCircuit, Reason = reason, SeedCap = seedCap };
        }
示例#13
0
        public virtual void EnableChildAgents(UUID AgentID, ulong requestingRegion, int DrawDistance,
                                              AgentCircuitData circuit)
        {
            Util.FireAndForget((o) =>
                                   {
                                       int count = 0;
                                       int x, y;
                                       ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
                                       IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);
                                       Util.UlongToInts(requestingRegion, out x, out y);
                                       GridRegion ourRegion =
                                           m_registry.RequestModuleInterface<IGridService>().GetRegionByPosition(
                                               clientCaps.AccountInfo.AllScopeIDs, x, y);
                                       if (ourRegion == null)
                                       {
                                           MainConsole.Instance.Info(
                                               "[AgentProcessing]: Failed to inform neighbors about new agent, could not find our region.");
                                           return;
                                       }
                                       List<GridRegion> neighbors = GetNeighbors(clientCaps.AccountInfo.AllScopeIDs, ourRegion, DrawDistance);

                                       clientCaps.GetRootCapsService().CircuitData.DrawDistance = DrawDistance;
                                           //Fix the root agents dd
                                       foreach (GridRegion neighbor in neighbors)
                                       {
                                           if (neighbor.RegionHandle != requestingRegion &&
                                               clientCaps.GetCapsService(neighbor.RegionHandle) == null)
                                           {
                                               string reason;
                                               AgentCircuitData regionCircuitData =
                                                   clientCaps.GetRootCapsService().CircuitData.Copy();
                                               GridRegion nCopy = neighbor;
                                               regionCircuitData.child = true; //Fix child agent status
                                               regionCircuitData.roothandle = requestingRegion;
                                               regionCircuitData.reallyischild = true;
                                               regionCircuitData.DrawDistance = DrawDistance;
                                               bool useCallbacks = false;
                                               InformClientOfNeighbor(AgentID, requestingRegion, regionCircuitData,
                                                                      ref nCopy,
                                                                      (uint) TeleportFlags.Default, null, out reason,
                                                                      out useCallbacks);
                                           }
                                           count++;
                                       }
                                   });
        }
示例#14
0
        protected AgentCircuitData MakeAgent(GridRegion region, UserAccount account,
            AvatarAppearance appearance, UUID session, UUID secureSession, uint circuit, Vector3 position,
            IPEndPoint clientIP)
        {
            AgentCircuitData aCircuit = new AgentCircuitData
                                            {
                                                AgentID = account.PrincipalID,
                                                Appearance = appearance ?? new AvatarAppearance(account.PrincipalID),
                                                CapsPath = CapsUtil.GetRandomCapsObjectPath(),
                                                child = false,
                                                circuitcode = circuit,
                                                SecureSessionID = secureSession,
                                                SessionID = session,
                                                startpos = position,
                                                IPAddress = clientIP.Address.ToString(),
                                                ClientIPEndPoint = clientIP
                                            };


            // the first login agent is root

            return aCircuit;
        }
示例#15
0
        public virtual bool CrossAgent(GridRegion crossingRegion, Vector3 pos,
                                       Vector3 velocity, AgentCircuitData circuit, AgentData cAgent, UUID AgentID,
                                       ulong requestingRegion, out string reason)
        {
            try
            {
                IClientCapsService clientCaps =
                    m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
                IRegionClientCapsService requestingRegionCaps = clientCaps.GetCapsService(requestingRegion);
                ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
                if (SimulationService != null)
                {
                    //Note: we have to pull the new grid region info as the one from the region cannot be trusted
                    IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
                    if (GridService != null)
                    {
                        //Set the user in transit so that we block duplicate tps and reset any cancelations
                        if (!SetUserInTransit(AgentID))
                        {
                            reason = "Already in a teleport";
                            return false;
                        }

                        bool result = false;

                        //We need to get it from the grid service again so that we can get the simulation service urls correctly
                        // as regions don't get that info
                        crossingRegion = GridService.GetRegionByUUID(clientCaps.AccountInfo.AllScopeIDs, crossingRegion.RegionID);
                        cAgent.IsCrossing = true;
                        if (!SimulationService.UpdateAgent(crossingRegion, cAgent))
                        {
                            MainConsole.Instance.Warn("[AgentProcessing]: Failed to cross agent " + AgentID +
                                       " because region did not accept it. Resetting.");
                            reason = "Failed to update an agent";
                        }
                        else
                        {
                            IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>();

                            //Add this for the viewer, but not for the sim, seems to make the viewer happier
                            int XOffset = crossingRegion.RegionLocX - requestingRegionCaps.RegionX;
                            pos.X += XOffset;

                            int YOffset = crossingRegion.RegionLocY - requestingRegionCaps.RegionY;
                            pos.Y += YOffset;

                            IRegionClientCapsService otherRegion = clientCaps.GetCapsService(crossingRegion.RegionHandle);
                            //Tell the client about the transfer
                            EQService.CrossRegion(crossingRegion.RegionHandle, pos, velocity,
                                                  otherRegion.LoopbackRegionIP,
                                                  otherRegion.CircuitData.RegionUDPPort,
                                                  otherRegion.CapsUrl,
                                                  AgentID,
                                                  circuit.SessionID,
                                                  crossingRegion.RegionSizeX,
                                                  crossingRegion.RegionSizeY,
                                                  requestingRegion);

                            result = WaitForCallback(AgentID);
                            if (!result)
                            {
                                MainConsole.Instance.Warn("[AgentProcessing]: Callback never came in crossing agent " + circuit.AgentID +
                                           ". Resetting.");
                                reason = "Crossing timed out";
                            }
                            else
                            {
                                // Next, let's close the child agent connections that are too far away.
                                //Fix the root agent status
                                otherRegion.RootAgent = true;
                                requestingRegionCaps.RootAgent = false;

                                CloseNeighborAgents(requestingRegionCaps.Region, crossingRegion, AgentID);
                                reason = "";
                            }
                        }

                        //All done
                        ResetFromTransit(AgentID);
                        return result;
                    }
                    else
                        reason = "Could not find the GridService";
                }
                else
                    reason = "Could not find the SimulationService";
            }
            catch (Exception ex)
            {
                MainConsole.Instance.WarnFormat("[AgentProcessing]: Failed to cross an agent into a new region. {0}", ex);
            }
            ResetFromTransit(AgentID);
            reason = "Exception occured";
            return false;
        }
示例#16
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;
         }
         m_GridService.SetRegionUnsafe(r.RegionID);
     }
     destination = null;
     return false;
 }
 public override void FromOSD(OSDMap map)
 {
     Success = map["Success"];
     CircuitData = new AgentCircuitData();
     CircuitData.FromOSD((OSDMap)map["CircuitData"]);
     SeedCap = map["SeedCap"];
     Reason = map["Reason"];
 }
        public bool RetrieveAgent(GridRegion destination, UUID id, bool agentIsLeaving, out AgentData agent,
                                  out AgentCircuitData circuitData)
        {
            agent = null;
            circuitData = null;

            if (destination == null)
                return false;

            foreach (IScene s in m_sceneList)
            {
                if (s.RegionInfo.RegionID == destination.RegionID)
                {
                    //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
                    IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>();
                    if (transferModule != null)
                        return transferModule.IncomingRetrieveRootAgent(s, id, agentIsLeaving, out agent,
                                                                        out circuitData);
                }
            }
            return false;
            //MainConsole.Instance.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
        }
        /**
         * Agent-related communications
         */

        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags,
                                AgentData data, out int requestedUDPPort, out string reason)
        {
            requestedUDPPort = 0;
            if (destination == null)
            {
                reason = "Given destination was null";
                MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination");
                return false;
            }
            if (destination.ExternalEndPoint != null) requestedUDPPort = destination.ExternalEndPoint.Port;

#if (!ISWIN)
            foreach (IScene s in m_sceneList)
            {
                if (s.RegionInfo.RegionID == destination.RegionID)
                {
                    //MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName);
                    if (data != null)
                        UpdateAgent(destination, data);
                    IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>();
                    if (transferModule != null)
                        return transferModule.NewUserConnection(s, aCircuit, teleportFlags, out requestedUDPPort, out reason);
                }
            }
#else
            foreach (IScene s in m_sceneList.Where(s => s.RegionInfo.RegionID == destination.RegionID))
            {
                //MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName);
                if (data != null)
                    UpdateAgent(destination, data);
                IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>();
                if (transferModule != null)
                    return transferModule.NewUserConnection(s, aCircuit, teleportFlags, out requestedUDPPort,
                                                            out reason);
            }
#endif

            MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Did not find region {0} for CreateAgent",
                              destination.RegionName);
            OSDMap map = new OSDMap();
            map["Reason"] = "Did not find region " + destination.RegionName;
            map["Success"] = false;
            reason = OSDParser.SerializeJsonString(map);
            return false;
        }
        protected OSDMap PackCreateAgentArguments(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, IPEndPoint ipaddress)
        {
            OSDMap args = null;
            try
            {
                args = aCircuit.PackAgentCircuitData ();
            }
            catch (Exception e)
            {
                MainConsole.Instance.Debug ("[USER AGENT CONNECTOR]: PackAgentCircuitData failed with exception: " + e.Message);
            }
            // Add the input arguments
            args["gatekeeper_serveruri"] = OSD.FromString (gatekeeper.ServerURI);
            args["gatekeeper_host"] = OSD.FromString (gatekeeper.ExternalHostName);
            args["gatekeeper_port"] = OSD.FromString (gatekeeper.HttpPort.ToString ());
            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["destination_serveruri"] = OSD.FromString (destination.ServerURI);

            // 10/3/2010
            // I added the client_ip up to the regular AgentCircuitData, so this doesn't need to be here.
            // This need cleaning elsewhere...
            //if (ipaddress != null)
            //    args["client_ip"] = OSD.FromString(ipaddress.Address.ToString());

            return args;
        }
示例#21
0
        protected virtual OSDMap OnMessageReceived(OSDMap message)
        {
            if (!message.ContainsKey("Method"))
                return null;

            UUID AgentID = message["AgentID"].AsUUID();
            ulong requestingRegion = message["RequestingRegion"].AsULong();
            ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
            if (capsService == null)
                return new OSDMap();

            IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);

            IRegionClientCapsService regionCaps = null;
            if (clientCaps != null)
                regionCaps = clientCaps.GetCapsService(requestingRegion);
            if (message["Method"] == "LogoutRegionAgents")
            {
                LogOutAllAgentsForRegion(requestingRegion);
            }
            else if (message["Method"] == "RegionIsOnline")
                //This gets fired when the scene is fully finished starting up
            {
                //Log out all the agents first, then add any child agents that should be in this region
                LogOutAllAgentsForRegion(requestingRegion);
                IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
                if (GridService != null)
                {
                    int x, y;
                    Util.UlongToInts(requestingRegion, out x, out y);
                    GridRegion requestingGridRegion = GridService.GetRegionByPosition(null, x, y);
                    if (requestingGridRegion != null)
                        Util.FireAndForget((o) => EnableChildAgentsForRegion(requestingGridRegion));
                }
            }
            else if (message["Method"] == "DisableSimulator")
            {
                //KILL IT!
                if (regionCaps == null || clientCaps == null)
                    return null;
                IEventQueueService eventQueue = m_registry.RequestModuleInterface<IEventQueueService>();
                eventQueue.DisableSimulator(regionCaps.AgentID, regionCaps.RegionHandle);
                //regionCaps.Close();
                //clientCaps.RemoveCAPS(requestingRegion);
                regionCaps.Disabled = true;
            }
            else if (message["Method"] == "ArrivedAtDestination")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                //Recieved a callback
                if (clientCaps.InTeleport) //Only set this if we are in a teleport, 
                    //  otherwise (such as on login), this won't check after the first tp!
                    clientCaps.CallbackHasCome = true;

                regionCaps.Disabled = false;

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

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

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

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

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

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

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

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

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

                    AgentData AgentData = new AgentData();
                    AgentData.Unpack((OSDMap) body["AgentData"]);
                    regionCaps.Disabled = false;
                    string ResponseURL = message["ResponseURL"].AsString();
                    if (ResponseURL == "")
                    {
                        OSDMap result = new OSDMap();
                        string reason = "";
                        result["success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance,
                                                          Circuit, AgentData, AgentID, requestingRegion, out reason);
                        result["Reason"] = reason;
                        //Remove the region flags, not the regions problem
                        destination.Flags = 0;
                        result["Destination"] = destination.ToOSD(); //Send back the new destination
                        return result;
                    }
                    else
                    {
                        Util.FireAndForget(delegate
                        {
                            OSDMap result = new OSDMap();
                            string reason = "";
                            result["success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance,
                                                              Circuit, AgentData, AgentID, requestingRegion, out reason);
                            result["Reason"] = reason;
                            //Remove the region flags, not the regions problem
                            destination.Flags = 0;
                            result["Destination"] = destination.ToOSD(); //Send back the new destination
                            WebUtils.PostToService(ResponseURL, result);
                        });
                        return new OSDMap() { new KeyValuePair<string, OSD>("WillHaveResponse", true) };
                    }
                }
            }
            else if (message["Method"] == "CrossAgent")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps == null || rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    //This is a simulator message that tells us to cross the agent
                    OSDMap body = ((OSDMap) message["Message"]);

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

                    string ResponseURL = message["ResponseURL"].AsString();
                    if (ResponseURL == "")
                    {
                        OSDMap result = new OSDMap();
                        string reason = "";
                        result["success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData,
                                                       AgentID, requestingRegion, out reason);
                        result["reason"] = reason;
                        return result;
                    }
                    else
                    {
                        Util.FireAndForget(delegate
                        {
                            OSDMap result = new OSDMap();
                            string reason = "";
                            result["success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData,
                                                           AgentID, requestingRegion, out reason);
                            result["reason"] = reason;
                            if (ResponseURL != null)
                                WebUtils.PostToService(ResponseURL, result);
                        });
                        return new OSDMap() { new KeyValuePair<string, OSD>("WillHaveResponse", true) };
                    }
                }
                else if (clientCaps.InTeleport)
                {
                    OSDMap result = new OSDMap();
                    result["success"] = false;
                    result["Note"] = false;
                    return result;
                }
                else
                {
                    OSDMap result = new OSDMap();
                    result["success"] = false;
                    result["Note"] = false;
                    return result;
                }
            }
            return null;
        }
示例#22
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 "";
 }
示例#23
0
        private bool CreateAgent(GridRegion region, IRegionClientCapsService regionCaps, ref AgentCircuitData aCircuit,
            ISimulationService SimulationService, ref int requestedUDPPort, out string reason)
        {
            CachedUserInfo info = new CachedUserInfo();
            IAgentConnector con = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>();
            if (con != null)
                info.AgentInfo = con.GetAgent(aCircuit.AgentID);
            info.UserAccount = regionCaps.ClientCaps.AccountInfo;

            IGroupsServiceConnector groupsConn = Aurora.DataManager.DataManager.RequestPlugin<IGroupsServiceConnector>();
            if (groupsConn != null)
            {
                info.ActiveGroup = groupsConn.GetGroupMembershipData(aCircuit.AgentID, UUID.Zero, aCircuit.AgentID);
                info.GroupMemberships = groupsConn.GetAgentGroupMemberships(aCircuit.AgentID, aCircuit.AgentID);
            }
            aCircuit.OtherInformation["CachedUserInfo"] = info.ToOSD();
            return SimulationService.CreateAgent(region, aCircuit, aCircuit.teleportFlags, null,
                                                    out requestedUDPPort, out reason);
        }
        /// <summary>
        /// Verify if the user can connect to this region.  Checks the banlist and ensures that the region is set for public access
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="agent">The circuit data for the agent</param>
        /// <param name="reason">outputs the reason to this string</param>
        /// <returns>True if the region accepts this agent.  False if it does not.  False will 
        /// also return a reason.</returns>
        protected bool AuthorizeUser (IScene scene, AgentCircuitData agent, out string reason)
        {
            reason = String.Empty;

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

            return true;
        }
示例#25
0
        /// <summary>
        ///   Async component for informing client of which neighbors exist
        /// </summary>
        /// <remarks>
        ///   This needs to run asynchronously, as a network timeout may block the thread for a long while
        /// </remarks>
        /// <param name = "remoteClient"></param>
        /// <param name = "a"></param>
        /// <param name = "regionHandle"></param>
        /// <param name = "endPoint"></param>
        public virtual bool InformClientOfNeighbor(UUID AgentID, ulong requestingRegion, AgentCircuitData circuitData,
                                                   ref GridRegion neighbor,
                                                   uint TeleportFlags, AgentData agentData, out string reason,
                                                   out bool useCallbacks)
        {
            useCallbacks = true;
            if (neighbor == null || neighbor.RegionHandle == 0)
            {
                reason = "Could not find neighbor to inform";
                return false;
            }
            /*if ((neighbor.Flags & (int)Aurora.Framework.RegionFlags.RegionOnline) == 0 &&
                (neighbor.Flags & (int)(Aurora.Framework.RegionFlags.Foreign | Aurora.Framework.RegionFlags.Hyperlink)) == 0)
            {
                reason = "The region you are attempting to teleport to is offline";
                return false;
            }*/
            MainConsole.Instance.Info("[AgentProcessing]: Starting to inform client about neighbor " + neighbor.RegionName);

            //Notes on this method
            // 1) the SimulationService.CreateAgent MUST have a fixed CapsUrl for the region, so we have to create (if needed)
            //       a new Caps handler for it.
            // 2) Then we can call the methods (EnableSimulator and EstatablishAgentComm) to tell the client the new Urls
            // 3) This allows us to make the Caps on the grid server without telling any other regions about what the
            //       Urls are.

            ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
            if (SimulationService != null)
            {
                ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
                IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);

                IRegionClientCapsService oldRegionService = clientCaps.GetCapsService(neighbor.RegionHandle);

                //If its disabled, it should be removed, so kill it!
                if (oldRegionService != null && oldRegionService.Disabled)
                {
                    clientCaps.RemoveCAPS(neighbor.RegionHandle);
                    oldRegionService = null;
                }

                bool newAgent = oldRegionService == null;
                IRegionClientCapsService otherRegionService = clientCaps.GetOrCreateCapsService(neighbor.RegionHandle,
                                                                                                CapsUtil.GetCapsSeedPath
                                                                                                    (CapsUtil.
                                                                                                         GetRandomCapsObjectPath
                                                                                                         ()),
                                                                                                circuitData, 0);

                if (!newAgent)
                {
                    //Note: if the agent is already there, send an agent update then
                    bool result = true;
                    if (agentData != null)
                    {
                        agentData.IsCrossing = false;
                        result = SimulationService.UpdateAgent(neighbor, agentData);
                    }
                    if (result)
                        oldRegionService.Disabled = false;
                    reason = "";
                    return result;
                }

                ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService>();
                if (commsService != null)
                    commsService.GetUrlsForUser(neighbor, circuitData.AgentID);
                        //Make sure that we make userURLs if we need to

                circuitData.CapsPath = CapsUtil.GetCapsPathFromCapsSeed(otherRegionService.CapsUrl); //For OpenSim
                circuitData.firstname = clientCaps.AccountInfo.FirstName;
                circuitData.lastname = clientCaps.AccountInfo.LastName;

                int requestedPort = 0;
                if (circuitData.child)
                    circuitData.reallyischild = true;
                bool regionAccepted = CreateAgent(neighbor, otherRegionService, ref circuitData, SimulationService, ref requestedPort, out reason);
                if (regionAccepted)
                {
                    IPAddress ipAddress = neighbor.ExternalEndPoint.Address;
                    string otherRegionsCapsURL;
                    //If the region accepted us, we should get a CAPS url back as the reason, if not, its not updated or not an Aurora region, so don't touch it.
                    if (reason != "" && reason != "authorized")
                    {
                        OSDMap responseMap = (OSDMap) OSDParser.DeserializeJson(reason);
                        OSDMap SimSeedCaps = (OSDMap) responseMap["CapsUrls"];
                        if (responseMap.ContainsKey("OurIPForClient"))
                        {
                            string ip = responseMap["OurIPForClient"].AsString();
                            if (!IPAddress.TryParse(ip, out ipAddress))
#pragma warning disable 618
                                ipAddress = Dns.GetHostByName(ip).AddressList[0];
#pragma warning restore 618
                        }
                        otherRegionService.AddCAPS(SimSeedCaps);
                        otherRegionsCapsURL = otherRegionService.CapsUrl;
                    }
                    else
                    {
                        //We are assuming an OpenSim region now!

                        #region OpenSim teleport compatibility!

                        useCallbacks = false; //OpenSim can't send us back a message, don't try it!
                        otherRegionsCapsURL = otherRegionService.Region.ServerURI +
                                              CapsUtil.GetCapsSeedPath(circuitData.CapsPath);
                        otherRegionService.CapsUrl = otherRegionsCapsURL;

                        #endregion
                    }
                    if (ipAddress == null)
                        ipAddress = neighbor.ExternalEndPoint.Address;
                    if (requestedPort == 0)
                        requestedPort = neighbor.ExternalEndPoint.Port;
                    otherRegionService = clientCaps.GetCapsService(neighbor.RegionHandle);
                    otherRegionService.LoopbackRegionIP = ipAddress;
                    otherRegionService.CircuitData.RegionUDPPort = requestedPort;
                    circuitData.RegionUDPPort = requestedPort; //Fix the port

                    IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>();

                    EQService.EnableSimulator(neighbor.RegionHandle,
                                              ipAddress.GetAddressBytes(),
                                              requestedPort, AgentID,
                                              neighbor.RegionSizeX, neighbor.RegionSizeY, requestingRegion);

                    // EnableSimulator makes the client send a UseCircuitCode message to the destination, 
                    // which triggers a bunch of things there.
                    // So let's wait
                    Thread.Sleep(300);
                    EQService.EstablishAgentCommunication(AgentID, neighbor.RegionHandle,
                                                          ipAddress.GetAddressBytes(),
                                                          requestedPort, otherRegionsCapsURL, neighbor.RegionSizeX,
                                                          neighbor.RegionSizeY,
                                                          requestingRegion);

                    if (!useCallbacks)
                        Thread.Sleep(3000); //Give it a bit of time, only for OpenSim...

                    MainConsole.Instance.Info("[AgentProcessing]: Completed inform client about neighbor " + neighbor.RegionName);
                }
                else
                {
                    clientCaps.RemoveCAPS(neighbor.RegionHandle);
                    MainConsole.Instance.Error("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName +
                                ", reason: " + reason);
                    return false;
                }
                return true;
            }
            reason = "SimulationService does not exist";
            MainConsole.Instance.Error("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName +
                        ", reason: " + reason + "!");
            return false;
        }
        public virtual bool IncomingRetrieveRootAgent(IScene scene, UUID id, bool agentIsLeaving, out AgentData agent, out AgentCircuitData circuitData)
        {
            agent = null;
            circuitData = null;
            IScenePresence sp = scene.GetScenePresence (id);
            if ((sp != null) && (!sp.IsChildAgent))
            {
                AgentData data = new AgentData ();
                sp.CopyTo (data);
                agent = data;
                circuitData = BuildCircuitDataForPresence(sp, sp.AbsolutePosition);
                //if (agentIsLeaving)
                //    sp.SetAgentLeaving(null);//We arn't sure where they are going
                return true;
            }

            return false;
        }
        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 ();
            MainConsole.Instance.InfoFormat ("[GATEKEEPER SERVICE]: Login request for {0} {1} @ {2}",
                authURL, aCircuit.AgentID, destination.RegionName);

            //
            // Authenticate the user
            //
            if (!Authenticate (aCircuit))
            {
                reason = "Unable to verify identity";
                MainConsole.Instance.InfoFormat ("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0}. Refusing service.", aCircuit.AgentID);
                return false;
            }
            MainConsole.Instance.DebugFormat ("[GATEKEEPER SERVICE]: Identity verified for {0} @ {1}", aCircuit.AgentID, 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 (null, aCircuit.AgentID);
                if (account != null && m_userFinder.IsLocalGridUser(account.PrincipalID))
                {
                    // 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.AgentIsComingHome (aCircuit.SessionID, m_ExternalName))
                        {
                            // Can't do, sorry
                            reason = "Unauthorized";
                            MainConsole.Instance.InfoFormat ("[GATEKEEPER SERVICE]: Foreign agent {0} has same ID as local user. Refusing service.",
                                aCircuit.AgentID);
                            return false;

                        }
                    }
                }
            }
            MainConsole.Instance.InfoFormat ("[GATEKEEPER SERVICE]: User is ok");

            // May want to authorize

            //bool isFirstLogin = false;
            //
            // Login the presence, if it's not there yet (by the login service)
            //
            UserInfo presence = m_PresenceService.GetUserInfo (aCircuit.AgentID.ToString());
            if (m_userFinder.IsLocalGridUser(aCircuit.AgentID) && presence != null && presence.IsOnline) // it has been placed there by the login service
            {
                //    isFirstLogin = true;
            }
            else
            {
                IUserAgentService userAgentService = new UserAgentServiceConnector(aCircuit.ServiceURLs["HomeURI"].ToString());
                Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
                GridRegion finalDestination = userAgentService.GetHomeRegion(aCircuit.AgentID, out position, out lookAt);
                if (finalDestination == null)
                {
                    reason = "You do not have a home position set.";
                    return false;
                }
                m_PresenceService.SetHomePosition(aCircuit.AgentID.ToString(), finalDestination.RegionID, position, lookAt);
                m_PresenceService.SetLoggedIn(aCircuit.AgentID.ToString(), true, true, destination.RegionID);
            }

            MainConsole.Instance.DebugFormat ("[GATEKEEPER SERVICE]: Login presence ok");

            //
            // Get the region
            //
            destination = m_GridService.GetRegionByUUID(null, destination.RegionID);
            if (destination == null)
            {
                reason = "Destination region not found";
                return false;
            }

            //
            // Adjust the visible name
            //
            if (account != null)
            {
                aCircuit.firstname = account.FirstName;
                aCircuit.lastname = account.LastName;
            }
            if (account == null && !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
                {
                    MainConsole.Instance.WarnFormat ("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
                    aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString ();
                }
                m_userFinder.AddUser(aCircuit.AgentID, aCircuit.firstname, aCircuit.lastname, aCircuit.ServiceURLs);
                m_UserAccountService.CacheAccount(new UserAccount(UUID.Zero, aCircuit.AgentID, aCircuit.firstname + aCircuit.lastname, "") { UserFlags = 1024 });
            }

            retry:
            //
            // Finally launch the agent at the destination
            //
            TeleportFlags loginFlag = /*isFirstLogin ? */TeleportFlags.ViaLogin/* : TeleportFlags.ViaHGLogin*/;
            IRegionClientCapsService regionClientCaps = null;
            if (m_CapsService != null)
            {
                //Remove any previous users
                string ServerCapsBase = Aurora.Framework.Capabilities.CapsUtil.GetRandomCapsObjectPath ();
                m_CapsService.CreateCAPS(aCircuit.AgentID,
                    Aurora.Framework.Capabilities.CapsUtil.GetCapsSeedPath(ServerCapsBase),
                    destination.RegionHandle, true, aCircuit, 0);

                regionClientCaps = m_CapsService.GetClientCapsService (aCircuit.AgentID).GetCapsService (destination.RegionHandle);
                if (aCircuit.ServiceURLs == null)
                    aCircuit.ServiceURLs = new Dictionary<string, object>();
                aCircuit.ServiceURLs["IncomingCAPSHandler"] = regionClientCaps.CapsUrl;
            }
            aCircuit.child = false;//FIX THIS, OPENSIM ALWAYS SENDS CHILD!
            int requestedUDPPort = 0;
            bool success = m_SimulationService.CreateAgent (destination, aCircuit, (uint)loginFlag, null, out requestedUDPPort, out reason);
            if (success)
            {
                if (regionClientCaps != null)
                {
                    if (requestedUDPPort == 0)
                        requestedUDPPort = destination.ExternalEndPoint.Port;
                    IPAddress ipAddress = destination.ExternalEndPoint.Address;
                    aCircuit.RegionUDPPort = requestedUDPPort;
                    regionClientCaps.LoopbackRegionIP = ipAddress;
                    regionClientCaps.CircuitData.RegionUDPPort = requestedUDPPort;
                    OSDMap responseMap = (OSDMap)OSDParser.DeserializeJson (reason);
                    OSDMap SimSeedCaps = (OSDMap)responseMap["CapsUrls"];
                    regionClientCaps.AddCAPS (SimSeedCaps);
                }
            }
            else
            {
                if (m_CapsService != null)
                    m_CapsService.RemoveCAPS (aCircuit.AgentID);
                m_GridService.SetRegionUnsafe(destination.RegionID);
                if(!m_foundDefaultRegion)
                    m_DefaultGatewayRegion = FindDefaultRegion();
                if (destination != m_DefaultGatewayRegion)
                {
                    destination = m_DefaultGatewayRegion;
                    goto retry;
                }
                else
                {
                    m_DefaultGatewayRegion = FindDefaultRegion ();
                    if (m_DefaultGatewayRegion == destination)
                        return false;//It failed to find a new one
                    destination = m_DefaultGatewayRegion;
                    goto retry;//It found a new default region
                }
            }
            return success;
        }
        /// <summary>
        /// Do the work necessary to initiate a new user connection for a particular scene.
        /// At the moment, this consists of setting up the caps infrastructure
        /// The return bool should allow for connections to be refused, but as not all calling paths
        /// take proper notice of it let, we allowed banned users in still.
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="agent">CircuitData of the agent who is connecting</param>
        /// <param name="UDPPort"></param>
        /// <param name="reason">Outputs the reason for the false response on this string,
        /// If the agent was accepted, this will be the Caps SEED for the region</param>
        /// <param name="teleportFlags"></param>
        /// <returns>True if the region accepts this agent.  False if it does not.  False will 
        /// also return a reason.</returns>
        public bool NewUserConnection (IScene scene, AgentCircuitData agent, uint teleportFlags, out int UDPPort, out string reason)
        {
            reason = String.Empty;
            UDPPort = GetUDPPort(scene);
            IScenePresence sp = scene.GetScenePresence(agent.AgentID);

            // Don't disable this log message - it's too helpful
            MainConsole.Instance.TraceFormat (
                "[ConnectionBegin]: Region {0} told of incoming {1} agent {2} (circuit code {3}, teleportflags {4})",
                scene.RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.AgentID,
                agent.circuitcode, teleportFlags);

            if (!AuthorizeUser (scene, agent, out reason))
            {
                OSDMap map = new OSDMap ();
                map["Reason"] = reason;
                map["success"] = false;
                reason = OSDParser.SerializeJsonString (map);
                return false;
            }

            CacheUserInfo(scene, agent.OtherInformation);

            if (sp != null && !sp.IsChildAgent)
            {
                // We have a zombie from a crashed session. 
                // Or the same user is trying to be root twice here, won't work.
                // Kill it.
                MainConsole.Instance.InfoFormat ("[Scene]: Zombie scene presence detected for {0} in {1}", agent.AgentID, scene.RegionInfo.RegionName);
                //Tell everyone about it
                scene.AuroraEventManager.FireGenericEventHandler ("AgentIsAZombie", sp.UUID);
                //Send the killing message (DisableSimulator)
                scene.RemoveAgent (sp, true);
                sp = null;
            }

            OSDMap responseMap = new OSDMap ();
            responseMap["CapsUrls"] = scene.EventManager.TriggerOnRegisterCaps (agent.AgentID);
            responseMap["OurIPForClient"] = MainServer.Instance.HostName;

            // In all cases, add or update the circuit data with the new agent circuit data and teleport flags
            agent.teleportFlags = teleportFlags;

            responseMap["Agent"] = agent.PackAgentCircuitData ();

            object[] obj = new object[2];
            obj[0] = responseMap;
            obj[1] = agent;
            scene.AuroraEventManager.FireGenericEventHandler ("NewUserConnection", obj);

            //Add the circuit at the end
            scene.AuthenticateHandler.AddNewCircuit (agent.circuitcode, agent);

            MainConsole.Instance.InfoFormat (
                "[ConnectionBegin]: Region {0} authenticated and authorized incoming {1} agent {2} (circuit code {3})",
                scene.RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.AgentID,
                agent.circuitcode);

            responseMap["success"] = true;
            reason = OSDParser.SerializeJsonString (responseMap);
            return true;
        }
示例#29
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 scene, UUID cloneAppearanceFrom,
                                 UUID creatorID, Vector3 startPos)
        {
            AgentCircuitData m_aCircuitData = new AgentCircuitData
                                                  {
                                                      child = false,
                                                      circuitcode = (uint) Util.RandomClass.Next(),
                                                      Appearance = GetAppearance(cloneAppearanceFrom, scene)
                                                  };

            //Add the circuit data so they can login

            //Sets up appearance
            if (m_aCircuitData.Appearance == null)
            {
                m_aCircuitData.Appearance = new AvatarAppearance {Wearables = AvatarWearable.DefaultWearables};
            }
            //Create the new bot data
            BotClientAPI m_character = new BotClientAPI(scene, m_aCircuitData) { FirstName = FirstName, 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();
            foreach (AvatarAttachment t in attachments)
            {
                InventoryItemBase item = scene.InventoryService.GetItem(new InventoryItemBase(t.ItemID));
                if (item != null)
                {
                    item.ID = UUID.Random();
                    item.Owner = m_character.AgentId;
                    item.Folder = UUID.Zero;
                    scene.InventoryService.AddItemAsync(item, null);
                    //Now fix the ItemID
                    m_aCircuitData.Appearance.SetAttachment(t.AttachPoint, item.ID, t.AssetID);
                }
            }

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

            IScenePresence SP = scene.GetScenePresence(m_character.AgentId);
            if (SP == null)
                return UUID.Zero; //Failed!
            Bot bot = new Bot();
            bot.Initialize(SP, creatorID);
            SP.MakeRootAgent(startPos, false, true);
            //Move them
            SP.Teleport(startPos);

            foreach(var presence in scene.GetScenePresences())
                presence.SceneViewer.QueuePresenceForUpdate(SP, PrimUpdateFlags.ForcedFullUpdate);
            IAttachmentsModule attModule = SP.Scene.RequestModuleInterface<IAttachmentsModule>();
            if (attModule != null)
                foreach (AvatarAttachment att in attachments)
                    attModule.RezSingleAttachmentFromInventory(SP.ControllingClient, att.ItemID, att.AssetID, 0, true);

            IAvatarAppearanceModule appearance = SP.RequestModuleInterface<IAvatarAppearanceModule>();
            appearance.InitialHasWearablesBeenSent = true;

            //Save them in the bots list
            m_bots.Add(m_character.AgentId, bot);
            AddTagToBot(m_character.AgentId, "AllBots", bot.AvatarCreatorID);

            MainConsole.Instance.Info("[RexBotManager]: Added bot " + m_character.Name + " to scene.");
            //Return their UUID
            return m_character.AgentId;
        }
        public override bool InformClientOfNeighbor(UUID AgentID, ulong requestingRegion, AgentCircuitData circuitData, ref GridRegion neighbor, uint TeleportFlags, AgentData agentData, out string reason, out bool useCallbacks)
        {
            useCallbacks = true;
            if (neighbor == null)
            {
                reason = "Could not find neighbor to inform";
                return false;
            }

            MainConsole.Instance.Info ("[AgentProcessing]: Starting to inform client about neighbor " + neighbor.RegionName);

            //Notes on this method
            // 1) the SimulationService.CreateAgent MUST have a fixed CapsUrl for the region, so we have to create (if needed)
            //       a new Caps handler for it.
            // 2) Then we can call the methods (EnableSimulator and EstatablishAgentComm) to tell the client the new Urls
            // 3) This allows us to make the Caps on the grid server without telling any other regions about what the
            //       Urls are.

            ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService> ();
            if (SimulationService != null)
            {
                ICapsService capsService = m_registry.RequestModuleInterface<ICapsService> ();
                IClientCapsService clientCaps = capsService.GetClientCapsService (AgentID);
                GridRegion originalDest = neighbor;
                if ((neighbor.Flags & (int)Aurora.Framework.RegionFlags.Hyperlink) == (int)Aurora.Framework.RegionFlags.Hyperlink)
                {
                    neighbor = GetFinalDestination (neighbor);
                    if (neighbor == null || neighbor.RegionHandle == 0)
                    {
                        reason = "Could not find neighbor to inform";
                        return false;
                    }
                    //Remove any offenders
                    clientCaps.RemoveCAPS (originalDest.RegionHandle);
                    clientCaps.RemoveCAPS (neighbor.RegionHandle);
                }

                IRegionClientCapsService oldRegionService = clientCaps.GetCapsService (neighbor.RegionHandle);

                //If its disabled, it should be removed, so kill it!
                if (oldRegionService != null && oldRegionService.Disabled)
                {
                    clientCaps.RemoveCAPS (neighbor.RegionHandle);
                    oldRegionService = null;
                }

                bool newAgent = oldRegionService == null;
                IRegionClientCapsService otherRegionService = clientCaps.GetOrCreateCapsService (neighbor.RegionHandle,
                    CapsUtil.GetCapsSeedPath (CapsUtil.GetRandomCapsObjectPath ()), circuitData, 0);

                if (!newAgent)
                {
                    //Note: if the agent is already there, send an agent update then
                    bool result = true;
                    if (agentData != null)
                    {
                        agentData.IsCrossing = false;
                        result = SimulationService.UpdateAgent (neighbor, agentData);
                    }
                    if (result)
                        oldRegionService.Disabled = false;
                    reason = "";
                    return result;
                }

                ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService> ();
                if (commsService != null)
                    commsService.GetUrlsForUser (neighbor, circuitData.AgentID);//Make sure that we make userURLs if we need to

                circuitData.CapsPath = CapsUtil.GetCapsPathFromCapsSeed (otherRegionService.CapsUrl);
                if (clientCaps.AccountInfo != null)
                {
                    circuitData.firstname = clientCaps.AccountInfo.FirstName;
                    circuitData.lastname = clientCaps.AccountInfo.LastName;
                }
                bool regionAccepted = false;
                int requestedUDPPort = 0;
                if ((originalDest.Flags & (int)Aurora.Framework.RegionFlags.Hyperlink) == (int)Aurora.Framework.RegionFlags.Hyperlink)
                {
                    if (circuitData.ServiceURLs == null || circuitData.ServiceURLs.Count == 0)
                    {
                        if (clientCaps.AccountInfo != null)
                        {
                            circuitData.ServiceURLs = new Dictionary<string, object> ();
                            circuitData.ServiceURLs[GetHandlers.Helpers_HomeURI] = GetHandlers.GATEKEEPER_URL;
                            circuitData.ServiceURLs[GetHandlers.Helpers_GatekeeperURI] = GetHandlers.GATEKEEPER_URL;
                            circuitData.ServiceURLs[GetHandlers.Helpers_InventoryServerURI] = GetHandlers.GATEKEEPER_URL;
                            circuitData.ServiceURLs[GetHandlers.Helpers_AssetServerURI] = GetHandlers.GATEKEEPER_URL;
                            circuitData.ServiceURLs[GetHandlers.Helpers_ProfileServerURI] = GetHandlers.GATEKEEPER_URL;
                            circuitData.ServiceURLs[GetHandlers.Helpers_FriendsServerURI] = GetHandlers.GATEKEEPER_URL;
                            circuitData.ServiceURLs[GetHandlers.Helpers_IMServerURI] = GetHandlers.IM_URL;
                            clientCaps.AccountInfo.ServiceURLs = circuitData.ServiceURLs;
                            //Store the new urls
                            m_registry.RequestModuleInterface<IUserAccountService> ().StoreUserAccount (clientCaps.AccountInfo);
                        }
                    }
                    string userAgentDriver = circuitData.ServiceURLs[GetHandlers.Helpers_HomeURI].ToString ();
                    IUserAgentService connector = new UserAgentServiceConnector (userAgentDriver);
                    regionAccepted = connector.LoginAgentToGrid (circuitData, originalDest, neighbor, out reason);
                }
                else
                {
                    if(circuitData.child)
                        circuitData.reallyischild = true;
                    regionAccepted = SimulationService.CreateAgent (neighbor, ref circuitData,
                            TeleportFlags, agentData, out requestedUDPPort, out reason);
                }
                if (regionAccepted)
                {
                    IPAddress ipAddress = neighbor.ExternalEndPoint.Address;
                    string otherRegionsCapsURL;
                    //If the region accepted us, we should get a CAPS url back as the reason, if not, its not updated or not an Aurora region, so don't touch it.
                    if (reason != "")
                    {
                        OSDMap responseMap = (OSDMap)OSDParser.DeserializeJson (reason);
                        OSDMap SimSeedCaps = (OSDMap)responseMap["CapsUrls"];
                        if(responseMap.ContainsKey("OurIPForClient"))
                        {
                            string ip = responseMap["OurIPForClient"].AsString();
                            ipAddress = IPAddress.Parse(ip);
                        }
                        otherRegionService.AddCAPS (SimSeedCaps);
                        otherRegionsCapsURL = otherRegionService.CapsUrl;
                    }
                    else
                    {
                        //We are assuming an OpenSim region now!
                        #region OpenSim teleport compatibility!

                        useCallbacks = false;
                        otherRegionsCapsURL = neighbor.ServerURI +
                            CapsUtil.GetCapsSeedPath (circuitData.CapsPath);
                        otherRegionService.CapsUrl = otherRegionsCapsURL;

                        #endregion
                    }
                    if (requestedUDPPort == 0)
                        requestedUDPPort = neighbor.ExternalEndPoint.Port;
                    if(ipAddress == null)
                        ipAddress = neighbor.ExternalEndPoint.Address;
                    circuitData.RegionUDPPort = requestedUDPPort;
                    otherRegionService = clientCaps.GetCapsService(neighbor.RegionHandle);
                    otherRegionService.LoopbackRegionIP = ipAddress;
                    otherRegionService.CircuitData.RegionUDPPort = requestedUDPPort;

                    IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService> ();

                    EQService.EnableSimulator (neighbor.RegionHandle,
                        ipAddress.GetAddressBytes(),
                        requestedUDPPort, AgentID,
                        neighbor.RegionSizeX, neighbor.RegionSizeY, requestingRegion);

                    // EnableSimulator makes the client send a UseCircuitCode message to the destination,
                    // which triggers a bunch of things there.
                    // So let's wait
                    Thread.Sleep (300);
                    EQService.EstablishAgentCommunication (AgentID, neighbor.RegionHandle,
                        ipAddress.GetAddressBytes(),
                        requestedUDPPort, otherRegionsCapsURL, neighbor.RegionSizeX,
                        neighbor.RegionSizeY,
                        requestingRegion);

                    if (!useCallbacks)
                        Thread.Sleep (3000); //Give it a bit of time, only for OpenSim...

                    MainConsole.Instance.Info ("[AgentProcessing]: Completed inform client about neighbor " + neighbor.RegionName);
                }
                else
                {
                    clientCaps.RemoveCAPS (neighbor.RegionHandle);
                    MainConsole.Instance.Error ("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName + ", reason: " + reason);
                    return false;
                }
                return true;
            }
            reason = "SimulationService does not exist";
            MainConsole.Instance.Error ("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName + ", reason: " + reason + "!");
            return false;
        }