private GridRegion FixGridRegion(GridRegion gridRegion)
        {
            if (gridRegion == null)
                return null;
            SceneManager manager = m_registry.RequestModuleInterface<SceneManager>();
            if (manager != null)
            {
#if (!ISWIN)
                foreach (IScene scene in manager.Scenes)
                {
                    if (scene.RegionInfo.RegionID == gridRegion.RegionID)
                    {
                        gridRegion.RegionSizeX = scene.RegionInfo.RegionSizeX;
                        gridRegion.RegionSizeY = scene.RegionInfo.RegionSizeY;
                        return gridRegion;
                    }
                }
#else
                foreach (IScene scene in manager.Scenes.Where(scene => scene.RegionInfo.RegionID == gridRegion.RegionID))
                {
                    gridRegion.RegionSizeX = scene.RegionInfo.RegionSizeX;
                    gridRegion.RegionSizeY = scene.RegionInfo.RegionSizeY;
                    return gridRegion;
                }
#endif
            }
            return gridRegion;
        }
        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 CloseAgent(GridRegion destination, UUID id)
        {
            // Try local first
            if (m_localBackend.CloseAgent(destination, id))
                return true;

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
            {
                string uri = MakeUri(destination, true) + id + "/" + destination.RegionID.ToString() + "/";

                try
                {
                    WebUtils.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false, false);
                }
                catch (Exception e)
                {
                    MainConsole.Instance.WarnFormat("[REMOTE SIMULATION CONNECTOR] CloseAgent failed with exception; {0}", e);
                }

                return true;
            }

            return false;
        }
        public virtual bool CreateAgent(GridRegion destination, ref AgentCircuitData aCircuit, uint teleportFlags, AgentData data, out string reason)
        {
            reason = String.Empty;
            // Try local first
            if (m_localBackend.CreateAgent(destination, ref aCircuit, teleportFlags, data, out reason))
                return true;

            reason = String.Empty;

            string uri = MakeUri(destination, true) + 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(teleportFlags.ToString());
                if(data != null)
                    args["agent_data"] = data.Pack();

                OSDMap result = WebUtils.PostToService (uri, args, true, false);
                OSDMap results = WebUtils.GetOSDMap(result["_RawResult"].AsString());
                //Pull out the result and set it as the reason
                if (results == null)
                    return false;
                reason = results["reason"] != null ? results["reason"].AsString() : "";
                if (result["Success"].AsBoolean())
                {
                    //Not right... don't return true except for opensim combatibility :/
                    if (reason == "")
                        return true;
                    try
                    {
                        OSDMap responseMap = (OSDMap)OSDParser.DeserializeJson(reason);
                        if (responseMap.ContainsKey("Reason"))
                            reason = responseMap["Reason"].AsString();
                        return responseMap["Success"].AsBoolean();
                    }
                    catch
                    {
                        //Not right... don't return true except for opensim combatibility :/
                        return true;
                    }
                }

                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;
        }
        public virtual string RegisterRegion(UUID scopeID, GridRegion regionInfo, UUID SecureSessionID, out UUID SessionID)
        {
            SessionID = UUID.Zero;
            Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
            Dictionary<string, object> sendData = new Dictionary<string,object>();
            foreach (KeyValuePair<string, object> kvp in rinfo)
                sendData[kvp.Key] = (string)kvp.Value;

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["SESSIONID"] = SecureSessionID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"] = "register";

            string reqString = WebUtils.BuildQueryString(sendData);
            // m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/grid",
                        reqString);
                if (reply != string.Empty)
                {
                    Dictionary<string, object> replyData = WebUtils.ParseXmlResponse(reply);

                    if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success"))
                    {
                        if (replyData.ContainsKey("Message"))
                        {
                            SessionID = UUID.Parse(replyData["Message"].ToString());
                        }
                        m_log.Info("[GridService]: Successfully registered region " + regionInfo.RegionName + " at " + regionInfo.RegionLocX + "," + regionInfo.RegionLocY + " to the grid server @ " + m_ServerURI);
                        return String.Empty;
                    }
                    else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure"))
                    {
                        //m_log.DebugFormat("[GRID CONNECTOR]: Registration failed: {0}", replyData["Message"].ToString());
                        return replyData["Message"].ToString();
                    }
                    else if (!replyData.ContainsKey("Result"))
                    {
                        m_log.DebugFormat("[GRID CONNECTOR]: reply data does not contain result field");
                    }
                    else
                    {
                        m_log.DebugFormat("[GRID CONNECTOR]: unexpected result {0}", replyData["Result"].ToString());
                        return "Unexpected result "+replyData["Result"].ToString();
                    }
                }
                else
                    m_log.DebugFormat("[GRID CONNECTOR]: RegisterRegion received null reply from " + m_ServerURI);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server " + m_ServerURI + " : {0}", e.Message);
            }

            return "Error communicating with grid service";
        }
 public RexLoginResponse(UserAccount account, AgentCircuitData aCircuit, GridUserInfo pinfo,
     GridRegion destination, List<InventoryFolderBase> invSkel, FriendInfo[] friendsList, ILibraryService libService,
     string where, string startlocation, Vector3 position, Vector3 lookAt, List<InventoryItemBase> gestures, string message,
     GridRegion home, IPEndPoint clientIP, string mapTileURL, string searchURL)
     : base(account, aCircuit, pinfo, destination, invSkel, friendsList, libService, where, startlocation,
     position, lookAt, gestures, message, home, clientIP, mapTileURL, searchURL)
 {
 }
 protected virtual void PackData(OSDMap args, AgentCircuitData aCircuit, GridRegion destination, uint flags)
 {
         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());
 }
        public virtual string RegisterRegion(GridRegion regionInfo, UUID SecureSessionID, out UUID SessionID,
                                             out List<GridRegion> neighbors)
        {
            neighbors = new List<GridRegion>();
            OSDMap map = new OSDMap();
            map["Region"] = regionInfo.ToOSD();
            map["SecureSessionID"] = SecureSessionID;
            map["Method"] = "Register";

            List<string> serverURIs =
                m_registry.RequestModuleInterface<IConfigurationService>().FindValueOf("RegistrationURI");
            foreach (string mServerUri in serverURIs)
            {
                OSDMap result = WebUtils.PostToService(mServerUri + "/grid", map, true, false);
                if (result["Success"].AsBoolean())
                {
                    try
                    {
                        OSD r = OSDParser.DeserializeJson(result["_RawResult"]);
                        if (r is OSDMap)
                        {
                            OSDMap innerresult = (OSDMap) r;
                            if (innerresult["Result"].AsString() == "")
                            {
                                object[] o = new object[2];
                                o[0] = regionInfo;
                                o[1] = innerresult;
                                SessionID = innerresult["SecureSessionID"].AsUUID();
                                m_registry.RequestModuleInterface<IConfigurationService>().AddNewUrls(regionInfo.RegionHandle.ToString(), (OSDMap) innerresult["URLs"]);

                                OSDArray array = (OSDArray) innerresult["Neighbors"];
                                foreach (OSD ar in array)
                                {
                                    GridRegion n = new GridRegion();
                                    n.FromOSD((OSDMap) ar);
                                    neighbors.Add(n);
                                }
                                m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("GridRegionRegistered", o);
                                return "";
                            }
                            else
                            {
                                SessionID = UUID.Zero;
                                return innerresult["Result"].AsString();
                            }
                        }
                    }
                    catch (Exception) //JsonException
                    {
                        MainConsole.Instance.Warn("[GridServiceConnector]: Exception on parsing OSDMap from server, legacy (OpenSim) server?");
                    }
                }
            }
            SessionID = SecureSessionID;
            return OldRegisterRegion(regionInfo);
        }
Exemple #9
1
        private void OnRegionUp(GridRegion otherRegion)
        {
            // This shouldn't happen
            if (otherRegion == null)
                return;

            m_log.DebugFormat("[REGION CACHE]: (on region {0}) Region {1} is up @ {2}-{3}",
                m_scene.RegionInfo.RegionName, otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);

            m_neighbours[otherRegion.RegionHandle] = otherRegion;
        }
 public void FinishedStartup()
 {
     if (m_registry == null)
         return; //Not enabled
     m_CapsService = m_registry.RequestModuleInterface<ICapsService> ();
     m_GridService = m_registry.RequestModuleInterface<IGridService> ();
     m_PresenceService = m_registry.RequestModuleInterface<IAgentInfoService> ();
     m_UserAccountService = m_registry.RequestModuleInterface<IUserAccountService> ();
     m_UserAgentService = m_registry.RequestModuleInterface<IUserAgentService> ();
     m_SimulationService = m_registry.RequestModuleInterface<ISimulationService> ();
     m_DefaultGatewayRegion = FindDefaultRegion ();
 }
