Exemple #1
0
        public override byte[] Handle(string path, Stream requestData,
                                      OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            //m_log.DebugFormat("[XXX]: query String: {0}", body);
            string method = string.Empty;

            try
            {
                OSDMap map = (OSDMap)OSDParser.DeserializeJson(body);
                //Make sure that the person who is calling can access the web service
                if (VerifyPassword(map))
                {
                    method = map["Method"].AsString();
                    if (method == "Login")
                    {
                        return(ProcessLogin(map));
                    }
                    else if (method == "AdminLogin")
                    {
                        return(ProcessAdminLogin(map));
                    }
                    else if (method == "CreateAccount")
                    {
                        return(ProcessCreateAccount(map));
                    }
                    else if (method == "OnlineStatus")
                    {
                        return(ProcessOnlineStatus(map));
                    }
                    else if (method == "Authenticated")
                    {
                        return(Authenticated(map));
                    }
                    else if (method == "GetGridUserInfo")
                    {
                        return(GetGridUserInfo(map));
                    }
                    else if (method == "ChangePassword")
                    {
                        return(ChangePassword(map));
                    }
                    else if (method == "CheckIfUserExists")
                    {
                        return(CheckIfUserExists(map));
                    }
                    else if (method == "SaveEmail")
                    {
                        return(SaveEmail(map));
                    }
                    else if (method == "ChangeName")
                    {
                        return(ChangeName(map));
                    }
                    else if (method == "ConfirmUserEmailName")
                    {
                        return(ConfirmUserEmailName(map));
                    }
                    else if (method == "ForgotPassword")
                    {
                        return(ForgotPassword(map));
                    }
                    else if (method == "GetProfile")
                    {
                        return(GetProfile(map));
                    }
                    else if (method == "GetAvatarArchives")
                    {
                        return(GetAvatarArchives(map));
                    }
                    else if (method == "DeleteUser")
                    {
                        return(DeleteUser(map));
                    }
                    else if (method == "BanUser")
                    {
                        return(BanUser(map));
                    }
                    else if (method == "TempBanUser")
                    {
                        return(TempBanUser(map));
                    }
                    else if (method == "UnBanUser")
                    {
                        return(UnBanUser(map));
                    }
                    else if (method == "FindUsers")
                    {
                        return(FindUsers(map));
                    }
                    else if (method == "GetAbuseReports")
                    {
                        return(GetAbuseReports(map));
                    }
                    else if (method == "AbuseReportSaveNotes")
                    {
                        return(AbuseReportSaveNotes(map));
                    }
                    else if (method == "AbuseReportMarkComlete")
                    {
                        return(AbuseReportMarkComlete(map));
                    }
                    else if (method == "SetWebLoginKey")
                    {
                        return(SetWebLoginKey(map));
                    }
                }
            }
            catch (Exception)
            {
            }
            OSDMap resp = new OSDMap();

            resp.Add("response", OSD.FromString("Failed"));
            string       xmlString = OSDParser.SerializeJsonString(resp);
            UTF8Encoding encoding  = new UTF8Encoding();

            return(encoding.GetBytes(xmlString));
        }
        private Color4 GetFaceColor(Primitive.TextureEntryFace face)
        {
            Color4 color;

            if (face.TextureID == UUID.Zero)
            {
                return(face.RGBA);
            }

            if (!m_colors.TryGetValue(face.TextureID, out color))
            {
                bool fetched = false;

                // Attempt to fetch the texture metadata
                UUID      metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
                AssetBase metadata   = m_scene.AssetService.GetCached(metadataID.ToString());
                if (metadata != null)
                {
                    OSDMap map = null;
                    try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; }
                    catch { }

                    if (map != null)
                    {
                        color   = map["X-JPEG2000-RGBA"].AsColor4();
                        fetched = true;
                    }
                }

                if (!fetched)
                {
                    // Fetch the texture, decode and get the average color,
                    // then save it to a temporary metadata asset
                    AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
                    if (textureAsset != null)
                    {
                        int width, height;
                        color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);

                        OSDMap data = new OSDMap {
                            { "X-JPEG2000-RGBA", OSD.FromColor4(color) }
                        };
                        metadata = new AssetBase
                        {
                            Data        = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
                            Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
                            Flags       = AssetFlags.Collectable,
                            FullID      = metadataID,
                            ID          = metadataID.ToString(),
                            Local       = true,
                            Temporary   = true,
                            Name        = String.Empty,
                            Type        = (sbyte)AssetType.Simstate // Make something up to get around OpenSim's myopic treatment of assets
                        };
                        m_scene.AssetService.Store(metadata);
                    }
                    else
                    {
                        color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
                    }
                }

                m_colors[face.TextureID] = color;
            }

            return(color * face.RGBA);
        }
