private byte[] SetEnvironment(Stream request, UUID agentID)
        {
            IScenePresence SP = m_scene.GetScenePresence(agentID);
            if (SP == null)
                return new byte[0]; //They don't exist
            bool success = false;
            string fail_reason = "";
            if (SP.Scene.Permissions.CanIssueEstateCommand(agentID, false))
            {
                m_info = OSDParser.DeserializeLLSDXml(request);
                IGenericsConnector gc = DataManager.DataManager.RequestPlugin<IGenericsConnector>();
                if (gc != null)
                    gc.AddGeneric(m_scene.RegionInfo.RegionID, "EnvironmentSettings", "",
                                  (new DatabaseWrapper { Info = m_info }).ToOSD());
                success = true;
                SP.ControllingClient.SendAlertMessage("Windlight Settings saved successfully");
            }
            else
            {
                fail_reason = "You don't have permissions to set the windlight settings here.";
                SP.ControllingClient.SendAlertMessage(
                    "You don't have the correct permissions to set the Windlight Settings");
            }
            OSDMap result = new OSDMap()
            {
                new KeyValuePair<string, OSD>("success", success),
                new KeyValuePair<string, OSD>("regionID", SP.Scene.RegionInfo.RegionID)
            };
            if (fail_reason != "")
                result["fail_reason"] = fail_reason;

            return OSDParser.SerializeLLSDXmlBytes(result);
        }
 public override bool TryEnqueue(OSD ev, UUID avatarID, ulong RegionHandle)
 {
     if (!base.TryEnqueue(ev, avatarID, RegionHandle))
         if (!m_remoteService.TryEnqueue(ev, avatarID, RegionHandle))
             return false;
     return true;
 }
        public OSD HandleLLSDLogin(string path, OSD request, IPEndPoint remoteClient)
        {
            if (request.Type == OSDType.Map)
            {
                OSDMap map = (OSDMap) request;

                if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
                {
                    string startLocation = string.Empty;

                    if (map.ContainsKey("start"))
                        startLocation = map["start"].AsString();

                    MainConsole.Instance.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" +
                                              map["last"].AsString() + "' / " + startLocation);

                    LoginResponse reply = null;
                    string loginName = map["name"].AsString() == ""
                                           ? map["first"].AsString() + " " + map["last"].AsString()
                                           : map["name"].AsString();
                    reply = m_loginService.Login(UUID.Zero, loginName, "UserAccount", map["passwd"].AsString(),
                                                 startLocation,
                                                 "", "", "", "", remoteClient, new Hashtable());
                    return reply.ToOSDMap();
                }
            }

            return FailedOSDResponse();
        }
//        private static byte[] uintToByteArray(uint uIntValue)
//        {
//            byte[] result = new byte[4];
//            Utils.UIntToBytesBig(uIntValue, result, 0);
//            return result;
//        }

        public static OSD BuildEvent(string eventName, OSD eventBody)
        {
            OSDMap llsdEvent = new OSDMap(2);
            llsdEvent.Add("message", new OSDString(eventName));
            llsdEvent.Add("body", eventBody);

            return llsdEvent;
        }
 public static IPAddress ToIP(OSD osd)
 {
     byte[] binary = osd.AsBinary();
     if (binary != null && binary.Length == 4)
         return new IPAddress(binary);
     else
         return IPAddress.Any;
 }
Exemple #6
0
 public void SendAlertToUser(UUID agentID, string message, string infoMessage, OSD extraParams)
 {
     ScenePresence sp = m_scene.GetScenePresence(agentID);
     
     if (sp != null)
     {
         sp.ControllingClient.SendAlertMessage(message, infoMessage, extraParams);
     }
 }
Exemple #7
0
 public Hotkeyable(OSD osd, string name, string tempDisableDefault, string toggleDefault, bool state)
 {
     _config = HotkeyManager.Instance.Config;
     _osd = osd;
     _name = name;
     _tempDisable = new Hotkey("Disable " + name, tempDisableDefault);
     _toggle = new Hotkey("Toggle " + name, toggleDefault);
     _state = state;
     Load();
 }
        public void FromOSD(OSD osd)
        {
            OSDArray array = osd as OSDArray;

            RegionID = (array[0] as OSDMap)["regionID"];
            Cycle = new DayCycle();
            Cycle.FromOSD(array);

            Water = new WaterData();
            Water.FromOSD(array[3]);
        }
        public void Unpack(OSD data)
        {
            OSDMap map = (OSDMap)data;

            if (map.ContainsKey("InboundVersion"))
                InboundVersion = (float)map["InboundVersion"].AsReal();
            if (map.ContainsKey("OutboundVersion"))
                OutboundVersion = (float)map["OutboundVersion"].AsReal();
            if (map.ContainsKey("WearablesCount"))
                WearablesCount = map["WearablesCount"].AsInteger();
        }
Exemple #10
0
        public virtual bool Enqueue(OSD o, UUID agentID, ulong regionHandle)
        {
            //Find the CapsService for the user and enqueue the event
            IRegionClientCapsService service = GetRegionClientCapsService(agentID, regionHandle);
            if (service == null)
                return false;
            RegionClientEventQueueService eventQueueService = FindEventQueueConnector(service);
            if (eventQueueService == null)
                return false;

            return eventQueueService.Enqueue(o);
        }
Exemple #11
0
        public static Dictionary<string, string> ToDictionaryString(OSD osd)
        {
            if (osd.Type == OSDType.Map)
            {
                OSDMap map = (OSDMap)osd;
                Dictionary<string, string> dict = new Dictionary<string, string>(map.Count);
                foreach (KeyValuePair<string, OSD> entry in map)
                    dict.Add(entry.Key, entry.Value.AsString());
                return dict;
            }

            return new Dictionary<string, string>(0);
        }
Exemple #12
0
        public void Start()
        {
            _Dead = false;

            // Create an EventQueueGet request
            OSDMap request = new OSDMap();
            request["ack"] = new OSD();
            request["done"] = OSD.FromBoolean(false);

            byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);

            _Request = CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler);
        }
Exemple #13
0
        public static Dictionary<Uri, Uri> ToDictionaryUri(OSD osd)
        {
            if (osd.Type == OSDType.Map)
            {
                OSDMap map = (OSDMap)osd;
                Dictionary<Uri, Uri> dict = new Dictionary<Uri, Uri>(map.Count);
                foreach (KeyValuePair<string, OSD> entry in map)
                    dict.Add(new Uri(entry.Key), entry.Value.AsUri());
                return dict;
            }

            return new Dictionary<Uri, Uri>(0);
        }