Exemple #11
1
        public bool FriendshipApproved(GridRegion region, UUID userID, string userName, UUID friendID)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();
            //sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            //sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"] = "friendship_approved";

            sendData["FromID"] = userID.ToString();
            sendData["FromName"] = userName;
            sendData["ToID"] = friendID.ToString();

            return Call(region, sendData);
        }
Exemple #12
1
        public bool FriendshipOffered(GridRegion region, UUID userID, UUID friendID, string message)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();
            //sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            //sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"] = "friendship_offered";

            sendData["FromID"] = userID.ToString();
            sendData["ToID"] = friendID.ToString();
            sendData["Message"] = message;

            return Call(region, sendData);

        }
        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;
        }
        public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason)
        {
            HttpWebRequest AgentCreateRequest = null;
            reason = String.Empty;

            if (SendRequest(destination, aCircuit, flags, out reason, out AgentCreateRequest))
            {
                string response = GetResponse(AgentCreateRequest, out reason);
                bool success = true;
                UnpackResponse(response, out success, out reason);
                return success;
            }

            return false;
        }
 private GridRegion FixGridRegion(GridRegion gridRegion)
 {
     if (gridRegion == null)
         return null;
     ISceneManager manager = m_registry.RequestModuleInterface<ISceneManager>();
     if (manager != null)
     {
         foreach (IScene scene in manager.GetAllScenes().Where(scene => scene.RegionInfo.RegionID == gridRegion.RegionID))
         {
             gridRegion.RegionSizeX = scene.RegionInfo.RegionSizeX;
             gridRegion.RegionSizeY = scene.RegionInfo.RegionSizeY;
             return gridRegion;
         }
     }
     return gridRegion;
 }
 protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout)
 {
     logout = false;
     return m_aScene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason);
 }
        private void Fail(ScenePresence sp, GridRegion finalDestination)
        {
            // Client never contacted destination. Let's restore everything back
            sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");

            // Fail. Reset it back
            sp.IsChildAgent = false;
            ReInstantiateScripts(sp);
            ResetFromTransit(sp.UUID);

            EnableChildAgents(sp);

            // Finally, kill the agent we just created at the destination.
            m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);

        }
        public void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
        {
            if (reg == null || finalDestination == null)
            {
                sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
                return;
            }

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

            uint newRegionX = (uint)(reg.RegionHandle >> 40);
            uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
            uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
            uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);

            ulong destinationHandle = finalDestination.RegionHandle;

            // Let's do DNS resolution only once in this process, please!
            // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
            // it's actually doing a lot of work.
            IPEndPoint endPoint = finalDestination.ExternalEndPoint;
            if (endPoint.Address != null)
            {
                // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
                // both regions
                if (sp.ParentID != (uint)0)
                    sp.StandUp();

                if (!sp.ValidateAttachments())
                    m_log.DebugFormat(
                        "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}.  Continuing.",
                        sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName);

//                if (!sp.ValidateAttachments())
//                {
//                    sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
//                    return;
//                }

                string reason;
                string version;
                if (!m_aScene.SimulationService.QueryAccess(finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason))
                {
                    sp.ControllingClient.SendTeleportFailed("Teleport failed: " + reason);
                    return;
                }
                m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Destination is running version {0}", version);

                sp.ControllingClient.SendTeleportStart(teleportFlags);

                // the avatar.Close below will clear the child region list. We need this below for (possibly)
                // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
                //List<ulong> childRegions = avatar.KnownRegionHandles;
                // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
                // failure at this point (unlike a border crossing failure).  So perhaps this can never fail
                // once we reach here...
                //avatar.Scene.RemoveCapsHandler(avatar.UUID);

                string capsPath = String.Empty;

                AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
                AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
                agentCircuit.startpos = position;
                agentCircuit.child = true;
                agentCircuit.Appearance = sp.Appearance;
                if (currentAgentCircuit != null)
                {
                    agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
                    agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
                    agentCircuit.Viewer = currentAgentCircuit.Viewer;
                    agentCircuit.Channel = currentAgentCircuit.Channel;
                    agentCircuit.Mac = currentAgentCircuit.Mac;
                    agentCircuit.Id0 = currentAgentCircuit.Id0;
                }

                if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    // brand new agent, let's create a new caps seed
                    agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
                }

                // Let's create an agent there if one doesn't exist yet. 
                bool logout = false;
                if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
                {
                    sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
                                                                              reason));
                    return;
                }

                // OK, it got this agent. Let's close some child agents
                sp.CloseChildAgents(newRegionX, newRegionY);
                IClientIPEndpoint ipepClient;  
                if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
                    #region IP Translation for NAT
                    // Uses ipepClient above
                    if (sp.ClientView.TryGet(out ipepClient))
                    {
                        endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
                    }
                    #endregion
                    capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);

                    if (eq != null)
                    {
                        eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);

                        // ES makes the client send a UseCircuitCode message to the destination, 
                        // which triggers a bunch of things there.
                        // So let's wait
                        Thread.Sleep(200);

                        eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);

                    }
                    else
                    {
                        sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
                    }
                }
                else
                {
                    agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
                    capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
                }


                SetInTransit(sp.UUID);

                // Let's send a full update of the agent. This is a synchronous call.
                AgentData agent = new AgentData();
                sp.CopyTo(agent);
                agent.Position = position;
                SetCallbackURL(agent, sp.Scene.RegionInfo);

                //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent...");

                if (!UpdateAgent(reg, finalDestination, agent))
                {
                    // Region doesn't take it
                    m_log.WarnFormat(
                        "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}.  Returning avatar to source region.", 
                        sp.Name, finalDestination.RegionName);
                    
                    Fail(sp, finalDestination);
                    return;
                }

                sp.ControllingClient.SendTeleportProgress(teleportFlags | (uint)TeleportFlags.DisableCancel, "sending_dest");

                m_log.DebugFormat(
                    "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);

                if (eq != null)
                {
                    eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
                                           0, teleportFlags, capsPath, sp.UUID);
                }
                else
                {
                    sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
                                                                teleportFlags, capsPath);
                }

                // Let's set this to true tentatively. This does not trigger OnChildAgent
                sp.IsChildAgent = true;

                // 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 close things here.
                if (!WaitForCallback(sp.UUID))
                {
                    m_log.WarnFormat(
                        "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} failed due to no callback from destination region.  Returning avatar to source region.", 
                        sp.Name, finalDestination.RegionName);
                    
                    Fail(sp, finalDestination);                   
                    return;
                }

                // For backwards compatibility
                if (version == "Unknown" || version == string.Empty)
                {
                    // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
                    m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one...");
                    CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
                }

                // May need to logout or other cleanup
                AgentHasMovedAway(sp, logout);

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

                // Now let's make it officially a child agent
                sp.MakeChildAgent();
                

//                sp.Scene.CleanDroppedAttachments();

                // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone

                if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
                {
                    Thread.Sleep(5000);
                    sp.Close();
                    sp.Scene.IncomingCloseAgent(sp.UUID);
                }
                else
                {
                    // now we have a child agent in this region. 
                    sp.IsInTransit = false; // not sure :(
                    sp.Reset();
                }

                // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
                if (sp.Scene.NeedSceneCacheClear(sp.UUID))
                {
                    m_log.DebugFormat(
                        "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed",
                        sp.UUID);
                }
            }
            else
            {
                sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
            }
        }
 public virtual List <string> GetAgentsLocations(string requestor, List <string> userIDs)
 {
     string[] infos = new string[userIDs.Count];
     for (int i = 0; i < userIDs.Count; i++)
     {
         UserInfo user = GetUserInfo(userIDs[i]);
         if (user != null && user.IsOnline)
         {
             Interfaces.GridRegion gr =
                 m_registry.RequestModuleInterface <IGridService>().GetRegionByUUID(null,
                                                                                    user.CurrentRegionID);
             if (gr != null)
             {
                 infos[i] = gr.ServerURI;
             }
             else
             {
                 infos[i] = "NotOnline";
             }
         }
         else if (user == null)
         {
             infos[i] = "NonExistant";
         }
         else
         {
             infos[i] = "NotOnline";
         }
     }
     return(new List <string>(infos));
 }