Exemple #3
0
        protected virtual void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            if (m_safemode)
            {
                // Authentication
                string authority = string.Empty;
                string authToken = string.Empty;
                if (!GetAuthentication(request, out authority, out authToken))
                {
                    m_log.InfoFormat("[REST COMMS]: Authentication failed for agent message {0}", request["uri"]);
                    responsedata["int_response_code"]   = 403;
                    responsedata["str_response_string"] = "Forbidden";
                    return;
                }
                if (!VerifyKey(id, authority, authToken))
                {
                    m_log.InfoFormat("[REST COMMS]: Authentication failed for agent message {0}", request["uri"]);
                    responsedata["int_response_code"]   = 403;
                    responsedata["str_response_string"] = "Forbidden";
                    return;
                }
                m_log.DebugFormat("[REST COMMS]: Authentication succeeded for {0}", id);
            }

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

            if (args == null)
            {
                responsedata["int_response_code"]   = 400;
                responsedata["str_response_string"] = "false";
                return;
            }

            // retrieve the regionhandle
            ulong regionhandle = 0;

            if (args["destination_handle"] != null)
            {
                UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
            }

            AgentCircuitData aCircuit = new AgentCircuitData();

            try
            {
                aCircuit.UnpackAgentCircuitData(args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildCreate message {0}", ex.Message);
                return;
            }

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

            // This is the meaning of POST agent
            m_regionClient.AdjustUserInformation(aCircuit);
            bool result = m_localBackend.SendCreateChildAgent(regionhandle, aCircuit, out reason);

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

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = 200;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

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

            AgentDestinationData data = CreateAgentDestinationData();

            UnpackData(args, data, request);

            GridRegion destination = new GridRegion();

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

            GridRegion gatekeeper = ExtractGatekeeper(data);

            AgentCircuitData aCircuit = new AgentCircuitData();

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

            GridRegion source = null;

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

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

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

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

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

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
Exemple #5
0
        public void SaveStateTo(ScriptData script, bool forced, bool saveBackup)
        {
            if (!forced)
            {
                if (script.Script == null)
                {
                    return; //If it didn't compile correctly, this happens
                }
                if (!script.Script.NeedsStateSaved)
                {
                    return; //If it doesn't need a state save, don't save one
                }
            }
            if (script.Script != null)
            {
                script.Script.NeedsStateSaved = false;
            }
            StateSave stateSave = new StateSave
            {
                State           = script.State,
                ItemID          = script.ItemID,
                Running         = script.Running,
                MinEventDelay   = script.EventDelayTicks,
                Disabled        = script.Disabled,
                UserInventoryID = script.UserInventoryItemID,
                AssemblyName    = script.AssemblyName,
                Compiled        = script.Compiled,
                Source          = script.Source == null ? "" : script.Source
            };

            //Allow for the full path to be put down, not just the assembly name itself
            if (script.InventoryItem != null)
            {
                stateSave.PermsGranter = script.InventoryItem.PermsGranter;
                stateSave.PermsMask    = script.InventoryItem.PermsMask;
            }
            else
            {
                stateSave.PermsGranter = UUID.Zero;
                stateSave.PermsMask    = 0;
            }
            stateSave.TargetOmegaWasSet = script.TargetOmegaWasSet;

            //Vars
            Dictionary <string, object> vars = new Dictionary <string, object>();

            if (script.Script != null)
            {
                vars = script.Script.GetStoreVars();
            }
            stateSave.Variables = XMLUtils.BuildXmlResponse(vars);

            //Plugins
            stateSave.Plugins =
                OSDParser.SerializeJsonString(m_module.GetSerializationData(script.ItemID, script.Part.UUID));

            lock (StateSaveLock)
                script.Part.StateSaves[script.ItemID] = stateSave;
            if (saveBackup)
            {
                script.Part.ParentEntity.HasGroupChanged = true;
            }
        }
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = WebUtils.GetOSDMap((string)request["body"]);

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

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

            if (args.ContainsKey("destination_x") && args["destination_x"] != null)
            {
                Int32.TryParse(args["destination_x"].AsString(), out x);
            }
            else
            {
                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("teleport_flags") && args["teleport_flags"] != null)
            {
                teleportFlags = args["teleport_flags"].AsUInteger();
            }

            AgentData agent = null;

            if (args.ContainsKey("agent_data") && args["agent_data"] != null)
            {
                try
                {
                    OSDMap agentDataMap = (OSDMap)args["agent_data"];
                    agent = new AgentData();
                    agent.Unpack(agentDataMap);
                }
                catch (Exception ex)
                {
                    MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex);
                }
            }

            GridRegion destination = new GridRegion
            {
                RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname
            };

            AgentCircuitData aCircuit = new AgentCircuitData();

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

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

            int requestedUDPPort = 0;
            // This is the meaning of POST agent
            bool result = CreateAgent(destination, ref aCircuit, teleportFlags, agent, out requestedUDPPort, out reason);

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

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
        public Hashtable Handler(Hashtable request)
        {
            //MainConsole.Instance.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");

            //MainConsole.Instance.Debug("---------------------------");
            //MainConsole.Instance.Debug(" >> uri=" + request["uri"]);
            //MainConsole.Instance.Debug(" >> content-type=" + request["content-type"]);
            //MainConsole.Instance.Debug(" >> http-method=" + request["http-method"]);
            //MainConsole.Instance.Debug("---------------------------\n");

            Hashtable responsedata = new Hashtable();

            responsedata["content_type"]        = "text/html";
            responsedata["keepalive"]           = false;
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = "";


            UUID   agentID;
            UUID   regionID;
            string action;
            string other;
            string uri = ((string)request["uri"]);

            if (m_secure)
            {
                uri = uri.Remove(0, 37); //Remove the secure UUID from the uri
            }
            if (!WebUtils.GetParams(uri, out agentID, out regionID, out action, out other))
            {
                MainConsole.Instance.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
                responsedata["int_response_code"]   = 404;
                responsedata["str_response_string"] = "false";

                return(responsedata);
            }

            // Next, let's parse the verb
            string method = (string)request["http-method"];

            if (method.Equals("PUT"))
            {
                DoAgentPut(request, responsedata);
                return(responsedata);
            }
            else if (method.Equals("POST"))
            {
                OSDMap map = null;
                try
                {
                    string data = request["body"].ToString();
                    map = (OSDMap)OSDParser.DeserializeJson(data);
                }
                catch
                {
                    map = null;
                }
                if (map != null)
                {
                    if (map["Method"] == "MakeChildAgent")
                    {
                        DoMakeChildAgent(agentID, regionID);
                    }
                    else if (map["Method"] == "FailedToMoveAgentIntoNewRegion")
                    {
                        FailedToMoveAgentIntoNewRegion(agentID, regionID);
                    }
                    else
                    {
                        DoAgentPost(request, responsedata, agentID);
                    }
                }
                return(responsedata);
            }
            else if (method.Equals("GET"))
            {
                DoAgentGet(request, responsedata, agentID, regionID, bool.Parse(action));
                return(responsedata);
            }
            else if (method.Equals("DELETE"))
            {
                DoAgentDelete(request, responsedata, agentID, action, regionID);
                return(responsedata);
            }
            else if (method.Equals("QUERYACCESS"))
            {
                responsedata["int_response_code"] = HttpStatusCode.OK;

                OSDMap resp = new OSDMap(2);

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

                responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
                return(responsedata);
            }
            else
            {
                MainConsole.Instance.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method);
                responsedata["int_response_code"]   = HttpStatusCode.MethodNotAllowed;
                responsedata["str_response_string"] = "Method not allowed";

                return(responsedata);
            }
        }
        public override byte[] Handle(string path, Stream request,
                                      OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            byte[] result = new byte[0];

            UUID   regionID;
            string action;
            ulong  regionHandle;

            if (RestHandlerUtils.GetParams(path, out regionID, out regionHandle, out action))
            {
                m_log.InfoFormat("[RegionPostHandler]: Invalid parameters for neighbour message {0}", path);
                httpResponse.StatusCode        = (int)HttpStatusCode.BadRequest;
                httpResponse.StatusDescription = "Invalid parameters for neighbour message " + path;

                return(result);
            }

            if (m_AuthenticationService != null)
            {
                // Authentication
                string authority = string.Empty;
                string authToken = string.Empty;
                if (!RestHandlerUtils.GetAuthentication(httpRequest, out authority, out authToken))
                {
                    m_log.InfoFormat("[RegionPostHandler]: Authentication failed for neighbour message {0}", path);
                    httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(result);
                }
                // TODO: Rethink this
                //if (!m_AuthenticationService.VerifyKey(regionID, authToken))
                //{
                //    m_log.InfoFormat("[RegionPostHandler]: Authentication failed for neighbour message {0}", path);
                //    httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
                //    return result;
                //}
                m_log.DebugFormat("[RegionPostHandler]: Authentication succeeded for {0}", regionID);
            }

            OSDMap args = Util.GetOSDMap(request, (int)httpRequest.ContentLength);

            if (args == null)
            {
                httpResponse.StatusCode        = (int)HttpStatusCode.BadRequest;
                httpResponse.StatusDescription = "Unable to retrieve data";
                m_log.DebugFormat("[RegionPostHandler]: Unable to retrieve data for post {0}", path);
                return(result);
            }

            // retrieve the regionhandle
            ulong regionhandle = 0;

            if (args["destination_handle"] != null)
            {
                UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
            }

            RegionInfo aRegion = new RegionInfo();

            try
            {
                aRegion.UnpackRegionInfoData(args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[RegionPostHandler]: exception on unpacking region info {0}", ex.Message);
                httpResponse.StatusCode        = (int)HttpStatusCode.BadRequest;
                httpResponse.StatusDescription = "Problems with data deserialization";
                return(result);
            }

            // Finally!
            GridRegion thisRegion = m_NeighbourService.HelloNeighbour(regionhandle, aRegion);

            OSDMap resp = new OSDMap(1);

            if (thisRegion != null)
            {
                resp["success"] = OSD.FromBoolean(true);
            }
            else
            {
                resp["success"] = OSD.FromBoolean(false);
            }

            httpResponse.StatusCode = (int)HttpStatusCode.OK;

            return(Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)));
        }
        // The Login service calls this interface with a non-null [client] ipaddress
        public bool LoginAgentToGrid(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, IPEndPoint ipaddress, out string reason)
        {
            reason = String.Empty;

            if (destination == null)
            {
                reason = "Destination is null";
                MainConsole.Instance.Debug("[USER AGENT CONNECTOR]: Given destination is null");
                return(false);
            }

            string uri = m_ServerURL + "homeagent/" + aCircuit.AgentID + "/";

            Console.WriteLine("   >>> LoginAgentToGrid <<< " + uri);

            HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);

            AgentCreateRequest.Method      = "POST";
            AgentCreateRequest.ContentType = "application/json";
            AgentCreateRequest.Timeout     = 10000;
            //AgentCreateRequest.KeepAlive = false;
            //AgentCreateRequest.Headers.Add("Authorization", authKey);

            // Fill it in
            OSDMap args = PackCreateAgentArguments(aCircuit, gatekeeper, destination, ipaddress);

            string strBuffer = "";

            byte[] buffer = new byte[1];
            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                Encoding str = Util.UTF8;
                buffer = str.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                MainConsole.Instance.WarnFormat("[USER AGENT CONNECTOR]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
                // ignore. buffer will be empty, caller should check.
            }

            Stream os = null;

            try
            {                                                     // send the Post
                AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
                os = AgentCreateRequest.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);            //Send it
                MainConsole.Instance.InfoFormat("[USER AGENT CONNECTOR]: Posted CreateAgent request to remote sim {0}, region {1}, x={2} y={3}",
                                                uri, destination.RegionName, destination.RegionLocX, destination.RegionLocY);
            }
            //catch (WebException ex)
            catch
            {
                //MainConsole.Instance.InfoFormat("[USER AGENT CONNECTOR]: Bad send on ChildAgentUpdate {0}", ex.Message);
                reason = "cannot contact remote region";
                return(false);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            // Let's wait for the response
            //MainConsole.Instance.Info("[USER AGENT CONNECTOR]: Waiting for a reply after DoCreateChildAgentCall");

            WebResponse  webResponse = null;
            StreamReader sr          = null;

            try
            {
                webResponse = AgentCreateRequest.GetResponse();
                if (webResponse == null)
                {
                    MainConsole.Instance.Info("[USER AGENT CONNECTOR]: Null reply on DoCreateChildAgentCall post");
                }
                else
                {
                    sr = new StreamReader(webResponse.GetResponseStream());
                    string response = sr.ReadToEnd().Trim();
                    MainConsole.Instance.InfoFormat("[USER AGENT CONNECTOR]: DoCreateChildAgentCall reply was {0} ", response);

                    if (!String.IsNullOrEmpty(response))
                    {
                        try
                        {
                            // we assume we got an OSDMap back
                            OSDMap r       = Util.GetOSDMap(response);
                            bool   success = r["success"].AsBoolean();
                            reason = r["reason"].AsString();
                            return(success);
                        }
                        catch (NullReferenceException e)
                        {
                            MainConsole.Instance.InfoFormat("[USER AGENT CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", e.Message);

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

                            return(false);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                MainConsole.Instance.InfoFormat("[USER AGENT CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
                reason = "Destination did not reply";
                return(false);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(true);
        }
        public bool DoHelloNeighbourCall(GridRegion region, RegionInfo thisRegion)
        {
            string uri = region.ServerURI + "region/" + thisRegion.RegionID + "/";
//            m_log.Debug("   >>> DoHelloNeighbourCall <<< " + uri);

            WebRequest helloNeighbourRequest;

            try
            {
                ServicePointManagerTimeoutSupport.ResetHosts();
                helloNeighbourRequest = WebRequest.Create(uri);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Unable to parse uri {0} to send HelloNeighbour from {1} to {2}.  Exception {3} ",
                               uri, thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

            helloNeighbourRequest.Method      = "POST";
            helloNeighbourRequest.ContentType = "application/json";
            helloNeighbourRequest.Timeout     = 10000;

            // Fill it in
            OSDMap args = null;

            try
            {
                args = thisRegion.PackRegionInfoData();
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: PackRegionInfoData failed for HelloNeighbour from {0} to {1}.  Exception {2} ",
                               thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

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

            string strBuffer = "";

            byte[] buffer = new byte[1];

            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                buffer    = Util.UTF8NoBomEncoding.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Exception thrown on serialization of HelloNeighbour from {0} to {1}.  Exception {2} ",
                               thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

            Stream os = null;

            try
            {                                                        // send the Post
                helloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
                os = helloNeighbourRequest.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);               //Send it
                //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Unable to send HelloNeighbour from {0} to {1} (uri {2}).  Exception {3} ",
                               thisRegion.RegionName, region.RegionName, uri, e.Message), e);

                return(false);
            }
            finally
            {
                if (os != null)
                {
                    os.Dispose();
                }
            }

            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");

            try
            {
                using (WebResponse webResponse = helloNeighbourRequest.GetResponse())
                {
                    if (webResponse == null)
                    {
                        m_log.DebugFormat(
                            "[NEIGHBOUR SERVICES CONNECTOR]: Null reply on DoHelloNeighbourCall post from {0} to {1}",
                            thisRegion.RegionName, region.RegionName);
                    }

                    using (Stream s = webResponse.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(s))
                        {
                            //reply = sr.ReadToEnd().Trim();
                            sr.ReadToEnd().Trim();
                            //m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Exception on reply of DoHelloNeighbourCall from {0} back to {1}.  Exception {2} ",
                               region.RegionName, thisRegion.RegionName, e.Message), e);

                return(false);
            }

            return(true);
        }
Exemple #11
0
        public string RegisterRegion(GridRegion regionInfo, UUID oldSessionID, out UUID SessionID,
                                     out List <GridRegion> neighbors)
        {
            neighbors = new List <GridRegion>();
            SessionID = UUID.Zero;
            // Generate and upload our map tile in PNG format to the SimianGrid AddMapTile service
            IScene scene;

            if (m_scenes.TryGetValue(regionInfo.RegionID, out scene))
            {
                UploadMapTile(scene);
            }
            else
            {
                MainConsole.Instance.Warn("Registering region " + regionInfo.RegionName + " (" + regionInfo.RegionID +
                                          ") that we are not tracking");
            }

            Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
            Vector3d maxPosition = minPosition + new Vector3d(Constants.RegionSize, Constants.RegionSize, 4096.0);

            string httpAddress = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort + "/";

            OSDMap extraData = new OSDMap
            {
                { "ServerURI", OSD.FromString(regionInfo.ServerURI) },
                {
                    "InternalAddress",
                    OSD.FromString(regionInfo.InternalEndPoint.Address.ToString())
                },
                { "InternalPort", OSD.FromInteger(regionInfo.InternalEndPoint.Port) },
                {
                    "ExternalAddress",
                    OSD.FromString(regionInfo.ExternalEndPoint.Address.ToString())
                },
                { "ExternalPort", OSD.FromInteger(regionInfo.ExternalEndPoint.Port) },
                { "MapTexture", OSD.FromUUID(regionInfo.TerrainMapImage) },
                { "Access", OSD.FromInteger(regionInfo.Access) },
                { "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
                { "Token", OSD.FromString(regionInfo.AuthToken) }
            };

            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "AddScene" },
                { "SceneID", regionInfo.RegionID.ToString() },
                { "Name", regionInfo.RegionName },
                { "MinPosition", minPosition.ToString() },
                { "MaxPosition", maxPosition.ToString() },
                { "Address", httpAddress },
                { "Enabled", "1" },
                { "ExtraData", OSDParser.SerializeJsonString(extraData) }
            };

            OSDMap response = WebUtils.PostToService(m_serverUrl, requestArgs);

            if (response["Success"].AsBoolean())
            {
                return(String.Empty);
            }
            else
            {
                return("Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString());
            }
        }
Exemple #12
0
 private byte[] Return(OSDMap result)
 {
     //m_log.DebugFormat("[AuroraDataServerPostHandler]: resp string: {0}", xmlString);
     return(Util.UTF8.GetBytes(OSDParser.SerializeJsonString(result)));
 }
        /// <summary>
        ///     PUT JSON-encoded data to a web service that returns LLSD or
        ///     JSON data
        /// </summary>
        public static string PutToService(string url, OSDMap data)
        {
            byte[] buffer = data != null?Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data, true)) : null;

            return(Encoding.UTF8.GetString(ServiceOSDRequest(url, buffer, "PUT", m_defaultTimeout)));
        }
Exemple #14
0
        private byte[] ProcessCreateAccount(OSDMap map)
        {
            bool   Verified     = false;
            string Name         = map["Name"].AsString();
            string PasswordHash = map["PasswordHash"].AsString();
            //string PasswordSalt = map["PasswordSalt"].AsString();
            string HomeRegion    = map["HomeRegion"].AsString();
            string Email         = map["Email"].AsString();
            string AvatarArchive = map["AvatarArchive"].AsString();



            IUserAccountService accountService = m_registry.RequestModuleInterface <IUserAccountService>();

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

            if (!PasswordHash.StartsWith("$1$"))
            {
                PasswordHash = "$1$" + Util.Md5Hash(PasswordHash);
            }
            PasswordHash = PasswordHash.Remove(0, 3); //remove $1$

            accountService.CreateUser(Name, PasswordHash, Email);
            UserAccount       user             = accountService.GetUserAccount(UUID.Zero, Name);
            IAgentInfoService agentInfoService = m_registry.RequestModuleInterface <IAgentInfoService> ();
            IGridService      gridService      = m_registry.RequestModuleInterface <IGridService> ();

            if (agentInfoService != null && gridService != null)
            {
                GridRegion r = gridService.GetRegionByName(UUID.Zero, HomeRegion);
                agentInfoService.SetHomePosition(user.PrincipalID.ToString(), r.RegionID, new Vector3(r.RegionSizeX / 2, r.RegionSizeY / 2, 20), Vector3.Zero);
            }

            Verified = user != null;
            UUID userID = UUID.Zero;

            if (Verified)
            {
                // could not find a way to save this data here.

                /*DateTime RLDOB = map["RLDOB"].AsDate();
                 * string RLFirstName = map["RLFisrtName"].AsString();
                 * string RLLastName = map["RLLastName"].AsString();
                 * string RLAdress = map["RLAdress"].AsString();
                 * string RLCity = map["RLCity"].AsString();
                 * string RLZip = map["RLZip"].AsString();
                 * string RLCountry = map["RLCountry"].AsString();
                 * string RLIP = map["RLIP"].AsString();*/
                // could not find a way to save this data here.


                userID         = user.PrincipalID;
                user.UserLevel = -1;

                accountService.StoreUserAccount(user);

                IProfileConnector profileData = DataManager.RequestPlugin <IProfileConnector>();
                IUserProfileInfo  profile     = profileData.GetUserProfile(user.PrincipalID);
                if (profile == null)
                {
                    profileData.CreateNewProfile(user.PrincipalID);
                    profile = profileData.GetUserProfile(user.PrincipalID);
                }
                if (AvatarArchive.Length > 0)
                {
                    profile.AArchiveName = AvatarArchive + ".database";
                }

                profile.IsNewUser = true;
                profileData.UpdateUserProfile(profile);
            }

            OSDMap resp = new OSDMap();

            resp["Verified"] = OSD.FromBoolean(Verified);
            resp["UUID"]     = OSD.FromUUID(userID);
            string       xmlString = OSDParser.SerializeJsonString(resp);
            UTF8Encoding encoding  = new UTF8Encoding();

            return(encoding.GetBytes(xmlString));
        }
        /// <summary>
        /// Add a new item to the user's inventory
        /// </summary>
        /// <param name="item"></param>
        /// <returns>true if the item was successfully added</returns>
        public bool AddItem(InventoryItemBase item)
        {
            // A folder of UUID.Zero means we need to find the most appropriate home for this item
            if (item.Folder == UUID.Zero)
            {
                InventoryFolderBase folder = null;
                if (Enum.IsDefined(typeof(FolderType), (sbyte)item.AssetType))
                {
                    folder = GetFolderForType(item.Owner, (FolderType)item.AssetType);
                }
                if (folder != null && folder.ID != UUID.Zero)
                {
                    item.Folder = folder.ID;
                }
                else
                {
                    item.Folder = item.Owner; // Root folder
                }
            }

            if ((AssetType)item.AssetType == AssetType.Gesture)
            {
                UpdateGesture(item.Owner, item.ID, item.Flags == 1);
            }

            if (item.BasePermissions == 0)
            {
                m_log.WarnFormat("[SIMIAN INVENTORY CONNECTOR]: Adding inventory item {0} ({1}) with no base permissions", item.Name, item.ID);
            }

            OSDMap permissions = new OSDMap
            {
                { "BaseMask", OSD.FromInteger(item.BasePermissions) },
                { "EveryoneMask", OSD.FromInteger(item.EveryOnePermissions) },
                { "GroupMask", OSD.FromInteger(item.GroupPermissions) },
                { "NextOwnerMask", OSD.FromInteger(item.NextPermissions) },
                { "OwnerMask", OSD.FromInteger(item.CurrentPermissions) }
            };

            OSDMap extraData = new OSDMap()
            {
                { "Flags", OSD.FromInteger(item.Flags) },
                { "GroupID", OSD.FromUUID(item.GroupID) },
                { "GroupOwned", OSD.FromBoolean(item.GroupOwned) },
                { "SalePrice", OSD.FromInteger(item.SalePrice) },
                { "SaleType", OSD.FromInteger(item.SaleType) },
                { "Permissions", permissions }
            };

            // Add different asset type only if it differs from inventory type
            // (needed for links)
            string invContentType   = SLUtil.SLInvTypeToContentType(item.InvType);
            string assetContentType = SLUtil.SLAssetTypeToContentType(item.AssetType);

            if (invContentType != assetContentType)
            {
                extraData["LinkedItemType"] = OSD.FromString(assetContentType);
            }

            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "AddInventoryItem" },
                { "ItemID", item.ID.ToString() },
                { "AssetID", item.AssetID.ToString() },
                { "ParentID", item.Folder.ToString() },
                { "OwnerID", item.Owner.ToString() },
                { "Name", item.Name },
                { "Description", item.Description },
                { "CreatorID", item.CreatorId },
                { "CreatorData", item.CreatorData },
                { "ContentType", invContentType },
                { "ExtraData", OSDParser.SerializeJsonString(extraData) }
            };

            OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
            bool   success  = response["Success"].AsBoolean();

            if (!success)
            {
                m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error creating item " + item.Name + " for " + item.Owner + ": " +
                           response["Message"].AsString());
            }

            return(success);
        }