Exemple #14
0
        public static JsonData SerializeJson(OSD osd, bool preserveDefaults)
        {
            switch (osd.Type)
            {
                case OSDType.Boolean:
                    return new JsonData(osd.AsBoolean());
                case OSDType.Integer:
                    return new JsonData(osd.AsInteger());
                case OSDType.Real:
                    return new JsonData(osd.AsReal());
                case OSDType.String:
                case OSDType.Date:
                case OSDType.URI:
                case OSDType.UUID:
                    return new JsonData(osd.AsString());
                case OSDType.Binary:
                    byte[] binary = osd.AsBinary();
                    JsonData jsonbinarray = new JsonData();
                    jsonbinarray.SetJsonType(JsonType.Array);
                    for (int i = 0; i < binary.Length; i++)
                        jsonbinarray.Add(new JsonData(binary[i]));
                    return jsonbinarray;
                case OSDType.Array:
                    JsonData jsonarray = new JsonData();
                    jsonarray.SetJsonType(JsonType.Array);
                    OSDArray array = (OSDArray)osd;
                    for (int i = 0; i < array.Count; i++)
                        jsonarray.Add(SerializeJson(array[i], preserveDefaults));
                    return jsonarray;
                case OSDType.Map:
                    JsonData jsonmap = new JsonData();
                    jsonmap.SetJsonType(JsonType.Object);
                    OSDMap map = (OSDMap)osd;
                    foreach (KeyValuePair<string, OSD> kvp in map)
                    {
                        JsonData data;

                        if (preserveDefaults)
                            data = SerializeJson(kvp.Value, preserveDefaults);
                        else
                            data = SerializeJsonNoDefaults(kvp.Value);

                        if (data != null)
                            jsonmap[kvp.Key] = data;
                    }
                    return jsonmap;
                case OSDType.Unknown:
                default:
                    return new JsonData(null);
            }
        }
        public static WearableCacheItem[] FromOSD(OSD pInput, IImprovedAssetCache dataCache)
        {
            List<WearableCacheItem> ret = new List<WearableCacheItem>();
            if (pInput.Type == OSDType.Array)
            {
                OSDArray itemarray = (OSDArray) pInput;
                foreach (OSDMap item in itemarray)
                {
                    ret.Add(new WearableCacheItem()
                                {
                                    TextureIndex = item["textureindex"].AsUInteger(),
                                    CacheId = item["cacheid"].AsUUID(),
                                    TextureID = item["textureid"].AsUUID()
                                });
                    
                    if (dataCache != null && item.ContainsKey("assetdata"))
                    {
                        AssetBase asset = new AssetBase(item["textureid"].AsUUID(),"BakedTexture",(sbyte)AssetType.Texture,UUID.Zero.ToString());
                        asset.Temporary = true;
                        asset.Data = item["assetdata"].AsBinary();
                        dataCache.Cache(asset);
                    }
                }
            }
            else if (pInput.Type == OSDType.Map)
            {
                OSDMap item = (OSDMap) pInput;
                ret.Add(new WearableCacheItem(){
                                    TextureIndex = item["textureindex"].AsUInteger(),
                                    CacheId = item["cacheid"].AsUUID(),
                                    TextureID = item["textureid"].AsUUID()
                                });
                if (dataCache != null && item.ContainsKey("assetdata"))
                {
                    string assetCreator = item["assetcreator"].AsString();
                    string assetName = item["assetname"].AsString();
                    AssetBase asset = new AssetBase(item["textureid"].AsUUID(), assetName, (sbyte)AssetType.Texture, assetCreator);
                    asset.Temporary = true;
                    asset.Data = item["assetdata"].AsBinary();
                    dataCache.Cache(asset);
                }
            }
            else
            {
                return new WearableCacheItem[0];
            }
            return ret.ToArray();

        }
        /// <summary>
        /// Creates AgentDisplayName object from OSD
        /// </summary>
        /// <param name="data">Incoming OSD data</param>
        /// <returns>AgentDisplayName object</returns>
        public static AgentDisplayName FromOSD(OSD data)
        {
            AgentDisplayName ret = new AgentDisplayName();

            OSDMap map = (OSDMap)data;
            ret.ID = map["id"];
            ret.UserName = map["username"];
            ret.DisplayName = map["display_name"];
            ret.LegacyFirstName = map["legacy_first_name"];
            ret.LegacyLastName = map["legacy_last_name"];
            ret.IsDefaultDisplayName = map["is_display_name_default"];
            ret.NextUpdate = map["display_name_next_update"];
            ret.Updated = map["last_updated"];

            return ret;
        }
        public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
        {
            OSD osd = null;

            using (MemoryStream msSinkCompressed = new MemoryStream())
            {
                using (ZOutputStream zOut = new ZOutputStream(msSinkCompressed,1))
                {
                    CopyStream(new MemoryStream(OSDParser.SerializeLLSDBinary(inOsd, useHeader)), zOut);
                    msSinkCompressed.Seek(0L, SeekOrigin.Begin);
                    osd = OSD.FromBinary(msSinkCompressed.ToArray());
                    zOut.Close();
                }

            }

            return osd;
        }
        internal static OSD ChatterBoxSessionAgentListUpdates(UUID sessionID,
                                                              ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
                                                              [] agentUpdatesBlock, string Transition)
        {
            OSDMap body         = new OSDMap();
            OSDMap agentUpdates = new OSDMap();
            OSDMap infoDetail   = new OSDMap();
            OSDMap mutes        = new OSDMap();

            foreach (ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block in agentUpdatesBlock)
            {
                infoDetail = new OSDMap();
                mutes      = new OSDMap
                {
                    { "text", OSD.FromBoolean(block.MuteText) }, { "voice", OSD.FromBoolean(block.MuteVoice) }
                };
                infoDetail.Add("can_voice_chat", OSD.FromBoolean(block.CanVoiceChat));
                infoDetail.Add("is_moderator", OSD.FromBoolean(block.IsModerator));
                infoDetail.Add("mutes", mutes);
                OSDMap info = new OSDMap {
                    { "info", infoDetail }
                };
                if (Transition != string.Empty)
                {
                    info.Add("transition", OSD.FromString(Transition));
                }
                agentUpdates.Add(block.AgentID.ToString(), info);
            }
            body.Add("agent_updates", agentUpdates);
            body.Add("session_id", OSD.FromUUID(sessionID));
            body.Add("updates", new OSD());

            OSDMap chatterBoxSessionAgentListUpdates = new OSDMap
            {
                {
                    "message",
                    OSD.FromString("ChatterBoxSessionAgentListUpdates")
                },
                { "body", body }
            };

            return(chatterBoxSessionAgentListUpdates);
        }