Exemple #20
0
 /// <summary>
 /// Define equality as two regions having the same, non-zero UUID.
 /// </summary>
 public bool Equals(GridRegion region)
 {
     if ((object)region == null)
     {
         return(false);
     }
     // Return true if the non-zero UUIDs are equal:
     return((RegionID != UUID.Zero) && RegionID.Equals(region.RegionID));
 }
        public override void FromOSD(OSDMap map)
        {
            Error = map["Error"];
            OSDArray n = (OSDArray)map["Neighbors"];

            Neighbors   = n.ConvertAll <GridRegion>((osd) => { GridRegion r = new GridRegion(); r.FromOSD((OSDMap)osd); return(r); });
            SessionID   = map["SessionID"];
            RegionFlags = map["RegionFlags"];
            Urls        = (OSDMap)map["Urls"];
        }
Exemple #22
0
 public GridRegion(GridRegion ConvertFrom)
 {
     m_regionName       = ConvertFrom.RegionName;
     m_regionLocX       = ConvertFrom.RegionLocX;
     m_regionLocY       = ConvertFrom.RegionLocY;
     m_internalEndPoint = ConvertFrom.InternalEndPoint;
     m_externalHostName = ConvertFrom.ExternalHostName;
     m_httpPort         = ConvertFrom.HttpPort;
     RegionID           = ConvertFrom.RegionID;
     ServerURI          = ConvertFrom.ServerURI;
     TerrainImage       = ConvertFrom.TerrainImage;
     Access             = ConvertFrom.Access;
     Maturity           = ConvertFrom.Maturity;
     RegionSecret       = ConvertFrom.RegionSecret;
     EstateOwner        = ConvertFrom.EstateOwner;
 }
 private GridRegion FixGridRegion (GridRegion gridRegion)
 {
     SceneManager manager = m_registry.RequestModuleInterface<SceneManager> ();
     if (manager != null)
     {
         foreach (Scene scene in manager.Scenes)
         {
             if (scene.RegionInfo.RegionID == gridRegion.RegionID)
             {
                 gridRegion.RegionSizeX = scene.RegionInfo.RegionSizeX;
                 gridRegion.RegionSizeY = scene.RegionInfo.RegionSizeY;
                 return gridRegion;
             }
         }
     }
     return gridRegion;
 }
Exemple #24
0
        public bool RegisterRegion(UUID scopeID, GridRegion regionInfos)
        {
            // This needs better sanity testing. What if regionInfo is registering in
            // overlapping coords?
            RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
            if ((region != null) && (region.RegionID != regionInfos.RegionID))
            {
                m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.", 
                    regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
                return false;
            }
            if ((region != null) && (region.RegionID == regionInfos.RegionID) && 
                ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
            {
                // Region reregistering in other coordinates. Delete the old entry
                m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
                    regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);

                try
                {
                    m_Database.Delete(regionInfos.RegionID);
                }
                catch (Exception e)
                {
                    m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
                }
            }

            // Everything is ok, let's register
            RegionData rdata = RegionInfo2RegionData(regionInfos);
            rdata.ScopeID = scopeID;
            try
            {
                m_Database.Store(rdata);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
            }

            m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) registered successfully at {2}-{3}", 
                regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);

            return true;
        }
        protected virtual void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
        {
            if (source != null)
            {
                args["source_x"] = OSD.FromString(source.RegionLocX.ToString());
                args["source_y"] = OSD.FromString(source.RegionLocY.ToString());
                args["source_name"] = OSD.FromString(source.RegionName);
                args["source_uuid"] = OSD.FromString(source.RegionID.ToString());
                if (!String.IsNullOrEmpty(source.RawServerURI))
                    args["source_server_uri"] = OSD.FromString(source.RawServerURI);
            }

            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());
        }
        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.PostToService(uri, args, 20000);
                if (result["Success"].AsBoolean())
                    return true;
                
                m_log.WarnFormat(
                    "[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {1}", 
                    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;
        }
        public virtual string RegisterRegion(GridRegion regionInfo, UUID SecureSessionID, out UUID SessionID)
        {
            OSDMap map = new OSDMap();
            map["Region"] = regionInfo.ToOSD();
            map["SecureSessionID"] = SecureSessionID;
            map["Method"] = "Register";

            foreach (string m_ServerURI in m_ServerURIs)
            {
                OSDMap result = WebUtils.PostToService(m_ServerURI + "/grid", map);
                if (result["Success"].AsBoolean())
                {
                    try
                    {
                        OSD r = OSDParser.DeserializeJson(result["_RawResult"]);
                        if (r is OSDMap)
                        {
                            OSDMap innerresult = (OSDMap)r;
                            if (innerresult["Result"].AsString() == "")
                            {
                                SessionID = innerresult["SecureSessionID"].AsUUID();
                                return "";
                            }
                            else
                            {
                                SessionID = UUID.Zero;
                                return innerresult["Result"].AsString();
                            }
                        }
                    }
                    catch (Exception)//JsonException
                    {
                        m_log.Warn("[GridServiceConnector]: Exception on parsing OSDMap from server, legacy (OpenSim) server?");
                    }
                }
            } 
            SessionID = UUID.Zero;
            return OldRegisterRegion(regionInfo);
        }
Exemple #28
0
        public override void FromOSD(OSDMap map)
        {
            Error = map["Error"];
            OSDArray n = (OSDArray)map["Neighbors"];

            Neighbors   = n.ConvertAll <GridRegion>((osd) => { GridRegion r = new GridRegion(); r.FromOSD((OSDMap)osd); return(r); });
            SessionID   = map["SessionID"];
            RegionFlags = map["RegionFlags"];
            if (map.ContainsKey("Urls"))
            {
                Urls = (OSDMap)map["Urls"];
            }
            if (map.ContainsKey("RegionRemote"))
            {
                RegionRemote = (OSDMap)map["RegionRemote"];
            }
            if (map.ContainsKey("Region"))
            {
                Region = new GridRegion();
                Region.FromOSD((OSDMap)map["Region"]);
            }
        }
        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);
            }
        }
Exemple #30
0
        public bool LoginAgent(GridRegion source, 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}. From region {11}",
                             aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionID,
                             aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0, (TeleportFlags)aCircuit.teleportFlags,
                             (source == null) ? "Unknown" : string.Format("{0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI));

            string curViewer = Util.GetViewerName(aCircuit);

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

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

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

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

            //
            // Authenticate the user
            //
            string verifymessage = "";

            if (!Authenticate(aCircuit, out verifymessage))
            {
                reason = "Unable to verify identity";
                if (!string.IsNullOrEmpty(verifymessage))
                {
                    reason += ". " + verifymessage;
                    m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service. Reason: {2}", aCircuit.firstname, aCircuit.lastname, verifymessage);
                }
                else
                {
                    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);
                        }
                    }
                }
            }

            //
            // 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);
                }
            }

            //
            // Is the user banned?
            // This uses a Ban service that's more powerful than the configs
            //
            string uui = (account != null ? aCircuit.AgentID.ToString() : Util.ProduceUserUniversalIdentifier(aCircuit));

            if (m_BansService != null && m_BansService.IsBanned(uui, aCircuit.IPAddress, aCircuit.Id0, authURL))
            {
                reason = "You are banned from this world";
                m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: user {0} is banned", uui);
                return(false);
            }

            m_log.DebugFormat("[GATEKEEPER SERVICE]: User {0} is ok", aCircuit.Name);

            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 {0} is ok", aCircuit.Name);

                // 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 {0} is ok for {1}", destination.RegionName, aCircuit.Name);

            //
            // 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 {0}, Teleport Flags: {1}", aCircuit.Name, loginFlag);

            return(m_SimulationService.CreateAgent(source, destination, aCircuit, (uint)loginFlag, out reason));
        }
 protected virtual GridRegion GetFinalDestination(GridRegion region)
 {
     return region;
 }