Exemple #16
0
        public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed)
        {
            int reqnum = m_requestNumber++;
            // m_log.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);

            string errorMessage = "unknown error";
            int    tickstart    = Util.EnvironmentTickCount();
            int    tickdata     = 0;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method    = method;
                request.Timeout   = timeout;
                request.KeepAlive = false;
                request.MaximumAutomaticRedirections = 10;
                request.ReadWriteTimeout             = timeout / 4;
                request.Headers[OSHeaderRequestID]   = reqnum.ToString();

                // If there is some input, write it into the request
                if (data != null)
                {
                    string strBuffer = OSDParser.SerializeJsonString(data);
                    byte[] buffer    = System.Text.Encoding.UTF8.GetBytes(strBuffer);

                    if (compressed)
                    {
                        request.ContentType = "application/x-gzip";
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress))
                            {
                                comp.Write(buffer, 0, buffer.Length);
                                // We need to close the gzip stream before we write it anywhere
                                // because apparently something important related to gzip compression
                                // gets written on the strteam upon Dispose()
                            }
                            byte[] buf = ms.ToArray();
                            request.ContentLength = buf.Length;   //Count bytes to send
                            using (Stream requestStream = request.GetRequestStream())
                                requestStream.Write(buf, 0, (int)buf.Length);
                        }
                    }
                    else
                    {
                        request.ContentType   = "application/json";
                        request.ContentLength = buffer.Length;              //Count bytes to send
                        using (Stream requestStream = request.GetRequestStream())
                            requestStream.Write(buffer, 0, buffer.Length);  //Send it
                    }
                }

                // capture how much time was spent writing, this may seem silly
                // but with the number concurrent requests, this often blocks
                tickdata = Util.EnvironmentTickCountSubtract(tickstart);

                using (WebResponse response = request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        string responseStr = null;
                        responseStr = responseStream.GetStreamString();
                        // m_log.DebugFormat("[WEB UTIL]: <{0}> response is <{1}>",reqnum,responseStr);
                        return(CanonicalizeResults(responseStr));
                    }
                }
            }
            catch (WebException we)
            {
                errorMessage = we.Message;
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse webResponse = (HttpWebResponse)we.Response;
                    errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription);
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            finally
            {
                // This just dumps a warning for any operation that takes more than 100 ms
                int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
                if (tickdiff > LongCallTime)
                {
                    m_log.DebugFormat("[WEB UTIL]: osd request <{0}> (URI:{1}, METHOD:{2}) took {3}ms overall, {4}ms writing",
                                      reqnum, url, method, tickdiff, tickdata);
                }
            }

            m_log.DebugFormat("[WEB UTIL]: <{0}> osd request for {1}, method {2} FAILED: {3}", reqnum, url, method, errorMessage);
            return(ErrorResponseMap(errorMessage));
        }
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

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

            // retrieve the input arguments
            int        x = 0, y = 0;
            UUID       uuid                  = UUID.Zero;
            string     regionname            = string.Empty;
            string     gatekeeper_host       = string.Empty;
            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
            {
                m_log.WarnFormat("  -- request didn't have destination_x");
            }
            if (args.ContainsKey("destination_y") && args["destination_y"] != null)
            {
                Int32.TryParse(args["destination_y"].AsString(), out y);
            }
            else
            {
                m_log.WarnFormat("  -- request didn't have destination_y");
            }
            if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
            {
                UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
            }
            if (args.ContainsKey("destination_name") && args["destination_name"] != null)
            {
                regionname = args["destination_name"].ToString();
            }

            if (args.ContainsKey("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
                    {
                        m_log.WarnFormat("[HOME AGENT HANDLER]: Unauthorized machine {0} tried to set client ip to {1}", callerIP, ip_str);
                    }
                }
                catch
                {
                    m_log.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)
            {
                m_log.InfoFormat("[HOME AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

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

            bool result = m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, 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);
        }
        /// <summary>
        /// Sends json-rpc request with a serializable type.
        /// </summary>
        /// <returns>
        /// OSD Map.
        /// </returns>
        /// <param name='parameters'>
        /// Serializable type .
        /// </param>
        /// <param name='method'>
        /// Json-rpc method to call.
        /// </param>
        /// <param name='uri'>
        /// URI of json-rpc service.
        /// </param>
        /// <param name='jsonId'>
        /// Id for our call.
        /// </param>
        public bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
        {
            if (jsonId == null)
            {
                throw new ArgumentNullException("jsonId");
            }
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (string.IsNullOrWhiteSpace(uri))
            {
                return(false);
            }

            OSDMap request = new OSDMap();

            request.Add("jsonrpc", OSD.FromString("2.0"));
            request.Add("id", OSD.FromString(jsonId));
            request.Add("method", OSD.FromString(method));
            request.Add("params", OSD.SerializeMembers(parameters));

            OSDMap response;

            try
            {
                response = WebUtil.PostToService(uri, request, 10000, true);
            }
            catch (Exception e)
            {
                m_log.Debug(string.Format("JsonRpc request '{0}' to {1} failed", method, uri), e);
                return(false);
            }

            OSD osdtmp;

            if (!response.TryGetValue("_Result", out osdtmp) || !(osdtmp is OSDMap))
            {
                m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an invalid response: {2}",
                                  method, uri, OSDParser.SerializeJsonString(response));
                return(false);
            }

            response = osdtmp as OSDMap;
            if (response.TryGetValue("error", out osdtmp))
            {
                m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an error: {2}",
                                  method, uri, OSDParser.SerializeJsonString(osdtmp));
                return(false);
            }

            if (!response.TryGetValue("result", out osdtmp) || !(osdtmp is OSDMap))
            {
                m_log.DebugFormat("JsonRpc request '{0}' to {1} returned an invalid response: {2}",
                                  method, uri, OSDParser.SerializeJsonString(response));
                return(false);
            }

            OSD.DeserializeMembers(ref parameters, (OSDMap)osdtmp);
            return(true);
        }
        protected void DoAgentPut(Hashtable request, Hashtable responsedata)
        {
            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;

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

            GridRegion destination = new GridRegion
            {
                RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname
            };

            string messageType;

            if (args["message_type"] != null)
            {
                messageType = args["message_type"].AsString();
            }
            else
            {
                MainConsole.Instance.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
                messageType = "AgentData";
            }

            bool result = true;

            if ("AgentData".Equals(messageType))
            {
                AgentData agent = new AgentData();
                try
                {
                    agent.Unpack(args);
                }
                catch (Exception ex)
                {
                    MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex);
                    responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                    responsedata["str_response_string"] = "Bad request";
                    return;
                }

                //agent.Dump();
                // This is one of the meanings of PUT agent
                result = UpdateAgent(destination, agent);
            }
            else if ("AgentPosition".Equals(messageType))
            {
                AgentPosition agent = new AgentPosition();
                try
                {
                    agent.Unpack(args);
                }
                catch (Exception ex)
                {
                    MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex);
                    return;
                }
                //agent.Dump();
                // This is one of the meanings of PUT agent
                result = m_SimulationService.UpdateAgent(destination, agent);
            }
            OSDMap resp = new OSDMap();

            resp["Updated"] = result;
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
        public byte[] RenderMaterialsPostCap(string path, Stream request,
                                             OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            MainConsole.Instance.Debug("[MaterialsDemoModule]: POST cap handler");

            OSDMap req  = (OSDMap)OSDParser.DeserializeLLSDXml(request);
            OSDMap resp = new OSDMap();

            OSDMap materialsFromViewer = null;

            OSDArray respArr = new OSDArray();

            if (req.ContainsKey("Zipped"))
            {
                OSD osd = null;

                byte[] inBytes = req["Zipped"].AsBinary();

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null)
                    {
                        if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
                        {
                            foreach (OSD elem in (OSDArray)osd)
                            {
                                try
                                {
                                    UUID      id            = new UUID(elem.AsBinary(), 0);
                                    AssetBase materialAsset = null;
                                    if (m_knownMaterials.ContainsKey(id))
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for known material ID: " + id.ToString());
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"] = elem.AsBinary();

                                        matMap["Material"] = m_knownMaterials[id];
                                        respArr.Add(matMap);
                                    }
                                    else if ((materialAsset = m_scene.AssetService.Get(id.ToString())) != null)
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for stored material ID: " + id.ToString());
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"] = elem.AsBinary();

                                        matMap["Material"] = (OSDMap)OSDParser.DeserializeJson(
                                            Encoding.UTF8.GetString(materialAsset.Data));
                                        respArr.Add(matMap);
                                    }
                                    else
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for UNKNOWN material ID: " + id.ToString());
                                    }
                                }
                                catch (Exception)
                                {
                                    // report something here?
                                    continue;
                                }
                            }
                        }
                        else if (osd is OSDMap) // request to assign a material
                        {
                            materialsFromViewer = osd as OSDMap;

                            if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
                            {
                                OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
                                if (matsOsd is OSDArray)
                                {
                                    OSDArray matsArr = matsOsd as OSDArray;

                                    try
                                    {
                                        foreach (OSDMap matsMap in matsArr)
                                        {
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: processing matsMap: " + OSDParser.SerializeJsonString(matsMap));

                                            uint matLocalID = 0;
                                            try { matLocalID = matsMap["ID"].AsUInteger(); }
                                            catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"ID\" from matsMap: " + e.Message); }
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: matLocalId: " + matLocalID.ToString());


                                            OSDMap mat = null;
                                            try { mat = matsMap["Material"] as OSDMap; }
                                            catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"Material\" from matsMap: " + e.Message); }
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: mat: " + OSDParser.SerializeJsonString(mat));

                                            UUID id = HashOsd(mat);
                                            m_knownMaterials[id] = mat;


                                            var sop = m_scene.GetSceneObjectPart(matLocalID);
                                            if (sop == null)
                                            {
                                                MainConsole.Instance.Debug("[MaterialsDemoModule]: null SOP for localId: " + matLocalID.ToString());
                                            }
                                            else
                                            {
                                                //var te = sop.Shape.Textures;
                                                var te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);

                                                if (te == null)
                                                {
                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: null TextureEntry for localId: " + matLocalID.ToString());
                                                }
                                                else
                                                {
                                                    int face = -1;

                                                    if (matsMap.ContainsKey("Face"))
                                                    {
                                                        face = matsMap["Face"].AsInteger();
                                                        if (te.FaceTextures == null) // && face == 0)
                                                        {
                                                            if (te.DefaultTexture == null)
                                                            {
                                                                MainConsole.Instance.Debug("[MaterialsDemoModule]: te.DefaultTexture is null");
                                                            }
                                                            else
                                                            {
//## FixMe ##
// comparison always results in 'False'                                   if (te.DefaultTexture.MaterialID == null)
//                                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: te.DefaultTexture.MaterialID is null");
//                                                                else
//                                                                {
                                                                te.DefaultTexture.MaterialID = id;
//                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (te.FaceTextures.Length >= face - 1)
                                                            {
                                                                if (te.FaceTextures[face] == null)
                                                                {
                                                                    te.DefaultTexture.MaterialID = id;
                                                                }
                                                                else
                                                                {
                                                                    te.FaceTextures[face].MaterialID = id;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (te.DefaultTexture != null)
                                                        {
                                                            te.DefaultTexture.MaterialID = id;
                                                        }
                                                    }

                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: setting material ID for face " + face.ToString() + " to " + id.ToString());

                                                    //we cant use sop.UpdateTextureEntry(te); because it filters so do it manually

                                                    if (sop.ParentEntity != null)
                                                    {
                                                        sop.Shape.TextureEntry = te.GetBytes();
                                                        sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                                        sop.ParentEntity.HasGroupChanged = true;

                                                        sop.ScheduleUpdate(PrimUpdateFlags.FullUpdate);

                                                        AssetBase asset = new AssetBase(id, "RenderMaterial",
                                                                                        AssetType.Texture, sop.OwnerID)
                                                        {
                                                            Data = Encoding.UTF8.GetBytes(
                                                                OSDParser.SerializeJsonString(mat))
                                                        };
                                                        m_scene.AssetService.Store(asset);

                                                        StoreMaterialsForPart(sop);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        MainConsole.Instance.Warn("[MaterialsDemoModule]: exception processing received material: " + e.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MainConsole.Instance.Warn("[MaterialsDemoModule]: exception decoding zipped CAP payload: " + e.ToString());
                    //return "";
                }
                MainConsole.Instance.Debug("[MaterialsDemoModule]: knownMaterials.Count: " + m_knownMaterials.Count.ToString());
            }


            resp["Zipped"] = ZCompressOSD(respArr, false);
            string response = OSDParser.SerializeLLSDXmlString(resp);

            //MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request: " + request);
            MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            MainConsole.Instance.Debug("[MaterialsDemoModule]: cap response: " + response);
            return(OSDParser.SerializeLLSDBinary(resp));
        }
        protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID)
        {
            if (m_SimulationService == null)
            {
                m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless.");
                responsedata["content_type"]        = "application/json";
                responsedata["int_response_code"]   = HttpStatusCode.NotImplemented;
                responsedata["str_response_string"] = string.Empty;

                return;
            }

            // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]);
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            bool viaTeleport = true;

            if (args.ContainsKey("viaTeleport"))
            {
                viaTeleport = args["viaTeleport"].AsBoolean();
            }

            Vector3 position = Vector3.Zero;

            if (args.ContainsKey("position"))
            {
                position = Vector3.Parse(args["position"].AsString());
            }

            string agentHomeURI = null;

            if (args.ContainsKey("agent_home_uri"))
            {
                agentHomeURI = args["agent_home_uri"].AsString();
            }

            string theirVersion = string.Empty;

            if (args.ContainsKey("my_version"))
            {
                theirVersion = args["my_version"].AsString();
            }

            List <UUID> features = new List <UUID>();

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

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

            GridRegion destination = new GridRegion();

            destination.RegionID = regionID;

            string reason;
            string version;
            bool   result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, theirVersion, features, out version, out reason);

            responsedata["int_response_code"] = HttpStatusCode.OK;

            OSDMap resp = new OSDMap(3);

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

            OSDArray featuresWanted = new OSDArray();

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

            resp["features"] = featuresWanted;

            // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map!
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);

//            Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]);
        }
Exemple #22
0
        protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID)
        {
            Culture.SetCurrentCulture();

            EntityTransferContext ctx = new EntityTransferContext();

            if (m_SimulationService == null)
            {
                m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless.");
                responsedata["content_type"]        = "application/json";
                responsedata["int_response_code"]   = HttpStatusCode.NotImplemented;
                responsedata["str_response_string"] = string.Empty;

                return;
            }

            // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]);
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            bool viaTeleport = true;

            if (args.ContainsKey("viaTeleport"))
            {
                viaTeleport = args["viaTeleport"].AsBoolean();
            }

            Vector3 position = Vector3.Zero;

            if (args.ContainsKey("position"))
            {
                position = Vector3.Parse(args["position"].AsString());
            }

            string agentHomeURI = null;

            if (args.ContainsKey("agent_home_uri"))
            {
                agentHomeURI = args["agent_home_uri"].AsString();
            }

            // Decode the legacy (string) version and extract the number
            float theirVersion = 0f;

            if (args.ContainsKey("my_version"))
            {
                string   theirVersionStr = args["my_version"].AsString();
                string[] parts           = theirVersionStr.Split(new char[] { '/' });
                if (parts.Length > 1)
                {
                    theirVersion = float.Parse(parts[1], Culture.FormatProvider);
                }
            }

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

            // Decode the new versioning data
            float minVersionRequired = 0f;
            float maxVersionRequired = 0f;
            float minVersionProvided = 0f;
            float maxVersionProvided = 0f;

            if (args.ContainsKey("simulation_service_supported_min"))
            {
                minVersionProvided = (float)args["simulation_service_supported_min"].AsReal();
            }
            if (args.ContainsKey("simulation_service_supported_max"))
            {
                maxVersionProvided = (float)args["simulation_service_supported_max"].AsReal();
            }

            if (args.ContainsKey("simulation_service_accepted_min"))
            {
                minVersionRequired = (float)args["simulation_service_accepted_min"].AsReal();
            }
            if (args.ContainsKey("simulation_service_accepted_max"))
            {
                maxVersionRequired = (float)args["simulation_service_accepted_max"].AsReal();
            }

            responsedata["int_response_code"] = HttpStatusCode.OK;
            OSDMap resp = new OSDMap(3);

            float version = 0f;

            float outboundVersion = 0f;
            float inboundVersion  = 0f;

            if (minVersionProvided == 0f) // string version or older
            {
                // If there is no version in the packet at all we're looking at 0.6 or
                // even more ancient. Refuse it.
                if (theirVersion == 0f)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString("Your region is running a old version of opensim no longer supported. Consider updating it");
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }

                version = theirVersion;

                if (version < VersionInfo.SimulationServiceVersionAcceptedMin ||
                    version > VersionInfo.SimulationServiceVersionAcceptedMax)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString(String.Format("Your region protocol version is {0} and we accept only {1} - {2}. No version overlap.", theirVersion, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax));
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }
            }
            else
            {
                // Test for no overlap
                if (minVersionProvided > VersionInfo.SimulationServiceVersionAcceptedMax ||
                    maxVersionProvided < VersionInfo.SimulationServiceVersionAcceptedMin)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString(String.Format("Your region provide protocol versions {0} - {1} and we accept only {2} - {3}. No version overlap.", minVersionProvided, maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax));
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }
                if (minVersionRequired > VersionInfo.SimulationServiceVersionSupportedMax ||
                    maxVersionRequired < VersionInfo.SimulationServiceVersionSupportedMin)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString(String.Format("You require region protocol versions {0} - {1} and we provide only {2} - {3}. No version overlap.", minVersionRequired, maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax));
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }

                // Determine versions to use
                // This is intentionally inverted. Inbound and Outbound refer to the direction of the transfer.
                // Therefore outbound means from the sender to the receier and inbound means from the receiver to the sender.
                // So outbound is what we will accept and inbound is what we will send. Confused yet?
                outboundVersion = Math.Min(maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMax);
                inboundVersion  = Math.Min(maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMax);
            }

            List <UUID> features = new List <UUID>();

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

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

            GridRegion destination = new GridRegion();

            destination.RegionID = regionID;

            string reason;

            // We're sending the version numbers down to the local connector to do the varregion check.
            ctx.InboundVersion  = inboundVersion;
            ctx.OutboundVersion = outboundVersion;
            if (minVersionProvided == 0f)
            {
                ctx.InboundVersion  = version;
                ctx.OutboundVersion = version;
            }

            bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason);

            m_log.DebugFormat("[AGENT HANDLER]: QueryAccess returned {0} ({1}). Version={2}, {3}/{4}",
                              result, reason, version, inboundVersion, outboundVersion);

            resp["success"] = OSD.FromBoolean(result);
            resp["reason"]  = OSD.FromString(reason);
            string legacyVersion = String.Format(Culture.FormatProvider, "SIMULATION/{0}", version);

            resp["version"] = OSD.FromString(legacyVersion);
            resp["negotiated_inbound_version"]  = OSD.FromReal(inboundVersion);
            resp["negotiated_outbound_version"] = OSD.FromReal(outboundVersion);

            OSDArray featuresWanted = new OSDArray();

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

            resp["features"] = featuresWanted;

            // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map!
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);