Exemple #19
0
        /// <summary>
        /// Since there are no consistencies in the way web requests are
        /// formed, we need to do a little guessing about the result format.
        /// Keys:
        ///     Success|success == the success fail of the request
        ///     _RawResult == the raw string that came back
        ///     _Result == the OSD unpacked string
        /// </summary>
        private static OSDMap CanonicalizeResults(string response, bool deserializeResponse)
        {
            OSDMap result = new OSDMap();

            // Default values
            result["Success"]    = OSD.FromBoolean(true);
            result["success"]    = OSD.FromBoolean(true);
            result["_RawResult"] = OSD.FromString(response);
            result["_Result"]    = new OSDMap();

            if (response.Equals("true", System.StringComparison.OrdinalIgnoreCase))
            {
                return(result);
            }

            if (response.Equals("false", System.StringComparison.OrdinalIgnoreCase))
            {
                result["Success"] = OSD.FromBoolean(false);
                result["success"] = OSD.FromBoolean(false);
                return(result);
            }

            if (deserializeResponse)
            {
                try
                {
                    OSD responseOSD = OSDParser.Deserialize(response);
                    if (responseOSD.Type == OSDType.Map)
                    {
                        result["_Result"] = (OSDMap)responseOSD;
                        return(result);
                    }
                }
                catch (Exception e)
                {
                    // don't need to treat this as an error... we're just guessing anyway
                    m_log.InfoFormat("[WebUtils] couldn't decode <{0}>: {1}", response, e.Message);
                }
            }

            return(result);
        }
        public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint)
        {
            uint xstart = 0;
            uint ystart = 0;

            Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart);

            OSDMap responsemap = new OSDMap();
            int    tc          = Environment.TickCount;

            if (m_scene.GetRootAgentCount() == 0)
            {
                OSDMap responsemapdata = new OSDMap();
                responsemapdata["X"]      = OSD.FromInteger((int)(xstart + 1));
                responsemapdata["Y"]      = OSD.FromInteger((int)(ystart + 1));
                responsemapdata["ID"]     = OSD.FromUUID(UUID.Zero);
                responsemapdata["Name"]   = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
                responsemapdata["Extra"]  = OSD.FromInteger(0);
                responsemapdata["Extra2"] = OSD.FromInteger(0);
                OSDArray responsearr = new OSDArray();
                responsearr.Add(responsemapdata);

                responsemap["6"] = responsearr;
            }
            else
            {
                OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount());
                m_scene.ForEachScenePresence(delegate(ScenePresence sp)
                {
                    OSDMap responsemapdata    = new OSDMap();
                    responsemapdata["X"]      = OSD.FromInteger((int)(xstart + sp.AbsolutePosition.X));
                    responsemapdata["Y"]      = OSD.FromInteger((int)(ystart + sp.AbsolutePosition.Y));
                    responsemapdata["ID"]     = OSD.FromUUID(UUID.Zero);
                    responsemapdata["Name"]   = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
                    responsemapdata["Extra"]  = OSD.FromInteger(1);
                    responsemapdata["Extra2"] = OSD.FromInteger(0);
                    responsearr.Add(responsemapdata);
                });
                responsemap["6"] = responsearr;
            }
            return(responsemap);
        }
        public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
        {
            Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
            Vector3d maxPosition = minPosition + new Vector3d(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight);

            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.TerrainImage) },
                { "Access", OSD.FromInteger(regionInfo.Access) },
                { "RegionSecret", OSD.FromString(regionInfo.RegionSecret) },
                { "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
                { "Token", OSD.FromString(regionInfo.Token) }
            };

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

            OSDMap response = WebUtil.PostToService(m_ServerURI, requestArgs);

            if (response["Success"].AsBoolean())
            {
                return(String.Empty);
            }
            else
            {
                return("Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString());
            }
        }
        /// <summary>
        /// Report back collected statistical information as an OSDMap
        /// </summary>
        /// <returns></returns>
        public override OSDMap OReport(string uptime, string version)
        {
            OSDMap args = new OSDMap(30);

            //            args["AssetsInCache"] = OSD.FromString (String.Format ("{0:0.##}", AssetsInCache));
            //            args["TimeAfterCacheMiss"] = OSD.FromString (String.Format ("{0:0.##}",
            //                    assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0));
            //            args["BlockedMissingTextureRequests"] = OSD.FromString (String.Format ("{0:0.##}",
            //                    BlockedMissingTextureRequests));
            //            args["AssetServiceRequestFailures"] = OSD.FromString (String.Format ("{0:0.##}",
            //                    AssetServiceRequestFailures));
            //            args["abnormalClientThreadTerminations"] = OSD.FromString (String.Format ("{0:0.##}",
            //                    abnormalClientThreadTerminations));
            //            args["InventoryServiceRetrievalFailures"] = OSD.FromString (String.Format ("{0:0.##}",
            //                    InventoryServiceRetrievalFailures));
            args["Dilatn"]  = OSD.FromString(String.Format("{0:0.##}", timeDilation));
            args["SimFPS"]  = OSD.FromString(String.Format("{0:0.##}", simFps));
            args["PhyFPS"]  = OSD.FromString(String.Format("{0:0.##}", physicsFps));
            args["AgntUp"]  = OSD.FromString(String.Format("{0:0.##}", agentUpdates));
            args["RootAg"]  = OSD.FromString(String.Format("{0:0.##}", rootAgents));
            args["ChldAg"]  = OSD.FromString(String.Format("{0:0.##}", childAgents));
            args["Prims"]   = OSD.FromString(String.Format("{0:0.##}", totalPrims));
            args["AtvPrm"]  = OSD.FromString(String.Format("{0:0.##}", activePrims));
            args["AtvScr"]  = OSD.FromString(String.Format("{0:0.##}", activeScripts));
            args["ScrLPS"]  = OSD.FromString(String.Format("{0:0.##}", scriptLinesPerSecond));
            args["PktsIn"]  = OSD.FromString(String.Format("{0:0.##}", inPacketsPerSecond));
            args["PktOut"]  = OSD.FromString(String.Format("{0:0.##}", outPacketsPerSecond));
            args["PendDl"]  = OSD.FromString(String.Format("{0:0.##}", pendingDownloads));
            args["PendUl"]  = OSD.FromString(String.Format("{0:0.##}", pendingUploads));
            args["UnackB"]  = OSD.FromString(String.Format("{0:0.##}", unackedBytes));
            args["TotlFt"]  = OSD.FromString(String.Format("{0:0.##}", totalFrameTime));
            args["NetFt"]   = OSD.FromString(String.Format("{0:0.##}", netFrameTime));
            args["PhysFt"]  = OSD.FromString(String.Format("{0:0.##}", physicsFrameTime));
            args["OthrFt"]  = OSD.FromString(String.Format("{0:0.##}", otherFrameTime));
            args["AgntFt"]  = OSD.FromString(String.Format("{0:0.##}", agentFrameTime));
            args["ImgsFt"]  = OSD.FromString(String.Format("{0:0.##}", imageFrameTime));
            args["Memory"]  = OSD.FromString(base.XReport(uptime, version));
            args["Uptime"]  = OSD.FromString(uptime);
            args["Version"] = OSD.FromString(version);

            return(args);
        }
Exemple #23
0
        /// <summary>
        /// Get GridInfo in json format: Used bu the OSSL osGetGrid*
        /// Adding the SRV_HomeIRI to the kvp returned for use in scripts
        /// </summary>
        /// <returns>
        /// json string
        /// </returns>
        /// <param name='request'>
        /// Request.
        /// </param>
        /// <param name='path'>
        ///  /json_grid_info
        /// </param>
        /// <param name='param'>
        /// Parameter.
        /// </param>
        /// <param name='httpRequest'>
        /// Http request.
        /// </param>
        /// <param name='httpResponse'>
        /// Http response.
        /// </param>
        public string JsonGetGridInfoMethod(string request, string path, string param,
                                            IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            OSDMap map = new OSDMap();

            foreach (string k in _info.Keys)
            {
                map[k] = OSD.FromString(_info[k].ToString());
            }

            string HomeURI = Util.GetConfigVarFromSections <string>(m_Config, "HomeURI",
                                                                    new string[] { "Startup", "Hypergrid" }, String.Empty).ToLowerInvariant();

            if (!String.IsNullOrEmpty(HomeURI))
            {
                if (!HomeURI.EndsWith("/"))
                {
                    HomeURI += "/";
                }
                map["home"] = OSD.FromString(HomeURI);
            }
            else // Legacy. Remove soon!
            {
                IConfig cfg = m_Config.Configs["LoginService"];

                if (null != cfg)
                {
                    HomeURI = cfg.GetString("SRV_HomeURI", HomeURI).ToLowerInvariant();
                    if (!string.IsNullOrEmpty(HomeURI) && !HomeURI.EndsWith("/"))
                    {
                        HomeURI += "/";
                    }
                }

                if (!String.IsNullOrEmpty(HomeURI))
                {
                    map["home"] = OSD.FromString(HomeURI);
                }
            }

            return(OSDParser.SerializeJsonString(map).ToString());
        }
        OSDMap EditUser(OSDMap map)
        {
            bool   editRLInfo = (map.ContainsKey("RLName") && map.ContainsKey("RLAddress") && map.ContainsKey("RLZip") && map.ContainsKey("RLCity") && map.ContainsKey("RLCountry"));
            OSDMap resp       = new OSDMap();

            resp ["agent"]   = OSD.FromBoolean(!editRLInfo); // if we have no RLInfo, editing account is assumed to be successful.
            resp ["account"] = OSD.FromBoolean(false);
            UUID        principalID = map ["UserID"].AsUUID();
            UserAccount account     = m_registry.RequestModuleInterface <IUserAccountService> ().GetUserAccount(null, principalID);

            if (account != null)
            {
                account.Email = map ["Email"];
                if (m_registry.RequestModuleInterface <IUserAccountService> ().GetUserAccount(null, map ["Name"].AsString()) == null)
                {
                    account.Name = map ["Name"];
                }

                if (editRLInfo)
                {
                    IAgentConnector agentConnector = DataPlugins.RequestPlugin <IAgentConnector> ();
                    IAgentInfo      agent          = agentConnector.GetAgent(account.PrincipalID);
                    if (agent == null)
                    {
                        agentConnector.CreateNewAgent(account.PrincipalID);
                        agent = agentConnector.GetAgent(account.PrincipalID);
                    }
                    if (agent != null)
                    {
                        agent.OtherAgentInformation ["RLName"]    = map ["RLName"];
                        agent.OtherAgentInformation ["RLAddress"] = map ["RLAddress"];
                        agent.OtherAgentInformation ["RLZip"]     = map ["RLZip"];
                        agent.OtherAgentInformation ["RLCity"]    = map ["RLCity"];
                        agent.OtherAgentInformation ["RLCountry"] = map ["RLCountry"];
                        agentConnector.UpdateAgent(agent);
                        resp ["agent"] = OSD.FromBoolean(true);
                    }
                }
                resp ["account"] = OSD.FromBoolean(m_registry.RequestModuleInterface <IUserAccountService> ().StoreUserAccount(account));
            }
            return(resp);
        }