Exemple #32
0
        public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
        {
            Dictionary <string, object> rinfo    = regionInfo.ToKeyValuePairs();
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            foreach (KeyValuePair <string, object> kvp in rinfo)
            {
                sendData[kvp.Key] = (string)kvp.Value;
            }

            sendData["SCOPEID"]    = scopeID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"]     = "register";

            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri       = m_ServerURI + "/grid";

            // m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth);
                if (reply != string.Empty)
                {
                    Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success"))
                    {
                        return(String.Empty);
                    }
                    else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure"))
                    {
                        m_log.ErrorFormat(
                            "[GRID CONNECTOR]: Registration failed: {0} when contacting {1}", replyData["Message"], uri);

                        return(replyData["Message"].ToString());
                    }
                    else if (!replyData.ContainsKey("Result"))
                    {
                        m_log.ErrorFormat(
                            "[GRID CONNECTOR]: reply data does not contain result field when contacting {0}", uri);
                    }
                    else
                    {
                        m_log.ErrorFormat(
                            "[GRID CONNECTOR]: unexpected result {0} when contacting {1}", replyData["Result"], uri);

                        return("Unexpected result " + replyData["Result"].ToString());
                    }
                }
                else
                {
                    m_log.ErrorFormat(
                        "[GRID CONNECTOR]: RegisterRegion received null reply when contacting grid server at {0}", uri);
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
            }

            return(string.Format("Error communicating with the grid service at {0}", uri));
        }
 /// <summary>
 /// This informs all neighboring regions about the settings of it's child agent.
 /// Calls an asynchronous method to do so..  so it doesn't lag the sim.
 ///
 /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
 ///
 /// </summary>
 private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, UUID scopeID, GridRegion dest)
 {
     //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
     try
     {
         m_scene.SimulationService.UpdateAgent(dest, cAgentData);
     }
     catch
     {
         // Ignore; we did our best
     }
 }
        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();
            string processedMessage;

            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
                //
                if (m_MessageUrl != String.Empty)
                {
                    WebClient client = new WebClient();
                    processedMessage = client.DownloadString(m_MessageUrl);
                }
                else
                {
                    processedMessage = m_WelcomeMessage;
                }
                processedMessage = processedMessage.Replace("\\n", "\n").Replace("<USERNAME>", firstName + " " + lastName);

                LLLoginResponse response
                    = new LLLoginResponse(
                          account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
                          where, startLocation, position, lookAt, gestures, processedMessage, home, clientIP,
                          m_MapTileURL, 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);
            }
        }
        protected virtual void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
        {
            if (source != null)
            {
                args["source_x"]    = OSD.FromString(source.RegionLocX.ToString());
                args["source_y"]    = OSD.FromString(source.RegionLocY.ToString());
                args["source_name"] = OSD.FromString(source.RegionName);
                args["source_uuid"] = OSD.FromString(source.RegionID.ToString());
                if (!String.IsNullOrEmpty(source.RawServerURI))
                {
                    args["source_server_uri"] = OSD.FromString(source.RawServerURI);
                }
            }

            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());
        }
 /// <summary>
 /// Send complete data about an agent in this region to a neighbor
 /// </summary>
 public bool UpdateAgent(GridRegion destination, AgentData data, EntityTransferContext ctx)
 {
     return(UpdateAgent(destination, (IAgentData)data, ctx, 200000)); // yes, 200 seconds
 }
        public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, EntityTransferContext ctx, out string myipaddress, out string reason)
        {
            reason      = String.Empty;
            myipaddress = 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();
                    myipaddress = data["your_ip"].AsString();
                    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();
                        myipaddress = data["your_ip"].AsString();
                        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);
        }
        /// <summary>
        /// Send updated position information about an agent in this region to a neighbor
        /// This operation may be called very frequently if an avatar is moving about in
        /// the region.
        /// </summary>
        public bool UpdateAgent(GridRegion destination, AgentPosition data)
        {
            bool v = true;

            if (_failedSims.TryGetValue(destination.ServerURI, out v))
            {
                return(false);
            }

            // The basic idea of this code is that the first thread that needs to
            // send an update for a specific avatar becomes the worker for any subsequent
            // requests until there are no more outstanding requests. Further, only send the most
            // recent update; this *should* never be needed but some requests get
            // slowed down and once that happens the problem with service end point
            // limits kicks in and nothing proceeds
            string uri = destination.ServerURI + AgentPath() + data.AgentID + "/";

            lock (m_updateAgentQueue)
            {
                if (m_updateAgentQueue.ContainsKey(uri))
                {
                    // Another thread is already handling
                    // updates for this simulator, just update
                    // the position and return, overwrites are
                    // not a problem since we only care about the
                    // last update anyway
                    m_updateAgentQueue[uri] = data;
                    return(true);
                }

                // Otherwise update the reference and start processing
                m_updateAgentQueue[uri] = data;
            }

            AgentPosition pos     = null;
            bool          success = true;

            while (success)
            {
                lock (m_updateAgentQueue)
                {
                    // save the position
                    AgentPosition lastpos = pos;

                    pos = m_updateAgentQueue[uri];

                    // this is true if no one put a new
                    // update in the map since the last
                    // one we processed, if thats the
                    // case then we are done
                    if (pos == lastpos)
                    {
                        m_updateAgentQueue.Remove(uri);
                        return(true);
                    }
                }

                EntityTransferContext ctx = new EntityTransferContext(); // Dummy, not needed for position
                success = UpdateAgent(destination, (IAgentData)pos, ctx, 10000);
            }
            // we get here iff success == false
            // blacklist sim for 2 minutes
            lock (m_updateAgentQueue)
            {
                _failedSims.AddOrUpdate(destination.ServerURI, true, 120);
                m_updateAgentQueue.Remove(uri);
            }
            return(false);
        }
 /// <summary>
 ///
 /// </summary>
 public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
 {
     // TODO, not that urgent
     return(false);
 }
        public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List <UUID> featuresAvailable, EntityTransferContext ctx, out string reason)
        {
            Culture.SetCurrentCulture();

            reason = "Failed to contact destination";

            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/";

            OSDMap request = new OSDMap();

            request.Add("viaTeleport", OSD.FromBoolean(viaTeleport));
            request.Add("position", OSD.FromString(position.ToString()));
            // To those who still understad this field, we're telling them
            // the lowest version just to be safe
            request.Add("my_version", OSD.FromString(String.Format("SIMULATION/{0}", VersionInfo.SimulationServiceVersionSupportedMin)));
            // New simulation service negotiation
            request.Add("simulation_service_supported_min", OSD.FromReal(VersionInfo.SimulationServiceVersionSupportedMin));
            request.Add("simulation_service_supported_max", OSD.FromReal(VersionInfo.SimulationServiceVersionSupportedMax));
            request.Add("simulation_service_accepted_min", OSD.FromReal(VersionInfo.SimulationServiceVersionAcceptedMin));
            request.Add("simulation_service_accepted_max", OSD.FromReal(VersionInfo.SimulationServiceVersionAcceptedMax));

            request.Add("context", ctx.Pack());

            OSDArray features = new OSDArray();

            foreach (UUID feature in featuresAvailable)
            {
                features.Add(OSD.FromString(feature.ToString()));
            }

            request.Add("features", features);

            if (agentHomeURI != null)
            {
                request.Add("agent_home_uri", OSD.FromString(agentHomeURI));
            }

            try
            {
                OSDMap result  = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false);
                bool   success = result["success"].AsBoolean();
                if (result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    // FIXME: If there is a _Result map then it's the success key here that indicates the true success
                    // or failure, not the sibling result node.
                    success = data["success"].AsBoolean();

                    reason = data["reason"].AsString();
                    // We will need to plumb this and start sing the outbound version as well
                    // TODO: lay the pipe for version plumbing
                    if (data.ContainsKey("negotiated_inbound_version") && data["negotiated_inbound_version"] != null)
                    {
                        ctx.InboundVersion  = (float)data["negotiated_inbound_version"].AsReal();
                        ctx.OutboundVersion = (float)data["negotiated_outbound_version"].AsReal();
                    }
                    else if (data["version"] != null && data["version"].AsString() != string.Empty)
                    {
                        string   versionString = data["version"].AsString();
                        String[] parts         = versionString.Split(new char[] { '/' });
                        if (parts.Length > 1)
                        {
                            ctx.InboundVersion  = float.Parse(parts[1], Culture.FormatProvider);
                            ctx.OutboundVersion = float.Parse(parts[1], Culture.FormatProvider);
                        }
                    }

                    m_log.DebugFormat(
                        "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3}/{4}",
                        uri, success, reason, ctx.InboundVersion, ctx.OutboundVersion);
                }

                if (!success || ctx.InboundVersion == 0f || ctx.OutboundVersion == 0f)
                {
                    // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
                    // actual failure message
                    if (!result.ContainsKey("_Result"))
                    {
                        if (result.ContainsKey("Message"))
                        {
                            string message = result["Message"].AsString();
                            if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
                            {
                                m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
                                return(true);
                            }

                            reason = result["Message"];
                        }
                        else
                        {
                            reason = "Communications failure";
                        }
                    }

                    return(false);
                }

                featuresAvailable.Clear();

                if (result.ContainsKey("features"))
                {
                    OSDArray array = (OSDArray)result["features"];

                    foreach (OSD o in array)
                    {
                        featuresAvailable.Add(new UUID(o.AsString()));
                    }
                }

                // Version stuff
                if (ctx.OutboundVersion < 0.5)
                {
                    ctx.WearablesCount = AvatarWearable.LEGACY_VERSION_MAX_WEARABLES;
                }
                else if (ctx.OutboundVersion < 0.6)
                {
                    ctx.WearablesCount = AvatarWearable.LEGACY_VERSION_MAX_WEARABLES + 1;
                }
                else
                {
                    ctx.WearablesCount = -1; // send all (just in case..)
                }
                return(success);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}", e.ToString());
            }

            return(false);
        }
        private GridRegion FindForeignRegion(string domainName, uint port, string regionName, UserAccount account, out GridRegion gatekeeper)
        {
            m_log.Debug("[LLLOGIN SERVICE]: attempting to findforeignregion " + domainName + ":" + port.ToString() + ":" + regionName);
            gatekeeper = new GridRegion();
            gatekeeper.ExternalHostName = domainName;
            gatekeeper.HttpPort         = port;
            gatekeeper.RegionName       = regionName;
            gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);

            UUID   regionID;
            ulong  handle;
            string imageURL = string.Empty, reason = string.Empty;
            string message;

            if (m_GatekeeperConnector.LinkRegion(gatekeeper, out regionID, out handle, out domainName, out imageURL, out reason))
            {
                string homeURI = null;
                if (account.ServiceURLs != null && account.ServiceURLs.ContainsKey("HomeURI"))
                {
                    homeURI = (string)account.ServiceURLs["HomeURI"];
                }

                GridRegion destination = m_GatekeeperConnector.GetHyperlinkRegion(gatekeeper, regionID, account.PrincipalID, homeURI, out message);
                return(destination);
            }

            return(null);
        }