//            Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]);
        }
Exemple #23
0
        private int GetFaceColor(Primitive.TextureEntryFace face)
        {
            int    color;
            Color4 ctmp = Color4.White;

            if (face.TextureID == UUID.Zero)
            {
                return(warp_Color.White);
            }

            if (!m_colors.TryGetValue(face.TextureID, out color))
            {
                bool fetched = false;

                // Attempt to fetch the texture metadata
                string    cacheName = "MAPCLR" + face.TextureID.ToString();
                AssetBase metadata  = m_scene.AssetService.GetCached(cacheName);
                if (metadata != null)
                {
                    OSDMap map = null;
                    try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }

                    if (map != null)
                    {
                        ctmp    = map["X-RGBA"].AsColor4();
                        fetched = true;
                    }
                }

                if (!fetched)
                {
                    // Fetch the texture, decode and get the average color,
                    // then save it to a temporary metadata asset
                    AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
                    if (textureAsset != null)
                    {
                        int width, height;
                        ctmp = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);

                        OSDMap data = new OSDMap {
                            { "X-RGBA", OSD.FromColor4(ctmp) }
                        };
                        metadata = new AssetBase
                        {
                            Data        = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
                            Description = "Metadata for texture color" + face.TextureID.ToString(),
                            Flags       = AssetFlags.Collectable,
                            FullID      = UUID.Zero,
                            ID          = cacheName,
                            Local       = true,
                            Temporary   = true,
                            Name        = String.Empty,
                            Type        = (sbyte)AssetType.Unknown
                        };
                        m_scene.AssetService.Store(metadata);
                    }
                    else
                    {
                        ctmp = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
                    }
                }
                color = ConvertColor(ctmp);
                m_colors[face.TextureID] = color;
            }

            return(color);
        }