Exemple #25
0
        public OSDMap PackRegionInfoData(bool secure)
        {
            OSDMap args = new OSDMap();

            args["region_id"] = OSD.FromUUID(RegionID);
            if ((RegionName != null) && !RegionName.Equals(""))
            {
                args["region_name"] = OSD.FromString(RegionName);
            }
            args["external_host_name"]  = OSD.FromString(ExternalHostName);
            args["http_port"]           = OSD.FromString(HttpPort.ToString());
            args["server_uri"]          = OSD.FromString(ServerURI);
            args["region_xloc"]         = OSD.FromString(RegionLocX.ToString());
            args["region_yloc"]         = OSD.FromString(RegionLocY.ToString());
            args["internal_ep_address"] = OSD.FromString(InternalEndPoint.Address.ToString());
            args["internal_ep_port"]    = OSD.FromString(InternalEndPoint.Port.ToString());
            args["allow_alt_ports"]     = OSD.FromBoolean(m_allow_alternate_ports);
            if (RegionType != String.Empty)
            {
                args["region_type"] = OSD.FromString(RegionType);
            }
            args["password"]      = OSD.FromUUID(Password);
            args["region_size_x"] = OSD.FromInteger(RegionSizeX);
            args["region_size_y"] = OSD.FromInteger(RegionSizeY);
            args["region_size_z"] = OSD.FromInteger(RegionSizeZ);
            if (secure)
            {
                args["disabled"]        = OSD.FromBoolean(Disabled);
                args["scope_id"]        = OSD.FromUUID(ScopeID);
                args["object_capacity"] = OSD.FromInteger(m_objectCapacity);
                args["region_type"]     = OSD.FromString(RegionType);
                args["see_into_this_sim_from_neighbor"]  = OSD.FromBoolean(SeeIntoThisSimFromNeighbor);
                args["trust_binaries_from_foreign_sims"] = OSD.FromBoolean(TrustBinariesFromForeignSims);
                args["allow_script_crossing"]            = OSD.FromBoolean(AllowScriptCrossing);
                args["allow_physical_prims"]             = OSD.FromBoolean(AllowPhysicalPrims);
                args["number_startup"] = OSD.FromInteger(NumberStartup);
                args["startupType"]    = OSD.FromInteger((int)Startup);
                args["FindExternalIP"] = OSD.FromBoolean(FindExternalAutomatically);
                args["RegionSettings"] = RegionSettings.ToOSD();
            }
            return(args);
        }
Exemple #26
0
        public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
        {
            OSD osd = null;

            byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);

            using (MemoryStream msSinkCompressed = new MemoryStream())
            {
                using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
                                                                              Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
                {
                    zOut.Write(data, 0, data.Length);
                }

                msSinkCompressed.Seek(0L, SeekOrigin.Begin);
                osd = OSD.FromBinary(msSinkCompressed.ToArray());
            }

            return(osd);
        }
Exemple #27
0
        public static OSD EnableSimulator(ulong handle, IPEndPoint endPoint, int regionSizeX, int regionSizeY)
        {
            OSDMap llsdSimInfo = new OSDMap(5);

            llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle)));
            llsdSimInfo.Add("IP", new OSDBinary(endPoint.Address.GetAddressBytes()));
            llsdSimInfo.Add("Port", new OSDInteger(endPoint.Port));
            llsdSimInfo.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
            llsdSimInfo.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));

            OSDArray arr = new OSDArray(1);

            arr.Add(llsdSimInfo);

            OSDMap llsdBody = new OSDMap(1);

            llsdBody.Add("SimulatorInfo", arr);

            return(BuildEvent("EnableSimulator", llsdBody));
        }
Exemple #28
0
        private void FillOutRezAgentResponse(User user, Uri seedCapability, Vector3 startPosition, Vector3 lookAt, ref OSDMap responseMap)
        {
            IPAddress externalAddress = m_lludp.MasqueradeAddress ?? m_lludp.Address;
            uint      regionX, regionY;

            GetRegionXY(m_scene.MinPosition, out regionX, out regionY);

            responseMap["connect"]  = OSD.FromBoolean(true);
            responseMap["agent_id"] = OSD.FromUUID(user.ID);
            responseMap["sim_host"] = OSD.FromString(externalAddress.ToString());
            responseMap["sim_port"] = OSD.FromInteger(m_lludp.Port);
            responseMap["region_seed_capability"] = OSD.FromUri(seedCapability);
            responseMap["position"] = OSD.FromVector3(startPosition);
            responseMap["look_at"]  = OSD.FromVector3(lookAt);

            // Region information
            responseMap["region_id"] = OSD.FromUUID(m_scene.ID);
            responseMap["region_x"]  = OSD.FromInteger(regionX);
            responseMap["region_y"]  = OSD.FromInteger(regionY);
        }
        /// <summary>
        ///     Send the user a display name update
        /// </summary>
        /// <param name="newDisplayName"></param>
        /// <param name="oldDisplayName"></param>
        /// <param name="InfoFromAv"></param>
        /// <param name="ToAgentID"></param>
        public void DisplayNameUpdate(string newDisplayName, string oldDisplayName, UserAccount InfoFromAv,
                                      UUID ToAgentID)
        {
            if (m_eventQueue != null)
            {
                //If the DisplayName is blank, the client refuses to do anything, so we send the name by default
                if (newDisplayName == "")
                {
                    newDisplayName = InfoFromAv.Name;
                }

                bool isDefaultName = isDefaultDisplayName(InfoFromAv.FirstName, InfoFromAv.LastName, InfoFromAv.Name,
                                                          newDisplayName);

                OSD item = DisplayNameUpdate(newDisplayName, oldDisplayName, InfoFromAv.PrincipalID, isDefaultName,
                                             InfoFromAv.FirstName, InfoFromAv.LastName,
                                             InfoFromAv.FirstName + "." + InfoFromAv.LastName);
                m_eventQueue.Enqueue(item, ToAgentID, m_service.Region.RegionID);
            }
        }
        /// <summary>
        ///   Add the given event into the client's queue so that it is sent on the next
        /// </summary>
        /// <param name = "ev"></param>
        /// <param name = "avatarID"></param>
        /// <returns></returns>
        public bool Enqueue(OSD ev)
        {
            try
            {
                if (ev == null)
                {
                    return(false);
                }

                lock (queue)
                    queue.Enqueue(ev);
            }
            catch (NullReferenceException e)
            {
                MainConsole.Instance.Error("[EVENTQUEUE] Caught exception: " + e);
                return(false);
            }

            return(true);
        }