Exemple #42
0
        public virtual LandData GetLandData(ulong regionHandle, uint x, uint y)
        {
            LandData  landData = null;
            Hashtable hash     = new Hashtable();

            hash["region_handle"] = regionHandle.ToString();
            hash["x"]             = x.ToString();
            hash["y"]             = y.ToString();

            IList paramList = new ArrayList();

            paramList.Add(hash);

            try
            {
                uint xpos = 0, ypos = 0;
                Utils.LongToUInts(regionHandle, out xpos, out ypos);
                GridRegion info = m_GridService.GetRegionByPosition(UUID.Zero, (int)xpos, (int)ypos);
                if (info != null) // just to be sure
                {
                    XmlRpcRequest  request  = new XmlRpcRequest("land_data", paramList);
                    string         uri      = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/";
                    XmlRpcResponse response = request.Send(uri, 10000);
                    if (response.IsFault)
                    {
                        m_log.ErrorFormat("[LAND CONNECTOR] remote call returned an error: {0}", response.FaultString);
                    }
                    else
                    {
                        hash = (Hashtable)response.Value;
                        try
                        {
                            landData              = new LandData();
                            landData.AABBMax      = Vector3.Parse((string)hash["AABBMax"]);
                            landData.AABBMin      = Vector3.Parse((string)hash["AABBMin"]);
                            landData.Area         = Convert.ToInt32(hash["Area"]);
                            landData.AuctionID    = Convert.ToUInt32(hash["AuctionID"]);
                            landData.Description  = (string)hash["Description"];
                            landData.Flags        = Convert.ToUInt32(hash["Flags"]);
                            landData.GlobalID     = new UUID((string)hash["GlobalID"]);
                            landData.Name         = (string)hash["Name"];
                            landData.OwnerID      = new UUID((string)hash["OwnerID"]);
                            landData.SalePrice    = Convert.ToInt32(hash["SalePrice"]);
                            landData.SnapshotID   = new UUID((string)hash["SnapshotID"]);
                            landData.UserLocation = Vector3.Parse((string)hash["UserLocation"]);
                            m_log.DebugFormat("[OGS1 GRID SERVICES] Got land data for parcel {0}", landData.Name);
                        }
                        catch (Exception e)
                        {
                            m_log.Error("[LAND CONNECTOR] Got exception while parsing land-data:", e);
                        }
                    }
                }
                else
                {
                    m_log.WarnFormat("[LAND CONNECTOR] Couldn't find region with handle {0}", regionHandle);
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[LAND CONNECTOR] Couldn't contact region {0}: {1}", regionHandle, e);
            }

            return(landData);
        }
        protected GridRegion FindDestination(
            UserAccount account, UUID scopeID, GridUserInfo pinfo, UUID sessionID, string startLocation,
            GridRegion home, out GridRegion gatekeeper,
            out string where, out Vector3 position, out Vector3 lookAt, out TeleportFlags flags)
        {
            flags = TeleportFlags.ViaLogin;

            m_log.DebugFormat(
                "[LLOGIN SERVICE]: Finding destination matching start location {0} for {1}",
                startLocation, account.Name);

            gatekeeper = null;
            where      = "home";
            position   = new Vector3(128, 128, 0);
            lookAt     = new Vector3(0, 1, 0);

            if (m_GridService == null)
            {
                return(null);
            }

            if (startLocation.Equals("home"))
            {
                // logging into home region
                if (pinfo == null)
                {
                    return(null);
                }

                GridRegion region = null;

                bool tryDefaults = false;

                if (home == null)
                {
                    tryDefaults = true;
                }
                else
                {
                    region = home;

                    position = pinfo.HomePosition;
                    lookAt   = pinfo.HomeLookAt;
                    flags   |= TeleportFlags.ViaHome;
                }

                if (tryDefaults)
                {
                    List <GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
                    if (defaults != null && defaults.Count > 0)
                    {
                        region = defaults[0];
                        where  = "safe";
                    }
                    else
                    {
                        m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region",
                                         account.FirstName, account.LastName);
                        region = FindAlternativeRegion(scopeID);
                        if (region != null)
                        {
                            where = "safe";
                        }
                    }
                }

                return(region);
            }
            else if (startLocation.Equals("last"))
            {
                // logging into last visited region
                where = "last";

                if (pinfo == null)
                {
                    return(null);
                }

                GridRegion region = null;

                if (pinfo.LastRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.LastRegionID)) == null)
                {
                    List <GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
                    if (defaults != null && defaults.Count > 0)
                    {
                        region = defaults[0];
                        where  = "safe";
                    }
                    else
                    {
                        m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region");
                        region = FindAlternativeRegion(scopeID);
                        if (region != null)
                        {
                            where = "safe";
                        }
                    }
                }
                else
                {
                    position = pinfo.LastPosition;
                    lookAt   = pinfo.LastLookAt;
                }

                return(region);
            }
            else
            {
                flags |= TeleportFlags.ViaRegionID;

                // free uri form
                // e.g. New Moon&135&46  New [email protected]:8002&153&34
                where = "url";
                GridRegion region   = null;
                Regex      reURI    = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+[.]?\d*)&(?<y>\d+[.]?\d*)&(?<z>\d+[.]?\d*)$");
                Match      uriMatch = reURI.Match(startLocation);
                if (uriMatch == null)
                {
                    m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, but can't process it", startLocation);
                    return(null);
                }
                else
                {
                    position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
                                           float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo),
                                           float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));

                    string regionName = uriMatch.Groups["region"].ToString();
                    if (regionName != null)
                    {
                        if (!regionName.Contains("@"))
                        {
                            List <GridRegion> regions = m_GridService.GetRegionsByName(scopeID, regionName, 1);
                            if ((regions == null) || (regions != null && regions.Count == 0))
                            {
                                m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName);
                                regions = m_GridService.GetDefaultRegions(scopeID);
                                if (regions != null && regions.Count > 0)
                                {
                                    where = "safe";
                                    return(regions[0]);
                                }
                                else
                                {
                                    m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region");
                                    region = FindAlternativeRegion(scopeID);
                                    if (region != null)
                                    {
                                        where = "safe";
                                        return(region);
                                    }
                                    else
                                    {
                                        m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not provide default regions and no alternative found.", startLocation);
                                        return(null);
                                    }
                                }
                            }
                            return(regions[0]);
                        }
                        else
                        {
                            if (m_UserAgentService == null)
                            {
                                m_log.WarnFormat("[LLLOGIN SERVICE]: This llogin service is not running a user agent service, as such it can't lauch agents at foreign grids");
                                return(null);
                            }
                            string[] parts = regionName.Split(new char[] { '@' });
                            if (parts.Length < 2)
                            {
                                m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName);
                                return(null);
                            }
                            // Valid specification of a remote grid

                            regionName = parts[0];
                            string domainLocator = parts[1];
                            parts = domainLocator.Split(new char[] { ':' });
                            string domainName = parts[0];
                            uint   port       = 0;
                            if (parts.Length > 1)
                            {
                                UInt32.TryParse(parts[1], out port);
                            }

                            region = FindForeignRegion(domainName, port, regionName, account, out gatekeeper);
                            return(region);
                        }
                    }
                    else
                    {
                        List <GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
                        if (defaults != null && defaults.Count > 0)
                        {
                            where = "safe";
                            return(defaults[0]);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }
                //response.LookAt = "[r0,r1,r0]";
                //// can be: last, home, safe, url
                //response.StartLocation = "url";
            }
        }