Exemple #24
0
 public override string XReport(string uptime, string version)
 {
     return(OSDParser.SerializeJsonString(OReport(uptime, version)));
 }
        public bool DoHelloNeighbourCall(GridRegion region, RegionInfo thisRegion)
        {
            string uri = region.ServerURI + "region/" + thisRegion.RegionID + "/";
            //m_log.Debug("   >>> DoHelloNeighbourCall <<< " + uri);

            WebRequest HelloNeighbourRequest = WebRequest.Create(uri);

            HelloNeighbourRequest.Method      = "POST";
            HelloNeighbourRequest.ContentType = "application/json";
            HelloNeighbourRequest.Timeout     = 10000;

            // Fill it in
            OSDMap args = null;

            try
            {
                args = thisRegion.PackRegionInfoData();
            }
            catch (Exception e)
            {
                m_log.Debug("[REST COMMS]: PackRegionInfoData failed with exception: " + e.Message);
                return(false);
            }
            // Add the regionhandle of the destination region
            args["destination_handle"] = OSD.FromString(region.RegionHandle.ToString());

            string strBuffer = "";

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

            Stream os = null;

            try
            {                                                        // send the Post
                HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
                os = HelloNeighbourRequest.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);               //Send it
                //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[REST COMMS]: Unable to send HelloNeighbour to {0}: {1}", region.RegionName, ex.Message);
                return(false);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");

            StreamReader sr = null;

            try
            {
                WebResponse webResponse = HelloNeighbourRequest.GetResponse();
                if (webResponse == null)
                {
                    m_log.Info("[REST COMMS]: Null reply on DoHelloNeighbourCall post");
                }

                sr = new StreamReader(webResponse.GetResponseStream());
                //reply = sr.ReadToEnd().Trim();
                sr.ReadToEnd().Trim();
                //m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of DoHelloNeighbourCall {0}", ex.Message);
                return(false);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(true);
        }
Exemple #26
0
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

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

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

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

            GridRegion gatekeeper = new GridRegion();

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

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

            GridRegion destination = new GridRegion();

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

            AgentCircuitData aCircuit = new AgentCircuitData();

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

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

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

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

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
        public bool DoHelloNeighbourCall(GridRegion region, RegionInfo thisRegion)
        {
            string uri = region.ServerURI + "region/" + thisRegion.RegionID + "/";

            //m_log.Debug("   >>> DoHelloNeighbourCall <<< " + uri);

            byte[] buffer = null;
            try
            {
                OSDMap args = thisRegion.PackRegionInfoData();
                args["destination_handle"] = OSD.FromString(region.RegionHandle.ToString());
                buffer = Util.UTF8NoBomEncoding.GetBytes(OSDParser.SerializeJsonString(args));
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: PackRegionInfoData failed for HelloNeighbour from {0} to {1}.  Exception {2} ",
                               thisRegion.RegionName, region.RegionName, e.Message), e);
                return(false);
            }

            if (buffer == null || buffer.Length == 0)
            {
                return(false);
            }

            HttpWebRequest helloNeighbourRequest;

            try
            {
                helloNeighbourRequest = (HttpWebRequest)WebRequest.Create(uri);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Unable to parse uri {0} to send HelloNeighbour from {1} to {2}.  Exception {3} ",
                               uri, thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

            helloNeighbourRequest.Method      = "POST";
            helloNeighbourRequest.ContentType = "application/json";
            helloNeighbourRequest.Timeout     = 10000;

            try
            {
                helloNeighbourRequest.ContentLength = buffer.Length;
                using (var os = helloNeighbourRequest.GetRequestStream())
                    os.Write(buffer, 0, buffer.Length);
                buffer = null;
                //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
            }
            // catch (Exception e)
            catch
            {
                //m_log.WarnFormat(
                //    "[NEIGHBOUR SERVICE CONNCTOR]: Unable to send HelloNeighbour from {0} to {1}.  Exception {2}{3}",
                //    thisRegion.RegionName, region.RegionName, e.Message, e.StackTrace);

                return(false);
            }
            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");

            try
            {
                using (WebResponse webResponse = helloNeighbourRequest.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
                    {
                        sr.ReadToEnd(); // just try to read
                        //reply = sr.ReadToEnd().Trim();
                        //m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Exception on reply of DoHelloNeighbourCall from {0} back to {1}.  Exception {2} ",
                               region.RegionName, thisRegion.RegionName, e.Message), e);
            }
            return(false);
        }
        private void CreateItem(inventoryitems item)
        {
            ++m_counter;

            AssetType     assetType     = (item.assetType.HasValue) ? (AssetType)item.assetType.Value : AssetType.Unknown;
            InventoryType inventoryType = (item.invType.HasValue) ? (InventoryType)item.invType.Value : InventoryType.Unknown;
            UUID          groupID;

            UUID.TryParse(item.groupID, out groupID);

            string parentFolderID = item.parentFolderID;

            if (m_rewriteFolderIDs.ContainsKey(parentFolderID))
            {
                parentFolderID = m_rewriteFolderIDs[parentFolderID];
            }

            // Create this item
            OSDMap permissions = new OSDMap
            {
                { "BaseMask", OSD.FromInteger(item.inventoryBasePermissions) },
                { "EveryoneMask", OSD.FromInteger(item.inventoryEveryOnePermissions) },
                { "GroupMask", OSD.FromInteger(item.inventoryGroupPermissions) },
                { "NextOwnerMask", OSD.FromInteger(item.inventoryNextPermissions.HasValue ? item.inventoryNextPermissions.Value : item.inventoryBasePermissions) },
                { "OwnerMask", OSD.FromInteger(item.inventoryCurrentPermissions.HasValue ? item.inventoryCurrentPermissions.Value : item.inventoryBasePermissions) }
            };

            OSDMap extraData = new OSDMap()
            {
                { "Flags", OSD.FromInteger(item.flags) },
                { "GroupID", OSD.FromUUID(groupID) },
                { "GroupOwned", OSD.FromBoolean(item.groupOwned != 0) },
                { "SalePrice", OSD.FromInteger(item.salePrice) },
                { "SaleType", OSD.FromInteger(item.saleType) },
                { "Permissions", permissions }
            };

            // Add different asset type only if it differs from inventory type
            // (needed for links)
            string invContentType   = LLUtil.SLInvTypeToContentType((int)inventoryType);
            string assetContentType = LLUtil.SLAssetTypeToContentType((int)assetType);

            if (invContentType != assetContentType)
            {
                extraData["LinkedItemType"] = OSD.FromString(assetContentType);
            }

            string ownerID   = item.avatarID;
            string creatorID = item.creatorID;

            // Handle OpenSim profile anchors by rewriting non-UUID creatorIDs to the ownerID
            // More information on (OSPA) profile anchors @ http://opensimulator.org/wiki/OpenSim_Profile_Anchors
            UUID creatorUUID;

            if (!UUID.TryParse(creatorID, out creatorUUID))
            {
                creatorID = ownerID;
            }

            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "AddInventoryItem" },
                { "ItemID", item.inventoryID },
                { "AssetID", item.assetID },
                { "ParentID", parentFolderID },
                { "OwnerID", ownerID },
                { "Name", item.inventoryName },
                { "Description", item.inventoryDescription },
                { "CreatorID", creatorID },
                { "ContentType", invContentType },
                { "ExtraData", OSDParser.SerializeJsonString(extraData) }
            };

            OSDMap response = WebUtil.PostToService(m_inventoryUrl, requestArgs);
            bool   success  = response["Success"].AsBoolean();

            if (success)
            {
                // Gesture handling
                if (assetType == AssetType.Gesture)
                {
                    UpdateGesture(UUID.Parse(item.avatarID), UUID.Parse(item.inventoryID), item.flags == 1);
                }
            }
            else
            {
                Console.WriteLine("Error creating item " + item.inventoryName + " for " + item.avatarID + ": " + response["Message"].AsString());
            }
        }
        /// <summary>
        /// Sends json-rpc request with a serializable type.
        /// </summary>
        /// <returns>
        /// OSD Map.
        /// </returns>
        /// <param name='parameters'>
        /// Serializable type .
        /// </param>
        /// <param name='method'>
        /// Json-rpc method to call.
        /// </param>
        /// <param name='uri'>
        /// URI of json-rpc service.
        /// </param>
        /// <param name='jsonId'>
        /// Id for our call.
        /// </param>
        public bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
        {
            if (jsonId == null)
            {
                throw new ArgumentNullException("jsonId");
            }
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            OSDMap request = new OSDMap();

            request.Add("jsonrpc", OSD.FromString("2.0"));
            request.Add("id", OSD.FromString(jsonId));
            request.Add("method", OSD.FromString(method));
            request.Add("params", OSD.SerializeMembers(parameters));

            OSDMap response;

            try
            {
                response = WebUtil.PostToService(uri, request, 10000, true);
            }
            catch (Exception e)
            {
                m_log.Debug(string.Format("JsonRpc request '{0}' failed", method), e);
                return(false);
            }

            if (!response.ContainsKey("_Result"))
            {
                m_log.DebugFormat("JsonRpc request '{0}' returned an invalid response: {1}",
                                  method, OSDParser.SerializeJsonString(response));
                return(false);
            }
            response = (OSDMap)response["_Result"];

            OSD data;

            if (response.ContainsKey("error"))
            {
                data = response["error"];
                m_log.DebugFormat("JsonRpc request '{0}' returned an error: {1}",
                                  method, OSDParser.SerializeJsonString(data));
                return(false);
            }

            if (!response.ContainsKey("result"))
            {
                m_log.DebugFormat("JsonRpc request '{0}' returned an invalid response: {1}",
                                  method, OSDParser.SerializeJsonString(response));
                return(false);
            }

            data = response["result"];
            OSD.DeserializeMembers(ref parameters, (OSDMap)data);

            return(true);
        }