Exemple #31
0
        public override OSDMap ToOSD()
        {
            OSDMap map = new OSDMap
            {
                { "RegionID", OSD.FromUUID(RegionID) },
                { "RegionLocX", OSD.FromReal(RegionLocX) },
                { "RegionLocY", OSD.FromReal(RegionLocY) },
                { "TelehubRotX", OSD.FromReal(TelehubRotX) },
                { "TelehubRotY", OSD.FromReal(TelehubRotY) },
                { "TelehubRotZ", OSD.FromReal(TelehubRotZ) },
                { "TelehubLocX", OSD.FromReal(TelehubLocX) },
                { "TelehubLocY", OSD.FromReal(TelehubLocY) },
                { "TelehubLocZ", OSD.FromReal(TelehubLocZ) },
                { "Spawns", OSD.FromString(BuildFromList(SpawnPos)) },
                { "ObjectUUID", OSD.FromUUID(ObjectUUID) },
                { "Name", OSD.FromString(Name) }
            };

            return(map);
        }
Exemple #32
0
        public static Grid FromOSD(OSD data)
        {
            if (data == null || data.Type != OSDType.Map) return null;
            Grid grid = new Grid();
            OSDMap map = (OSDMap)data;

            grid.ID = map["gridnick"].AsString();
            grid.Name = map["gridname"].AsString();
            grid.Platform = map["platform"].AsString();
            grid.LoginURI = map["loginuri"].AsString();
            grid.LoginPage = map["loginpage"].AsString();
            grid.HelperURI = map["helperuri"].AsString();
            grid.Website = map["website"].AsString();
            grid.Support = map["support"].AsString();
            grid.Register = map["register"].AsString();
            grid.PasswordURL = map["password"].AsString();
            grid.Version = map["version"].AsString();

            return grid;
        }
Exemple #33
0
        void CameraOnllyModeRequest(OSHttpRequest httpRequest)
        {
            //if (ShouldSend(m_service.AgentID,m_service.RegionID) && UserLevel(m_service.AgentID) <= m_UserLevel)
            //{
            OSDMap extrasMap = new OSDMap();

            if (httpRequest.Query.ContainsKey("OpenSimExtras"))
            {
                OSD nmap = httpRequest.Query ["OpenSimExtras"].ToString();
                extrasMap = (OSDMap)nmap;
            }

            extrasMap ["camera-only-mode"] = OSDMap.FromString("true");

            // TODO: Need to find out how this is determined  i.e. sent from viewer??
            // Detach agent attachments
            //Util.FireAndForget(delegate { DetachAttachments(agentID); });

            //}
        }
Exemple #34
0
        private void GatherCapsResponse(CapsClient client, OSD response, Exception error)
        {
            if (response is OSDMap)
            {
                OSDMap respTable = (OSDMap)response;

                // parse
                _caps = new RegistrationCaps();

                _caps.CreateUser    = respTable["create_user"].AsUri();
                _caps.CheckName     = respTable["check_name"].AsUri();
                _caps.GetLastNames  = respTable["get_last_names"].AsUri();
                _caps.GetErrorCodes = respTable["get_error_codes"].AsUri();

                // finalize
                _initializing++;

                GatherErrorMessages();
            }
        }
Exemple #35
0
        public void CreateFromData(UUID itemID, UUID objectID,
                                   OSD data)
        {
            OSDMap     save = (OSDMap)data;
            TimerClass ts   = new TimerClass();

            ts.ID       = objectID;
            ts.itemID   = itemID;
            ts.interval = (long)save["Interval"].AsReal();
            if (ts.interval == 0)
            {
                return;
            }
            ts.next = Environment.TickCount + (long)save["Next"].AsReal();

            lock (TimerListLock)
            {
                Timers[MakeTimerKey(objectID, itemID)] = ts;
            }
        }
Exemple #36
0
        protected virtual void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
        {
            if (source != null)
            {
                args["source_x"]    = OSD.FromString(source.RegionLocX.ToString());
                args["source_y"]    = OSD.FromString(source.RegionLocY.ToString());
                args["source_name"] = OSD.FromString(source.RegionName);
                args["source_uuid"] = OSD.FromString(source.RegionID.ToString());
                if (!String.IsNullOrEmpty(source.RawServerURI))
                {
                    args["source_server_uri"] = OSD.FromString(source.RawServerURI);
                }
            }

            args["destination_x"]    = OSD.FromString(destination.RegionLocX.ToString());
            args["destination_y"]    = OSD.FromString(destination.RegionLocY.ToString());
            args["destination_name"] = OSD.FromString(destination.RegionName);
            args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
            args["teleport_flags"]   = OSD.FromString(flags.ToString());
        }
        public static OSD ScriptRunningReplyEvent(UUID objectID, UUID itemID, bool running, bool mono)
        {
            OSDMap script = new OSDMap
            {
                { "ObjectID", OSD.FromUUID(objectID) },
                { "ItemID", OSD.FromUUID(itemID) },
                { "Running", OSD.FromBoolean(running) },
                { "Mono", OSD.FromBoolean(mono) }
            };

            OSDArray scriptArr = new OSDArray {
                script
            };

            OSDMap body = new OSDMap {
                { "Script", scriptArr }
            };

            return(buildEvent("ScriptRunningReply", body));
        }
Exemple #38
0
        /// <summary>
        ///   Serialize all the registered Components into a string to be saved later
        /// </summary>
        /// <param name = "obj">The object to serialize</param>
        /// <returns>The serialized string</returns>
        public string SerializeComponents(ISceneChildEntity obj)
        {
            OSDMap ComponentsBody = new OSDMap();

            //Run through the list of components and serialize them
            foreach (IComponent component in m_components.Values)
            {
                //Add the componet to the map by its name
                OSD o = component.GetState(obj.UUID, true);
                if (o != null && o.Type != OSDType.Unknown)
                {
                    ComponentsBody.Add(component.Name, o);
                }
            }
            string result = OSDParser.SerializeJsonString(ComponentsBody, true);

            ComponentsBody.Clear();

            return(result);
        }
Exemple #39
0
        /// <summary>
        ///     Pack this asset into an OSDMap
        /// </summary>
        /// <returns></returns>
        public override OSDMap ToOSD()
        {
            OSDMap assetMap = new OSDMap
            {
                { "AssetFlags", OSD.FromInteger((int)Flags) },
                { "AssetID", ID },
                { "CreationDate", OSD.FromDate(CreationDate) },
                { "CreatorID", OSD.FromUUID(CreatorID) },
                { "Data", OSD.FromBinary(Data) },
                { "HostUri", OSD.FromString(HostUri) },
                { "LastAccessed", OSD.FromDate(LastAccessed) },
                { "Name", OSD.FromString(Name) },
                { "ParentID", CreationDate },
                { "TypeAsset", OSD.FromInteger((int)TypeAsset) },
                { "Description", OSD.FromString(Description) },
                { "DatabaseTable", OSD.FromString(DatabaseTable) }
            };

            return(assetMap);
        }
        public byte [] HandleFetchInventory(Stream request, UUID agentID)
        {
            try {
                // MainConsole.Instance.DebugFormat("[InventoryCAPS]: Received FetchInventory request for {0}", agentID);
                OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(HttpServerHandlerHelpers.ReadFully(request));
                if (requestmap ["items"].Type == OSDType.Unknown)
                {
                    MainConsole.Instance.Error("[InventoryCAPS]: Call to 'FetchInventory' with missing 'items' parameter");
                    return(MainServer.BadRequest);
                }

                OSDArray foldersrequested = (OSDArray)requestmap ["items"];
                OSDMap   map = new OSDMap {
                    { "agent_id", OSD.FromUUID(agentID) }
                };
                // We have to send the agent_id in the main map as well as all the items

                OSDArray items = new OSDArray();
                foreach (
                    OSDArray item in
                    foldersrequested.Cast <OSDMap> ()
                    .Select(requestedFolders => requestedFolders ["item_id"].AsUUID())
                    .Select(item_id => m_inventoryService.GetOSDItem(m_agentID, item_id))
                    .Where(item => item != null && item.Count > 0))
                {
                    items.Add(item [0]);
                }
                map.Add("items", items);

                byte [] response = OSDParser.SerializeLLSDXmlBytes(map);
                map.Clear();
                return(response);
            } catch (Exception ex) {
                MainConsole.Instance.Warn("[InventoryCAPS]: SERIOUS ISSUE! " + ex);
            }

            OSDMap rmap = new OSDMap();

            rmap ["items"] = new OSDArray();
            return(OSDParser.SerializeLLSDXmlBytes(rmap));
        }