Exemple #44
0
 // subclasses can override this
 protected virtual bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog)
 {
     return(m_SimulationService.CreateObject(destination, newPosition, sog, false));
 }
        public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, EntityTransferContext ctx, out string reason)
        {
            string tmp = String.Empty;

            return(CreateAgent(source, destination, aCircuit, flags, ctx, out tmp, out reason));
        }
        /// <summary>
        /// This Closes child agents on neighbouring regions
        /// Calls an asynchronous method to do so..  so it doesn't lag the sim.
        /// </summary>
        protected ScenePresence CrossAgentToNewRegionAsync(
            ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion,
            bool isFlying, string version)
        {
            try
            {
                ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
    
                m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}", agent.Firstname, agent.Lastname, neighbourx, neighboury, version);
    
                Scene m_scene = agent.Scene;
    
                if (neighbourRegion != null)
                {
                    if (!agent.ValidateAttachments())
                        m_log.DebugFormat(
                            "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for region crossing of {0} from {1} to {2}.  Continuing.",
                            agent.Name, agent.Scene.RegionInfo.RegionName, neighbourRegion.RegionName);

                    pos = pos + agent.Velocity;
                    Vector3 vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0);

                    agent.RemoveFromPhysicalScene();
                    SetInTransit(agent.UUID);

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

                    // We don't need the callback anymnore
                    cAgent.CallbackURI = String.Empty;

                    if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent))
                    {
                        // region doesn't take it
                        ReInstantiateScripts(agent);
                        agent.AddToPhysicalScene(isFlying);
                        ResetFromTransit(agent.UUID);
                        return agent;
                    }
    
                    //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
                    agent.ControllingClient.RequestClientInfo();
    
                    //m_log.Debug("BEFORE CROSS");
                    //Scene.DumpChildrenSeeds(UUID);
                    //DumpKnownRegions();
                    string agentcaps;
                    if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
                    {
                        m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
                                         neighbourRegion.RegionHandle);
                        return agent;
                    }
                    string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps);
    
                    m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);

                    IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
                    if (eq != null)
                    {
                        eq.CrossRegion(neighbourHandle, pos, vel2 /* agent.Velocity */, neighbourRegion.ExternalEndPoint,
                                       capsPath, agent.UUID, agent.ControllingClient.SessionId);
                    }
                    else
                    {
                        agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
                                                    capsPath);
                    }

                    // SUCCESS! 
                    agent.MakeChildAgent();
                        ResetFromTransit(agent.UUID);

                    // now we have a child agent in this region. Request all interesting data about other (root) agents
                    agent.SendOtherAgentsAvatarDataToMe();
                    agent.SendOtherAgentsAppearanceToMe();

                    // Backwards compatibility. Best effort
                    if (version == "Unknown" || version == string.Empty)
                    {
                        m_log.DebugFormat("[ENTITY TRANSFER MODULE]: neighbor with old version, passing attachments one by one...");
                        Thread.Sleep(3000); // wait a little now that we're not waiting for the callback
                        CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
                    }


                    // Next, let's close the child agent connections that are too far away.
                    agent.CloseChildAgents(neighbourx, neighboury);
    
                    AgentHasMovedAway(agent, false);
    
                    // the user may change their profile information in other region,
                    // so the userinfo in UserProfileCache is not reliable any more, delete it
                    // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
                    if (agent.Scene.NeedSceneCacheClear(agent.UUID))
                    {
                        m_log.DebugFormat(
                            "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID);
                    }
                }
    
                //m_log.Debug("AFTER CROSS");
                //Scene.DumpChildrenSeeds(UUID);
                //DumpKnownRegions();
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2}.  Exception {3}{4}",
                    agent.Name, neighbourRegion.RegionName, agent.Scene.RegionInfo.RegionName, e.Message, e.StackTrace);
            }

            return agent;
        }
Exemple #47
0
        private void OnMapNameRequest(IClientAPI remoteClient, string mapName)
        {
            if (mapName.Length < 1)
            {
                remoteClient.SendAlertMessage("Use a search string with at least 1 character");
                return;
            }

            bool TryCoordsSearch = false;
            int  XCoord          = 0;
            int  YCoord          = 0;

            string[] splitSearch = mapName.Split(',');
            if (splitSearch.Length != 1)
            {
                if (int.TryParse(splitSearch[0], out XCoord) && int.TryParse(splitSearch[1], out YCoord))
                {
                    TryCoordsSearch = true;
                }
            }

            List <MapBlockData> blocks = new List <MapBlockData>();

            List <GridRegion> regionInfos = m_scene.GridService.GetRegionsByName(UUID.Zero, mapName, 20);

            if (TryCoordsSearch)
            {
                GridRegion region = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)(XCoord * Constants.RegionSize), (int)(YCoord * Constants.RegionSize));
                if (region != null)
                {
                    regionInfos.Add(region);
                }
            }
            foreach (GridRegion region in regionInfos)
            {
                //Add the found in search region first
                blocks.Add(SearchMapBlockFromGridRegion(region));
                //Then send surrounding regions
                List <GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
                                                                               (region.RegionLocX - (4 * (int)Constants.RegionSize)),
                                                                               (region.RegionLocX + (4 * (int)Constants.RegionSize)),
                                                                               (region.RegionLocY - (4 * (int)Constants.RegionSize)),
                                                                               (region.RegionLocY + (4 * (int)Constants.RegionSize)));
                foreach (GridRegion r in regions)
                {
                    blocks.Add(SearchMapBlockFromGridRegion(r));
                }
            }

            // final block, closing the search result
            MapBlockData data = new MapBlockData();

            data.Agents      = 0;
            data.Access      = 255;
            data.MapImageID  = UUID.Zero;
            data.Name        = mapName;
            data.RegionFlags = 0;
            data.WaterHeight = 0; // not used
            data.X           = 0;
            data.Y           = 0;
            blocks.Add(data);

            remoteClient.SendMapBlock(blocks, 0);
        }