Exemple #30
0
        protected void DoAgentPost(OSDMap args, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID)
        {
            OSD tmpOSD;
            EntityTransferContext ctx = new EntityTransferContext();

            if (args.TryGetValue("context", out tmpOSD) && tmpOSD is OSDMap)
            {
                ctx.Unpack((OSDMap)tmpOSD);
            }

            AgentDestinationData data = CreateAgentDestinationData();

            UnpackData(args, data);

            GridRegion destination = new GridRegion();

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

            GridRegion gatekeeper = ExtractGatekeeper(data);

            AgentCircuitData aCircuit = new AgentCircuitData();

            try
            {
                aCircuit.UnpackAgentCircuitData(args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                httpResponse.RawBuffer  = Util.UTF8.GetBytes("false");
                return;
            }

            GridRegion source = null;

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

                if (args.TryGetValue("source_server_uri", out tmpOSD))
                {
                    source.RawServerURI = tmpOSD.AsString();
                }
                else
                {
                    source.RawServerURI = null;
                }
            }

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

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

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

            httpResponse.StatusCode = (int)HttpStatusCode.OK;
            httpResponse.RawBuffer  = Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
            httpResponse.KeepAlive  = (data.flags & (uint)(TeleportFlags.ViaLogin | TeleportFlags.ViaHGLogin)) != (uint)TeleportFlags.ViaLogin;
        }