Exemple #41
0
        /// <summary>
        /// Get GridInfo in json format: Used by the OSSL osGetGrid*
        /// Adding the SRV_HomeIRI to the kvp returned for use in scripts
        /// </summary>
        /// <returns>
        /// json string
        /// </returns>
        /// </param>
        /// <param name='httpRequest'>
        /// Http request.
        /// </param>
        /// <param name='httpResponse'>
        /// Http response.
        /// </param>
        public void JsonGetGridInfoMethod(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            httpResponse.KeepAlive = false;

            if (httpRequest.HttpMethod != "GET")
            {
                httpResponse.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                return;
            }

            OSDMap map = new OSDMap();

            foreach (string k in _info.Keys)
            {
                map[k] = OSD.FromString(_info[k].ToString());
            }

            string HomeURI = Util.GetConfigVarFromSections <string>(m_Config, "HomeURI",
                                                                    new string[] { "Startup", "Hypergrid" }, String.Empty);

            if (!string.IsNullOrEmpty(HomeURI))
            {
                map["home"] = OSD.FromString(HomeURI);
            }
            else // Legacy. Remove soon!
            {
                IConfig cfg = m_Config.Configs["LoginService"];

                if (null != cfg)
                {
                    HomeURI = cfg.GetString("SRV_HomeURI", HomeURI);
                }

                if (!string.IsNullOrEmpty(HomeURI))
                {
                    map["home"] = OSD.FromString(HomeURI);
                }
            }

            httpResponse.RawBuffer = OSDParser.SerializeJsonToBytes(map);
        }
 /// <summary>
 /// Gets the classified records.
 /// </summary>
 /// <returns>
 /// Array of classified records
 /// </returns>
 /// <param name='creatorId'>
 /// Creator identifier.
 /// </param>
 public OSDArray GetClassifiedRecords(UUID creatorId)
 {
     OSDArray data = new OSDArray();
     
     using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
     {
         string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id";
         dbcon.Open();
         using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
         {
             cmd.Parameters.AddWithValue("?Id", creatorId);
             using( MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
             {
                 if(reader.HasRows)
                 {
                     while (reader.Read())
                     {
                         OSDMap n = new OSDMap();
                         UUID Id = UUID.Zero;
                         
                         string Name = null;
                         try
                         {
                             UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id);
                             Name = Convert.ToString(reader["name"]);
                         }
                         catch (Exception e)
                         {
                             m_log.DebugFormat("[PROFILES_DATA]" +
                                              ": UserAccount exception {0}", e.Message);
                         }
                         n.Add("classifieduuid", OSD.FromUUID(Id));
                         n.Add("name", OSD.FromString(Name));
                         data.Add(n);
                     }
                 }
             }
         }
     }
     return data;
 }
 public bool GetAvatarNotes(ref UserProfileNotes notes)
 {  // WIP
     string query = string.Empty;
     
     query += "SELECT `notes` FROM usernotes WHERE ";
     query += "useruuid = ?Id AND ";
     query += "targetuuid = ?TargetId";
     OSDArray data = new OSDArray();
     
     try
     {
         using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
         {
             dbcon.Open();
             using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
             {
                 cmd.Parameters.AddWithValue("?Id", notes.UserId.ToString());
                 cmd.Parameters.AddWithValue("?TargetId", notes.TargetId.ToString());
                 
                 using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                 {
                     if(reader.HasRows)
                     {
                         reader.Read();
                         notes.Notes = OSD.FromString((string)reader["notes"]);
                     }
                     else
                     {
                         notes.Notes = OSD.FromString("");
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         m_log.DebugFormat("[PROFILES_DATA]" +
                          ": GetAvatarNotes exception {0}", e.Message);
     }
     return true;
 }
 public OSDArray GetAvatarPicks(UUID avatarId)
 {
     string query = string.Empty;
     
     query += "SELECT `pickuuid`,`name` FROM userpicks WHERE ";
     query += "creatoruuid = ?Id";
     OSDArray data = new OSDArray();
     
     try
     {
         using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
         {
             dbcon.Open();
             using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
             {
                 cmd.Parameters.AddWithValue("?Id", avatarId.ToString());
                 
                 using (MySqlDataReader reader = cmd.ExecuteReader())
                 {
                     if(reader.HasRows)
                     {
                         while (reader.Read())
                         {
                             OSDMap record = new OSDMap();
                             
                             record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"]));
                             record.Add("name",OSD.FromString((string)reader["name"]));
                             data.Add(record);
                         }
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         m_log.DebugFormat("[PROFILES_DATA]" +
                          ": GetAvatarPicks exception {0}", e.Message);
     }
     return data;
 }
        public OSDArray GetAvatarPicks(UUID avatarId)
        {
            string query = string.Empty;

            query += "SELECT pickuuid, name FROM userpicks WHERE ";
            query += "creatoruuid = :Id";
            OSDArray data = new OSDArray();

            try
            {
                using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
                    {
                        cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId));

                        using (NpgsqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    OSDMap record = new OSDMap();

                                    record.Add("pickuuid", OSD.FromUUID(DBGuid.FromDB(reader["pickuuid"])));
                                    record.Add("name", OSD.FromString((string)reader["name"]));
                                    data.Add(record);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Error("[PROFILES_DATA]: GetAvatarPicks exception ", e);
            }

            return(data);
        }
        /// <summary>
        /// Gets the classified records.
        /// </summary>
        /// <returns>
        /// Array of classified records
        /// </returns>
        /// <param name='creatorId'>
        /// Creator identifier.
        /// </param>
        public OSDArray GetClassifiedRecords(UUID creatorId)
        {
            OSDArray data = new OSDArray();

            using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
            {
                string query = @"SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id";
                dbcon.Open();
                using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
                {
                    cmd.Parameters.Add(m_database.CreateParameter("Id", creatorId));
                    using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                OSDMap n  = new OSDMap();
                                UUID   Id = UUID.Zero;

                                string Name = null;
                                try
                                {
                                    Id   = DBGuid.FromDB(reader["classifieduuid"]);
                                    Name = Convert.ToString(reader["name"]);
                                }
                                catch (Exception e)
                                {
                                    m_log.Error("[PROFILES_DATA]: UserAccount exception ", e);
                                }

                                n.Add("classifieduuid", OSD.FromUUID(Id));
                                n.Add("name", OSD.FromString(Name));
                                data.Add(n);
                            }
                        }
                    }
                }
            }
            return(data);
        }
Exemple #47
0
        public override OSDMap ToOSD()
        {
            OSDMap map = new OSDMap
            {
                { "fromAgentID", OSD.FromUUID(fromAgentID) },
                { "fromAgentName", OSD.FromString(fromAgentName) },
                { "toAgentID", OSD.FromUUID(toAgentID) },
                { "dialog", OSD.FromInteger(dialog) },
                { "fromGroup", OSD.FromBoolean(fromGroup) },
                { "message", OSD.FromString(message) },
                { "imSessionID", OSD.FromUUID(imSessionID) },
                { "offline", OSD.FromInteger(offline) },
                { "Position", OSD.FromVector3(Position) },
                { "binaryBucket", OSD.FromBinary(binaryBucket) },
                { "ParentEstateID", OSD.FromUInteger(ParentEstateID) },
                { "RegionID", OSD.FromUUID(RegionID) },
                { "timestamp", OSD.FromUInteger(timestamp) }
            };

            return(map);
        }
        public override OSDMap ToOSD()
        {
            OSDMap Pick = new OSDMap
            {
                { "PickUUID", OSD.FromUUID(PickUUID) },
                { "CreatorUUID", OSD.FromUUID(CreatorUUID) },
                { "TopPick", OSD.FromInteger(TopPick) },
                { "ParcelUUID", OSD.FromUUID(ParcelUUID) },
                { "Name", OSD.FromString(Name) },
                { "Description", OSD.FromString(Description) },
                { "SnapshotUUID", OSD.FromUUID(SnapshotUUID) },
                { "User", OSD.FromString(User) },
                { "OriginalName", OSD.FromString(OriginalName) },
                { "SimName", OSD.FromString(SimName) },
                { "GlobalPos", OSD.FromVector3(GlobalPos) },
                { "SortOrder", OSD.FromInteger(SortOrder) },
                { "Enabled", OSD.FromInteger(Enabled) }
            };

            return(Pick);
        }
        private Hashtable SetEnvironment (Hashtable m_dhttpMethod, UUID agentID)
        {
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"] = 200; //501; //410; //404;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;
            responsedata["str_response_string"] = "";

            IScenePresence SP = m_scene.GetScenePresence(agentID);
            if(SP == null)
                return responsedata; //They don't exist
            if(SP.Scene.Permissions.CanIssueEstateCommand(agentID, false))
            {
                m_info = OSDParser.DeserializeLLSDXml((string)m_dhttpMethod["requestbody"]);
                IGenericsConnector gc = DataManager.DataManager.RequestPlugin<IGenericsConnector>();
                if(gc != null)
                    gc.AddGeneric(m_scene.RegionInfo.RegionID, "EnvironmentSettings", "", (new DatabaseWrapper() { Info=m_info }).ToOSD());
                SP.ControllingClient.SendAlertMessage("Windlight Settings saved successfully");
            }
            else
                SP.ControllingClient.SendAlertMessage("You don't have the correct permissions to set the Windlight Settings");
            return responsedata;
        }
        public void BeginGetResponse(OSD data, OSDFormat format, int millisecondsTimeout)
        {
            byte[] postData;
            string contentType;

            switch (format)
            {
                case OSDFormat.Xml:
                    postData = OSDParser.SerializeLLSDXmlBytes(data);
                    contentType = "application/llsd+xml";
                    break;
                case OSDFormat.Binary:
                    postData = OSDParser.SerializeLLSDBinary(data);
                    contentType = "application/llsd+binary";
                    break;
                case OSDFormat.Json:
                default:
                    postData = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data));
                    contentType = "application/llsd+json";
                    break;
            }

            BeginGetResponse(postData, contentType, millisecondsTimeout);
        }
Exemple #51
0
        public void CreateFromData(UUID itemID, UUID objectID,
                                   OSD data)
        {
            OSDMap save = (OSDMap)data;
            TimerClass ts = new TimerClass { ID = objectID, itemID = itemID, interval = save["Interval"].AsLong() };

            if (ts.interval == 0) // Disabling timer
                return;

            ts.next = Environment.TickCount + save["Next"].AsLong();

            lock (TimerListLock)
            {
                Timers[MakeTimerKey(objectID, itemID)] = ts;
            }

            //Make sure that the cmd handler thread is running
            m_ScriptEngine.MaintenanceThread.PokeThreads(ts.itemID);
        }
        private void ProvisionCapsResponse(CapsClient client, OSD response, Exception error)
        {
            if (response is OSDMap)
            {
                OSDMap respTable = (OSDMap)response;

                if (OnProvisionAccount != null)
                {
                    try { OnProvisionAccount(respTable["username"].AsString(), respTable["password"].AsString()); }
                    catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
                }
            }
        }
        private void ParcelVoiceInfoResponse(CapsClient client, OSD response, Exception error)
        {
            if (response is OSDMap)
            {
                OSDMap respTable = (OSDMap)response;

                string regionName = respTable["region_name"].AsString();
                int localID = (int)respTable["parcel_local_id"].AsInteger();

                string channelURI = null;
                if (respTable["voice_credentials"] is OSDMap)
                {
                    OSDMap creds = (OSDMap)respTable["voice_credentials"];
                    channelURI = creds["channel_uri"].AsString();
                }

                if (OnParcelVoiceInfo != null) OnParcelVoiceInfo(regionName, localID, channelURI);
            }
        }
Exemple #54
0
            public static TextureAnimation FromOSD(OSD osd)
            {
                TextureAnimation anim = new TextureAnimation();
                OSDMap map = osd as OSDMap;

                if (map != null)
                {
                    anim.Face = map["face"].AsUInteger();
                    anim.Flags = (TextureAnimMode)map["flags"].AsUInteger();
                    anim.Length = (float)map["length"].AsReal();
                    anim.Rate = (float)map["rate"].AsReal();
                    anim.SizeX = map["size_x"].AsUInteger();
                    anim.SizeY = map["size_y"].AsUInteger();
                    anim.Start = (float)map["start"].AsReal();
                }

                return anim;
            }
Exemple #55
0
            public static TextureEntryFace FromOSD(OSD osd, TextureEntryFace defaultFace, out int faceNumber)
            {
                OSDMap map = (OSDMap)osd;

                TextureEntryFace face = new TextureEntryFace(defaultFace);
                faceNumber = (map.ContainsKey("face_number")) ? map["face_number"].AsInteger() : -1;
                Color4 rgba = face.RGBA;
                rgba = ((OSDArray)map["colors"]).AsColor4();
                face.RGBA = rgba;
                face.RepeatU = (float)map["scales"].AsReal();
                face.RepeatV = (float)map["scalet"].AsReal();
                face.OffsetU = (float)map["offsets"].AsReal();
                face.OffsetV = (float)map["offsett"].AsReal();
                face.Rotation = (float)map["imagerot"].AsReal();
                face.Bump = (Bumpiness)map["bump"].AsInteger();
                face.Shiny = (Shininess)map["shiny"].AsInteger();
                face.Fullbright = map["fullbright"].AsBoolean();
                face.MediaFlags = map["media_flags"].AsBoolean();
                face.TexMapType = (MappingType)map["mapping"].AsInteger();
                face.Glow = (float)map["glow"].AsReal();
                face.TextureID = map["imageid"].AsUUID();
                face.MaterialID = map["materialid"];
                return face;
            }
 public TextureInfo(OSD osd)
 {
     if (osd is OSDMap)
     {
         Id = ((OSDMap)osd)["id"].AsUUID();
         MeanColor = ((OSDMap)osd)["meancolor"].AsColor4();
     }
 }
Exemple #57
0
        /// <summary>
        /// Handle response from LLSD login replies
        /// </summary>
        /// <param name="client"></param>
        /// <param name="result"></param>
        /// <param name="error"></param>
        private void LoginReplyLLSDHandler(CapsClient client, OSD result, Exception error)
        {
            if (error == null)
            {
                if (result != null && result.Type == OSDType.Map)
                {
                    OSDMap map = (OSDMap)result;
                    OSD osd;

                    LoginResponseData data = new LoginResponseData();
                    data.Parse(map);

                    if (map.TryGetValue("login", out osd))
                    {
                        bool loginSuccess = osd.AsBoolean();
                        bool redirect = (osd.AsString() == "indeterminate");

                        if (redirect)
                        {
                            // Login redirected

                            // Make the next login URL jump
                            UpdateLoginStatus(LoginStatus.Redirecting, data.Message);

                            LoginParams loginParams = CurrentContext.Value;
                            loginParams.URI = LoginResponseData.ParseString("next_url", map);
                            //CurrentContext.Params.MethodName = LoginResponseData.ParseString("next_method", map);

                            // Sleep for some amount of time while the servers work
                            int seconds = (int)LoginResponseData.ParseUInt("next_duration", map);
                            Logger.Log("Sleeping for " + seconds + " seconds during a login redirect",
                                Helpers.LogLevel.Info);
                            Thread.Sleep(seconds * 1000);

                            // Ignore next_options for now
                            CurrentContext = loginParams;

                            BeginLogin();
                        }
                        else if (loginSuccess)
                        {
                            // Login succeeded

                            // Fire the login callback
                            if (OnLoginResponse != null)
                            {
                                try { OnLoginResponse(loginSuccess, redirect, data.Message, data.Reason, data); }
                                catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
                            }

                            // These parameters are stored in NetworkManager, so instead of registering
                            // another callback for them we just set the values here
                            CircuitCode = (uint)data.CircuitCode;
                            LoginSeedCapability = data.SeedCapability;

                            UpdateLoginStatus(LoginStatus.ConnectingToSim, "Connecting to simulator...");

                            ulong handle = Utils.UIntsToLong((uint)data.RegionX, (uint)data.RegionY);

                            if (data.SimIP != null && data.SimPort != 0)
                            {
                                // Connect to the sim given in the login reply
                                if (Connect(data.SimIP, (ushort)data.SimPort, handle, true, LoginSeedCapability) != null)
                                {
                                    // Request the economy data right after login
                                    SendPacket(new EconomyDataRequestPacket());

                                    // Update the login message with the MOTD returned from the server
                                    UpdateLoginStatus(LoginStatus.Success, data.Message);
                                }
                                else
                                {
                                    UpdateLoginStatus(LoginStatus.Failed,
                                        "Unable to establish a UDP connection to the simulator");
                                }
                            }
                            else
                            {
                                UpdateLoginStatus(LoginStatus.Failed,
                                    "Login server did not return a simulator address");
                            }
                        }
                        else
                        {
                            // Login failed

                            // Make sure a usable error key is set
                            if (data.Reason != String.Empty)
                                InternalErrorKey = data.Reason;
                            else
                                InternalErrorKey = "unknown";

                            UpdateLoginStatus(LoginStatus.Failed, data.Message);
                        }
                    }
                    else
                    {
                        // Got an LLSD map but no login value
                        UpdateLoginStatus(LoginStatus.Failed, "login parameter missing in the response");
                    }
                }
                else
                {
                    // No LLSD response
                    InternalErrorKey = "bad response";
                    UpdateLoginStatus(LoginStatus.Failed, "Empty or unparseable login response");
                }
            }
            else
            {
                // Connection error
                InternalErrorKey = "no connection";
                UpdateLoginStatus(LoginStatus.Failed, error.Message);
            }
        }
Exemple #58
0
            public static TextureEntry FromOSD(OSD osd)
            {
                if (osd.Type == OSDType.Array)
                {
                    OSDArray array = (OSDArray)osd;
                    OSDMap faceSD;

                    if (array.Count > 0)
                    {
                        int faceNumber;
                        faceSD = (OSDMap)array[0];
                        TextureEntryFace defaultFace = TextureEntryFace.FromOSD(faceSD, null, out faceNumber);
                        TextureEntry te = new TextureEntry(defaultFace);

                        for (int i = 1; i < array.Count; i++)
                        {
                            TextureEntryFace tex = TextureEntryFace.FromOSD(array[i], defaultFace, out faceNumber);
                            if (faceNumber >= 0 && faceNumber < te.FaceTextures.Length)
                                te.FaceTextures[faceNumber] = tex;
                        }

                        return te;
                    }
                }

                return new TextureEntry(UUID.Zero);
            }
Exemple #59
0
        void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
        {
            // We don't care about this request now that it has completed
            _Request = null;

            OSDArray events = null;
            int ack = 0;

            if (responseData != null)
            {
                _errorCount = 0;
                // Got a response
                OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap;

                if (result != null)
                {
                    events = result["events"] as OSDArray;
                    ack = result["id"].AsInteger();
                }
                else
                {
                    Logger.Log("Got an unparseable response from the event queue: \"" +
                        System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning);
                }
            }
            else if (error != null)
            {
                #region Error handling

                HttpStatusCode code = HttpStatusCode.OK;

                if (error is WebException)
                {
                    WebException webException = (WebException)error;

                    if (webException.Response != null)
                        code = ((HttpWebResponse)webException.Response).StatusCode;
                    else if (webException.Status == WebExceptionStatus.RequestCanceled)
                        goto HandlingDone;
                }

                if (error is WebException && ((WebException)error).Response != null)
                    code = ((HttpWebResponse)((WebException)error).Response).StatusCode;

                if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone)
                {
                    Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info);

                    _Running = false;
                    _Dead = true;
                }
                else if (code == HttpStatusCode.BadGateway)
                {
                    // This is not good (server) protocol design, but it's normal.
                    // The EventQueue server is a proxy that connects to a Squid
                    // cache which will time out periodically. The EventQueue server
                    // interprets this as a generic error and returns a 502 to us
                    // that we ignore
                }
                else
                {
                    ++_errorCount;

                    // Try to log a meaningful error message
                    if (code != HttpStatusCode.OK)
                    {
                        Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}",
                            _Address, code), Helpers.LogLevel.Warning);
                    }
                    else if (error.InnerException != null)
                    {
                        Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}",
                            _Address, error.InnerException.Message), Helpers.LogLevel.Warning);
                    }
                    else
                    {
                        Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
                            _Address, error.Message), Helpers.LogLevel.Warning);
                    }
                }

                #endregion Error handling
            }
            else
            {
                ++_errorCount;

                Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning);
            }

        HandlingDone:

            #region Resume the connection

            if (_Running)
            {
                OSDMap osdRequest = new OSDMap();
                if (ack != 0) osdRequest["ack"] = OSD.FromInteger(ack);
                else osdRequest["ack"] = new OSD();
                osdRequest["done"] = OSD.FromBoolean(_Dead);

                byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest);

                if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU
                    Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount)));

                // Resume the connection. The event handler for the connection opening
                // just sets class _Request variable to the current HttpWebRequest
                CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT,
                    delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler);

                // If the event queue is dead at this point, turn it off since
                // that was the last thing we want to do
                if (_Dead)
                {
                    _Running = false;
                    Logger.DebugLog("Sent event queue shutdown message");
                }
            }

            #endregion Resume the connection

            #region Handle incoming events

            if (OnEvent != null && events != null && events.Count > 0)
            {
                // Fire callbacks for each event received
                foreach (OSDMap evt in events)
                {
                    string msg = evt["message"].AsString();
                    OSDMap body = (OSDMap)evt["body"];

                    try { OnEvent(msg, body); }
                    catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
                }
            }

            #endregion Handle incoming events
        }