Exemple #48
0
        public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, string serverURI, UUID ownerID, out GridRegion regInfo, out string reason)
        {
            m_log.DebugFormat("[HYPERGRID LINKER]: Link to {0} {1}, in {2}-{3}",
                              ((serverURI == null) ? (externalHostName + ":" + externalPort) : serverURI),
                              remoteRegionName, xloc / Constants.RegionSize, yloc / Constants.RegionSize);

            reason = string.Empty;
            Uri uri = null;

            regInfo = new GridRegion();
            if (externalPort > 0)
            {
                regInfo.HttpPort = externalPort;
            }
            else
            {
                regInfo.HttpPort = 0;
            }
            if (externalHostName != null)
            {
                regInfo.ExternalHostName = externalHostName;
            }
            else
            {
                regInfo.ExternalHostName = "0.0.0.0";
            }
            if (serverURI != null)
            {
                regInfo.ServerURI = serverURI;
                try
                {
                    uri = new Uri(serverURI);
                    regInfo.ExternalHostName = uri.Host;
                    regInfo.HttpPort         = (uint)uri.Port;
                }
                catch {}
            }

            if (remoteRegionName != string.Empty)
            {
                regInfo.RegionName = remoteRegionName;
            }

            regInfo.RegionLocX  = xloc;
            regInfo.RegionLocY  = yloc;
            regInfo.ScopeID     = scopeID;
            regInfo.EstateOwner = ownerID;

            // Make sure we're not hyperlinking to regions on this grid!
            if (m_ThisGatekeeperURI != null)
            {
                if (regInfo.ExternalHostName == m_ThisGatekeeperURI.Host && regInfo.HttpPort == m_ThisGatekeeperURI.Port)
                {
                    reason = "Cannot hyperlink to regions on the same grid";
                    return(false);
                }
            }
            else
            {
                m_log.WarnFormat("[HYPERGRID LINKER]: Please set this grid's Gatekeeper's address in [GridService]!");
            }

            // Check for free coordinates
            GridRegion region = m_GridService.GetRegionByPosition(regInfo.ScopeID, regInfo.RegionLocX, regInfo.RegionLocY);

            if (region != null)
            {
                m_log.WarnFormat("[HYPERGRID LINKER]: Coordinates {0}-{1} are already occupied by region {2} with uuid {3}",
                                 regInfo.RegionLocX / Constants.RegionSize, regInfo.RegionLocY / Constants.RegionSize,
                                 region.RegionName, region.RegionID);
                reason = "Coordinates are already in use";
                return(false);
            }

            try
            {
                regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0);
            }
            catch (Exception e)
            {
                m_log.Warn("[HYPERGRID LINKER]: Wrong format for link-region: " + e.Message);
                reason = "Internal error";
                return(false);
            }

            // Finally, link it
            ulong  handle       = 0;
            UUID   regionID     = UUID.Zero;
            string externalName = string.Empty;
            string imageURL     = string.Empty;

            if (!m_GatekeeperConnector.LinkRegion(regInfo, out regionID, out handle, out externalName, out imageURL, out reason))
            {
                return(false);
            }

            if (regionID == UUID.Zero)
            {
                m_log.Warn("[HYPERGRID LINKER]: Unable to link region");
                reason = "Remote region could not be found";
                return(false);
            }

            region = m_GridService.GetRegionByUUID(scopeID, regionID);
            if (region != null)
            {
                m_log.DebugFormat("[HYPERGRID LINKER]: Region already exists in coordinates {0} {1}",
                                  region.RegionLocX / Constants.RegionSize, region.RegionLocY / Constants.RegionSize);
                regInfo = region;
                return(true);
            }

            uint x, y;

            if (m_Check4096 && !Check4096(handle, out x, out y))
            {
                RemoveHyperlinkRegion(regInfo.RegionID);
                reason = "Region is too far (" + x + ", " + y + ")";
                m_log.Info("[HYPERGRID LINKER]: Unable to link, region is too far (" + x + ", " + y + ")");
                return(false);
            }

            regInfo.RegionID = regionID;

            if (externalName == string.Empty)
            {
                regInfo.RegionName = regInfo.ServerURI;
            }
            else
            {
                regInfo.RegionName = externalName;
            }

            m_log.DebugFormat("[HYPERGRID LINKER]: naming linked region {0}, handle {1}", regInfo.RegionName, handle.ToString());

            // Get the map image
            regInfo.TerrainImage = GetMapImage(regionID, imageURL);

            // Store the origin's coordinates somewhere
            regInfo.RegionSecret = handle.ToString();

            AddHyperlinkRegion(regInfo, handle);
            m_log.InfoFormat("[HYPERGRID LINKER]: Successfully linked to region {0} with image {1}", regInfo.RegionName, regInfo.TerrainImage);
            return(true);
        }
 protected override bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination,
                                     AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason)
 {
     return(m_GatekeeperService.LoginAgent(source, aCircuit, destination, out reason));
 }
Exemple #50
0
 public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, UUID ownerID, out GridRegion regInfo, out string reason)
 {
     return(TryCreateLink(scopeID, xloc, yloc, remoteRegionName, externalPort, externalHostName, null, ownerID, out regInfo, out reason));
 }
Exemple #51
0
        protected void DoObjectPost(Hashtable request, Hashtable responsedata, UUID regionID)
        {
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            if (args == null)
            {
                responsedata["int_response_code"]   = 400;
                responsedata["str_response_string"] = "false";
                return;
            }
            // retrieve the input arguments
            int     x = 0, y = 0;
            UUID    uuid        = UUID.Zero;
            string  regionname  = string.Empty;
            Vector3 newPosition = Vector3.Zero;

            if (args.ContainsKey("destination_x") && args["destination_x"] != null)
            {
                Int32.TryParse(args["destination_x"].AsString(), out x);
            }
            if (args.ContainsKey("destination_y") && args["destination_y"] != null)
            {
                Int32.TryParse(args["destination_y"].AsString(), out 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("new_position") && args["new_position"] != null)
            {
                Vector3.TryParse(args["new_position"], out newPosition);
            }

            GridRegion destination = new GridRegion();

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

            string sogXmlStr = "", extraStr = "", stateXmlStr = "";

            if (args.ContainsKey("sog") && args["sog"] != null)
            {
                sogXmlStr = args["sog"].AsString();
            }
            if (args.ContainsKey("extra") && args["extra"] != null)
            {
                extraStr = args["extra"].AsString();
            }

            IScene       s   = m_SimulationService.GetScene(destination.RegionHandle);
            ISceneObject sog = null;

            try
            {
                //m_log.DebugFormat("[OBJECT HANDLER]: received {0}", sogXmlStr);
                sog = s.DeserializeObject(sogXmlStr);
                sog.ExtraFromXmlString(extraStr);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[OBJECT HANDLER]: exception on deserializing scene object {0}", ex.Message);
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            if (args.ContainsKey("modified"))
            {
                sog.HasGroupChanged = args["modified"].AsBoolean();
            }
            else
            {
                sog.HasGroupChanged = false;
            }

            if ((args["state"] != null) && s.AllowScriptCrossings)
            {
                stateXmlStr = args["state"].AsString();
                if (stateXmlStr != "")
                {
                    try
                    {
                        sog.SetState(stateXmlStr, s);
                    }
                    catch (Exception ex)
                    {
                        m_log.InfoFormat("[OBJECT HANDLER]: exception on setting state for scene object {0}", ex.Message);
                        // ignore and continue
                    }
                }
            }

            bool result = false;

            try
            {
                // This is the meaning of POST object
                result = CreateObject(destination, newPosition, sog);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[OBJECT HANDLER]: Exception in CreateObject: {0}", e.StackTrace);
            }

            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = result.ToString();
        }
Exemple #52
0
        /// <summary>
        /// Create a user
        /// </summary>
        /// <param name="scopeID">Allows hosting of multiple grids in a single database.  Normally left as UUID.Zero</param>
        /// <param name="principalID">ID of the user</param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="password"></param>
        /// <param name="email"></param>
        /// <param name="model"></param>
        public UserAccount CreateUser(UUID scopeID, UUID principalID, string firstName, string lastName, string password, string email, string model = "")
        {
            UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);

            if (null == account)
            {
                account = new UserAccount(UUID.Zero, principalID, firstName, lastName, email);
                if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
                {
                    account.ServiceURLs                       = new Dictionary <string, object>();
                    account.ServiceURLs["HomeURI"]            = string.Empty;
                    account.ServiceURLs["InventoryServerURI"] = string.Empty;
                    account.ServiceURLs["AssetServerURI"]     = string.Empty;
                }

                if (StoreUserAccount(account))
                {
                    bool success;
                    if (m_AuthenticationService != null)
                    {
                        success = m_AuthenticationService.SetPassword(account.PrincipalID, password);
                        if (!success)
                        {
                            m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.",
                                             firstName, lastName);
                        }
                    }

                    GridRegion home = null;
                    if (m_GridService != null)
                    {
                        List <GridRegion> defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero);
                        if (defaultRegions != null && defaultRegions.Count >= 1)
                        {
                            home = defaultRegions[0];
                        }

                        if (m_GridUserService != null && home != null)
                        {
                            m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
                        }
                        else
                        {
                            m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.",
                                             firstName, lastName);
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.",
                                         firstName, lastName);
                    }

                    if (m_InventoryService != null)
                    {
                        success = m_InventoryService.CreateUserInventory(account.PrincipalID);
                        if (!success)
                        {
                            m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.",
                                             firstName, lastName);
                        }
                        else
                        {
                            m_log.DebugFormat(
                                "[USER ACCOUNT SERVICE]: Created user inventory for {0} {1}", firstName, lastName);
                        }

                        if (m_CreateDefaultAvatarEntries)
                        {
                            if (String.IsNullOrEmpty(model))
                            {
                                CreateDefaultAppearanceEntries(account.PrincipalID);
                            }
                            else
                            {
                                EstablishAppearance(account.PrincipalID, model);
                            }
                        }
                    }

                    m_log.InfoFormat(
                        "[USER ACCOUNT SERVICE]: Account {0} {1} {2} created successfully",
                        firstName, lastName, account.PrincipalID);
                }
                else
                {
                    m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0} {1}", firstName, lastName);
                }
            }
            else
            {
                m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName);
            }

            return(account);
        }
 protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent)
 {
     return m_aScene.SimulationService.UpdateAgent(finalDestination, agent);
 }
Exemple #54
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;
            string     gatekeeper_host       = string.Empty;
            string     gatekeeper_serveruri  = string.Empty;
            string     destination_serveruri = string.Empty;
            int        gatekeeper_port       = 0;
            IPEndPoint client_ipaddress      = null;

            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);
            }
            if (args.ContainsKey("gatekeeper_serveruri") && args["gatekeeper_serveruri"] != null)
            {
                gatekeeper_serveruri = args["gatekeeper_serveruri"];
            }
            if (args.ContainsKey("destination_serveruri") && args["destination_serveruri"] != null)
            {
                destination_serveruri = args["destination_serveruri"];
            }

            GridRegion gatekeeper = new GridRegion();

            gatekeeper.ServerURI        = gatekeeper_serveruri;
            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
            {
                MainConsole.Instance.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
            {
                MainConsole.Instance.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("client_ip") && args["client_ip"] != null)
            {
                string ip_str = args["client_ip"].ToString();
                try
                {
                    string callerIP = GetCallerIP(request);
                    // Verify if this caller has authority to send the client IP
                    if (callerIP == m_loginServerIP)
                    {
                        client_ipaddress = new IPEndPoint(IPAddress.Parse(ip_str), 0);
                    }
                    else // leaving this for now, but this warning should be removed
                    {
                        MainConsole.Instance.WarnFormat("[HOME AGENT HANDLER]: Unauthorized machine {0} tried to set client ip to {1}", callerIP, ip_str);
                    }
                }
                catch
                {
                    MainConsole.Instance.DebugFormat("[HOME AGENT HANDLER]: Exception parsing client ip address from {0}", ip_str);
                }
            }

            GridRegion destination = new GridRegion();

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

            AgentCircuitData aCircuit = new AgentCircuitData();

            try
            {
                aCircuit.UnpackAgentCircuitData(args);
            }
            catch (Exception ex)
            {
                MainConsole.Instance.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, client_ipaddress, 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);
        }
 protected virtual bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
 {
     return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
 }
Exemple #56
0
        // From the command line and the 2 above
        public bool TryCreateLink(UUID scopeID, int xloc, int yloc,
                                  string externalRegionName, uint externalPort, string externalHostName, out GridRegion regInfo, out string reason)
        {
            m_log.DebugFormat("[HYPERGRID LINKER]: Link to {0}:{1}:{2}, in {3}-{4}", externalHostName, externalPort, externalRegionName, xloc, yloc);

            reason                   = string.Empty;
            regInfo                  = new GridRegion();
            regInfo.RegionName       = externalRegionName;
            regInfo.HttpPort         = externalPort;
            regInfo.ExternalHostName = externalHostName;
            regInfo.RegionLocX       = xloc;
            regInfo.RegionLocY       = yloc;
            regInfo.ScopeID          = scopeID;

            try
            {
                regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0);
            }
            catch (Exception e)
            {
                m_log.Warn("[HYPERGRID LINKER]: Wrong format for link-region: " + e.Message);
                reason = "Internal error";
                return(false);
            }

            // Finally, link it
            ulong  handle       = 0;
            UUID   regionID     = UUID.Zero;
            string externalName = string.Empty;
            string imageURL     = string.Empty;

            if (!m_GatekeeperConnector.LinkRegion(regInfo, out regionID, out handle, out externalName, out imageURL, out reason))
            {
                return(false);
            }

            if (regionID != UUID.Zero)
            {
                GridRegion r = m_GridService.GetRegionByUUID(scopeID, regionID);
                if (r != null)
                {
                    m_log.DebugFormat("[HYPERGRID LINKER]: Region already exists in coordinates {0} {1}", r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize);
                    regInfo = r;
                    return(true);
                }

                regInfo.RegionID = regionID;
                if (regInfo.RegionName == string.Empty)
                {
                    regInfo.RegionName = regInfo.ExternalHostName;
                }

                // Try get the map image
                //regInfo.TerrainImage = m_GatekeeperConnector.GetMapImage(regionID, imageURL);
                // I need a texture that works for this... the one I tried doesn't seem to be working
                regInfo.TerrainImage = m_HGMapImage;

                AddHyperlinkRegion(regInfo, handle);
                m_log.Info("[HYPERGRID LINKER]: Successfully linked to region_uuid " + regInfo.RegionID);
            }
            else
            {
                m_log.Warn("[HYPERGRID LINKER]: Unable to link region");
                reason = "Remote region could not be found";
                return(false);
            }

            uint x, y;

            if (m_Check4096 && !Check4096(handle, out x, out y))
            {
                RemoveHyperlinkRegion(regInfo.RegionID);
                reason = "Region is too far (" + x + ", " + y + ")";
                m_log.Info("[HYPERGRID LINKER]: Unable to link, region is too far (" + x + ", " + y + ")");
                return(false);
            }

            m_log.Debug("[HYPERGRID LINKER]: link region succeeded");
            return(true);
        }
        /// <summary>
        /// This informs a single neighbouring region about agent "avatar".
        /// Calls an asynchronous method to do so..  so it doesn't lag the sim.
        /// </summary>
        /// <param name="sp"></param>
        /// <param name="region"></param>
        public void EnableChildAgent(ScenePresence sp, GridRegion region)
        {
            m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName);

            AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
            AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
            agent.BaseFolder = UUID.Zero;
            agent.InventoryFolder = UUID.Zero;
            agent.startpos = new Vector3(128, 128, 70);
            agent.child = true;
            agent.Appearance = sp.Appearance;
            agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();

            agent.ChildrenCapSeeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
            //m_log.DebugFormat("[XXX] Seeds 1 {0}", agent.ChildrenCapSeeds.Count);

            if (!agent.ChildrenCapSeeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
                agent.ChildrenCapSeeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
            //m_log.DebugFormat("[XXX] Seeds 2 {0}", agent.ChildrenCapSeeds.Count);

            sp.AddNeighbourRegion(region.RegionHandle, agent.CapsPath);
            //foreach (ulong h in agent.ChildrenCapSeeds.Keys)
            //    m_log.DebugFormat("[XXX] --> {0}", h);
            //m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
            agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);

            if (sp.Scene.CapsModule != null)
            {
                sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, agent.ChildrenCapSeeds);
            }

            if (currentAgentCircuit != null)
            {
                agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
                agent.IPAddress = currentAgentCircuit.IPAddress;
                agent.Viewer = currentAgentCircuit.Viewer;
                agent.Channel = currentAgentCircuit.Channel;
                agent.Mac = currentAgentCircuit.Mac;
                agent.Id0 = currentAgentCircuit.Id0;
            }

            InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
            d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
                          InformClientOfNeighbourCompleted,
                          d);
        }
Exemple #58
0
        public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
        {
            GridRegion rinfo        = null;
            ulong      regionHandle = Util.UIntsToLong((uint)x, (uint)y);

            // this cache includes NULL regions
            if (m_regionCache.TryGetValue(regionHandle, out rinfo))
            {
                return(rinfo);
            }

            Dictionary <string, object> sendData = new Dictionary <string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["X"]       = x.ToString();
            sendData["Y"]       = y.ToString();

            sendData["METHOD"] = "get_region_by_position";
            string reply = string.Empty;
            string uri   = m_ServerURI + "/grid";

            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                  uri,
                                                                  ServerUtils.BuildQueryString(sendData), m_Auth);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
                return(null);
            }

            if (reply != string.Empty)
            {
                Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && (replyData["result"] != null))
                {
                    if (replyData["result"] is Dictionary <string, object> )
                    {
                        rinfo = new GridRegion((Dictionary <string, object>)replyData["result"]);
                    }
                    //else
                    //    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region",
                    //        scopeID, x, y);
                }
                else
                {
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
                                      scopeID, x, y);
                }
            }
            else
            {
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");
            }

            m_regionCache.Add(regionHandle, rinfo, TimeSpan.FromSeconds(600));

            return(rinfo);
        }