Exemple #60
0
        public static object SerializeLisp(OSD osd)
        {
            switch (osd.Type)
            {
                case OSDType.Unknown:
                    throw new InvalidCastException();
                case OSDType.Boolean:
                    return osd.AsBoolean();
                case OSDType.Integer:
                    return osd.AsInteger();
                case OSDType.Real:
                    return osd.AsReal();
                case OSDType.String:
                    return osd.AsString();
                case OSDType.Date:
                    return osd.AsDate();
                case OSDType.URI:
                    return osd.AsUri();
                case OSDType.UUID:
                    return osd.AsUUID();

                case OSDType.Binary:
                    return osd.AsBinary();
                case OSDType.Array:
                    OSDArray args = (OSDArray) osd;
                    Cons ret = null;
                    for (int i = args.Count - 1; i >= 0; --i)
                    {
                        ret = new Cons(args[i], ret);
                    }
                    return ret;
                case OSDType.Map:
                    Cons list = null;
                    OSDMap map = (OSDMap) osd;
                    foreach (KeyValuePair<string, OSD> kvp in map)
                    {
                        Cons kv = new Cons(kvp.Key, new Cons(SerializeLisp(kvp.Value)));
                        list = new Cons(kv,list);
                    }
                    return Cons.Reverse(list);
                default:
                    return osd;
            }

        }