/// <summary>
        ///   Set the display name for the given user
        /// </summary>
        /// <param name = "mDhttpMethod"></param>
        /// <param name = "agentID"></param>
        /// <returns></returns>
        private Hashtable ProcessSetDisplayName(Hashtable mDhttpMethod)
        {
            try
            {
                OSDMap      rm             = (OSDMap)OSDParser.DeserializeLLSDXml((string)mDhttpMethod["requestbody"]);
                OSDArray    display_name   = (OSDArray)rm["display_name"];
                string      oldDisplayName = display_name[0].AsString();
                string      newDisplayName = display_name[1].AsString();
                UserAccount account        = m_userService.GetUserAccount(UUID.Zero, m_service.AgentID);

                //Check to see if their name contains a banned character
#if (!ISWIN)
                foreach (string bannedUserName in bannedNames)
                {
                    string BannedUserName = bannedUserName.Replace(" ", "");
                    if (newDisplayName.ToLower().Contains(BannedUserName.ToLower()))
                    {
                        //Revert the name to the original and send them a warning
                        newDisplayName = account.Name;
                        //m_avatar.ControllingClient.SendAlertMessage ("You cannot update your display name to the name chosen, your name has been reverted. This request has been logged.");
                        break; //No more checking
                    }
                }
#else
                if (bannedNames.Select(bannedUserName => bannedUserName.Replace(" ", "")).Any(BannedUserName => newDisplayName.ToLower().Contains(BannedUserName.ToLower())))
                {
                    newDisplayName = account.Name;
                }
#endif

                IUserProfileInfo info = m_profileConnector.GetUserProfile(m_service.AgentID);
                if (info == null)
                {
                    //m_avatar.ControllingClient.SendAlertMessage ("You cannot update your display name currently as your profile cannot be found.");
                }
                else
                {
                    //Set the name
                    info.DisplayName = newDisplayName;
                    m_profileConnector.UpdateUserProfile(info);

                    //One for us
                    DisplayNameUpdate(newDisplayName, oldDisplayName, account, m_service.AgentID);

#if (!ISWIN)
                    foreach (IRegionClientCapsService avatar in m_service.RegionCaps.GetClients())
                    {
                        if (avatar.AgentID != m_service.AgentID)
                        {
                            //Update all others
                            DisplayNameUpdate(newDisplayName, oldDisplayName, account, avatar.AgentID);
                        }
                    }
#else
                    foreach (IRegionClientCapsService avatar in m_service.RegionCaps.GetClients().Where(avatar => avatar.AgentID != m_service.AgentID))
                    {
                        //Update all others
                        DisplayNameUpdate(newDisplayName, oldDisplayName, account, avatar.AgentID);
                    }
#endif
                    //The reply
                    SetDisplayNameReply(newDisplayName, oldDisplayName, account);
                }
            }
            catch
            {
            }
            //Send back data
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "";

            return(responsedata);
        }
        /// <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 = GetFolderForType(item.Owner, (AssetType)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 },
                { "ContentType", invContentType },
                { "ExtraData", OSDParser.SerializeJsonString(extraData) }
            };

            OSDMap response = WebUtils.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);
        }
        public bool DoHelloNeighbourCall(GridRegion region, RegionInfo thisRegion)
        {
            string uri = region.ServerURI + "region/" + thisRegion.RegionID + "/";
            //            m_log.Debug("   >>> DoHelloNeighbourCall <<< " + uri);

            WebRequest helloNeighbourRequest;

            try
            {
                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 #4
0
        public string FetchInventoryRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            //m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capability request {0}", request);

            OSDMap   requestmap     = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
            OSDArray itemsRequested = (OSDArray)requestmap["items"];

            UUID[] itemIDs = new UUID[itemsRequested.Count];
            int    i       = 0;

            foreach (OSDMap osdItemId in itemsRequested)
            {
                itemIDs[i++] = osdItemId["item_id"].AsUUID();
            }

            InventoryItemBase[] items = null;

            if (m_agentID != UUID.Zero)
            {
                items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs);
            }
            else
            {
                items = new InventoryItemBase[itemsRequested.Count];
                foreach (UUID id in itemIDs)
                {
                    items[i++] = m_inventoryService.GetItem(UUID.Zero, id);
                }
            }

            osUTF8 lsl = LLSDxmlEncode2.Start(4096);

            LLSDxmlEncode2.AddMap(lsl);

            if (m_agentID == UUID.Zero && items.Length > 0)
            {
                LLSDxmlEncode2.AddElem("agent_id", items[0].Owner, lsl);
            }
            else
            {
                LLSDxmlEncode2.AddElem("agent_id", m_agentID, lsl);
            }

            if (items == null || items.Length == 0)
            {
                LLSDxmlEncode2.AddEmptyArray("items", lsl);
            }
            else
            {
                LLSDxmlEncode2.AddArray("items", lsl);
                foreach (InventoryItemBase item in items)
                {
                    if (item != null)
                    {
                        item.ToLLSDxml(lsl, 0xff);
                    }
                }
                LLSDxmlEncode2.AddEndArray(lsl);
            }

            LLSDxmlEncode2.AddEndMap(lsl);
            return(LLSDxmlEncode2.End(lsl));
        }
Exemple #5
0
        private void RequestAvatarPropertiesHandler(IClientAPI client, UUID avatarID)
        {
            OSDMap user = FetchUserData(avatarID);

            ProfileFlags flags = ProfileFlags.AllowPublish | ProfileFlags.MaturePublish;

            if (user != null)
            {
                OSDMap about = null;
                if (user.ContainsKey("LLAbout"))
                {
                    try { about = OSDParser.DeserializeJson(user["LLAbout"].AsString()) as OSDMap; }
                    catch { }
                }

                if (about == null)
                {
                    about = new OSDMap(0);
                }

                // Check if this user is a grid operator
                byte[] charterMember;
                if (user["AccessLevel"].AsInteger() >= 200)
                {
                    charterMember = Utils.StringToBytes("Operator");
                }
                else
                {
                    charterMember = Utils.EmptyBytes;
                }

                // Check if the user is online
                if (client.Scene is Scene)
                {
                    OpenSim.Services.Interfaces.PresenceInfo[] presences = ((Scene)client.Scene).PresenceService.GetAgents(new string[] { avatarID.ToString() });
                    if (presences != null && presences.Length > 0)
                    {
                        flags |= ProfileFlags.Online;
                    }
                }

                // Check if the user is identified
                if (user["Identified"].AsBoolean())
                {
                    flags |= ProfileFlags.Identified;
                }

                client.SendAvatarProperties(avatarID, about["About"].AsString(), user["CreationDate"].AsDate().ToString("M/d/yyyy",
                                                                                                                        System.Globalization.CultureInfo.InvariantCulture), charterMember, about["FLAbout"].AsString(), (uint)flags,
                                            about["FLImage"].AsUUID(), about["Image"].AsUUID(), about["URL"].AsString(), user["Partner"].AsUUID());

                OSDMap interests = null;
                if (user.ContainsKey("LLInterests"))
                {
                    try
                    {
                        interests = OSDParser.DeserializeJson(user["LLInterests"].AsString()) as OSDMap;
                        client.SendAvatarInterestsReply(avatarID, interests["WantMask"].AsUInteger(), interests["WantText"].AsString(), interests["SkillsMask"].AsUInteger(), interests["SkillsText"].AsString(), interests["languages"].AsString());
                    }
                    catch { }
                }

                if (about == null)
                {
                    about = new OSDMap(0);
                }
            }
            else
            {
                m_log.Warn("[SIMIAN PROFILES]: Failed to fetch profile information for " + client.Name + ", returning default values");
                client.SendAvatarProperties(avatarID, String.Empty, "1/1/1970", Utils.EmptyBytes,
                                            String.Empty, (uint)flags, UUID.Zero, UUID.Zero, String.Empty, UUID.Zero);
            }
        }
            public void SaveModuleToArchive(TarArchiveWriter writer, IScene scene)
            {
                m_isArchiving = true;

                MainConsole.Instance.Info("[Archive]: Writing parcels to archive");

                writer.WriteDir("parcels");

                IParcelManagementModule module = scene.RequestModuleInterface <IParcelManagementModule> ();

                if (module != null)
                {
                    List <ILandObject> landObject = module.AllParcels();
                    foreach (ILandObject parcel in landObject)
                    {
                        OSDMap parcelMap = parcel.LandData.ToOSD();
                        writer.WriteFile("parcels/" + parcel.LandData.GlobalID,
                                         OSDParser.SerializeLLSDBinary(parcelMap));
                    }
                }

                MainConsole.Instance.Info("[Archive]: Finished writing parcels to archive");
                MainConsole.Instance.Info("[Archive]: Writing terrain to archive");

                writer.WriteDir("newstyleterrain");
                writer.WriteDir("newstylerevertterrain");

                writer.WriteDir("newstylewater");
                writer.WriteDir("newstylerevertwater");

                ITerrainModule tModule = scene.RequestModuleInterface <ITerrainModule> ();

                if (tModule != null)
                {
                    try {
                        byte [] sdata = WriteTerrainToStream(tModule.TerrainMap);
                        writer.WriteFile("newstyleterrain/" + scene.RegionInfo.RegionID + ".terrain", sdata);

                        sdata = WriteTerrainToStream(tModule.TerrainRevertMap);
                        writer.WriteFile("newstylerevertterrain/" + scene.RegionInfo.RegionID + ".terrain",
                                         sdata);
                        sdata = null;

                        if (tModule.TerrainWaterMap != null)
                        {
                            sdata = WriteTerrainToStream(tModule.TerrainWaterMap);
                            writer.WriteFile("newstylewater/" + scene.RegionInfo.RegionID + ".terrain", sdata);

                            sdata = WriteTerrainToStream(tModule.TerrainWaterRevertMap);
                            writer.WriteFile(
                                "newstylerevertwater/" + scene.RegionInfo.RegionID + ".terrain", sdata);
                            sdata = null;
                        }
                    } catch (Exception ex) {
                        MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                    }
                }

                MainConsole.Instance.Info("[Archive]: Finished writing terrain to archive");
                MainConsole.Instance.Info("[Archive]: Writing entities to archive");
                ISceneEntity [] entities = scene.Entities.GetEntities();
                //Get all entities, then start writing them to the database
                writer.WriteDir("entities");

                IDictionary <UUID, AssetType> assets  = new Dictionary <UUID, AssetType> ();
                UuidGatherer            assetGatherer = new UuidGatherer(m_scene.AssetService);
                IUniverseBackupArchiver archiver      = m_scene.RequestModuleInterface <IUniverseBackupArchiver> ();
                bool saveAssets = false;

                if (archiver.AllowPrompting)
                {
                    saveAssets =
                        MainConsole.Instance.Prompt("Save assets? (Will not be able to load on other grids if not saved)", "false")
                        .Equals("true", StringComparison.CurrentCultureIgnoreCase);
                }

                int count = 0;

                foreach (ISceneEntity entity in entities)
                {
                    try {
                        if (entity.IsAttachment ||
                            ((entity.RootChild.Flags & PrimFlags.Temporary) == PrimFlags.Temporary) ||
                            ((entity.RootChild.Flags & PrimFlags.TemporaryOnRez) == PrimFlags.TemporaryOnRez))
                        {
                            continue;
                        }

                        //Write all entities
                        byte [] xml = entity.ToBinaryXml2();
                        writer.WriteFile("entities/" + entity.UUID, xml);
                        xml = null;
                        count++;
                        if (count % 3 == 0)
                        {
                            Thread.Sleep(5);
                        }

                        //Get all the assets too
                        if (saveAssets)
                        {
                            assetGatherer.GatherAssetUuids(entity, assets);
                        }
                    } catch (Exception ex) {
                        MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                    }
                }
                entities = null;

                MainConsole.Instance.Info("[Archive]: Finished writing entities to archive");
                MainConsole.Instance.Info("[Archive]: Writing assets for entities to archive");

                bool foundAllAssets = true;

                foreach (UUID assetID in new List <UUID> (assets.Keys))
                {
                    try {
                        foundAllAssets = false; //Not all are cached
                        m_scene.AssetService.Get(assetID.ToString(), writer, RetrievedAsset);
                        m_missingAssets.Add(assetID);
                    } catch (Exception ex) {
                        MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                    }
                }
                if (foundAllAssets)
                {
                    m_isArchiving = false; //We're done if all the assets were found
                }
                MainConsole.Instance.Info("[Archive]: Finished writing assets for entities to archive");
            }
        public Hashtable GetEvents(UUID requestID, UUID pAgentId)
        {
            if (DebugLevel >= 2)
            {
                m_log.WarnFormat("POLLED FOR EQ MESSAGES BY {0} in {1}", pAgentId, m_scene.Name);
            }

            Queue <OSD> queue = GetQueue(pAgentId);

            if (queue == null)
            {
                return(NoEvents(requestID, pAgentId));
            }

            OSD      element    = null;;
            OSDArray array      = new OSDArray();
            int      thisID     = 0;
            bool     negativeID = false;

            lock (queue)
            {
                if (queue.Count == 0)
                {
                    return(NoEvents(requestID, pAgentId));
                }

                lock (m_ids)
                    thisID = m_ids[pAgentId];

                if (thisID < 0)
                {
                    negativeID = true;
                    thisID     = -thisID;
                }

                while (queue.Count > 0)
                {
                    element = queue.Dequeue();
                    // add elements until a marker is found
                    // so they get into a response
                    if (element == null)
                    {
                        break;
                    }

                    if (DebugLevel > 0)
                    {
                        LogOutboundDebugMessage(element, pAgentId);
                    }
                    array.Add(element);
                }
            }

            lock (m_ids)
            {
                if (element == null && negativeID)
                {
                    Random rnd = new Random(Environment.TickCount);
                    m_ids[pAgentId] = rnd.Next(30000000);
                }
                else
                {
                    m_ids[pAgentId] = thisID + 1;
                }
            }

            if (array.Count == 0)
            {
                return(NoEvents(requestID, pAgentId));
            }

            OSDMap events = new OSDMap();

            events.Add("events", array);
            events.Add("id", new OSDInteger(thisID));

            Hashtable responsedata = new Hashtable();

            responsedata["int_response_code"] = 200;
            responsedata["content_type"]      = "application/xml";
//string tt = OSDParser.SerializeLLSDXmlString(events);
            responsedata["bin_response_data"] = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(events));

            //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", pAgentId, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
            return(responsedata);
        }
Exemple #8
0
 public virtual bool Enqueue(OSD o, UUID agentID, UUID regionID)
 {
     return(Enqueue(OSDParser.SerializeLLSDXmlString(o), agentID, regionID));
 }
        public override void FinishedMigration(IDataConnector genericData)
        {
            if (!genericData.TableExists("estates"))
            {
                return;
            }
            DataReaderConnection dr = genericData.QueryData("WHERE `Key` = 'EstateID'", "estates",
                                                            "`ID`, `Key`, `Value`");

            if (dr != null)
            {
                try
                {
                    while (dr.DataReader.Read())
                    {
                        try
                        {
                            UUID        ID     = UUID.Parse(dr.DataReader["ID"].ToString());
                            string      value  = dr.DataReader["Value"].ToString();
                            QueryFilter filter = new QueryFilter();
                            filter.andFilters["`ID`"]  = value;
                            filter.andFilters["`Key`"] = "EstateSettings";
                            List <string> results = genericData.Query(new string[1] {
                                "`Value`"
                            }, "estates", filter, null,
                                                                      null, null);
                            if ((results != null) && (results.Count >= 1))
                            {
                                EstateSettings es = new EstateSettings();
                                es.FromOSD((OSDMap)OSDParser.DeserializeLLSDXml(results[0]));
                                genericData.Insert("estateregions", new object[] { ID, value });

                                filter = new QueryFilter();
                                filter.andFilters["`EstateID`"] = value;

                                List <string> exist = genericData.Query(new string[1] {
                                    "`EstateID`"
                                }, "estatesettings",
                                                                        filter, null, null, null);
                                if (exist == null || exist.Count == 0)
                                {
                                    genericData.Insert("estatesettings",
                                                       new object[]
                                    {
                                        value, es.EstateName, es.EstateOwner, es.ParentEstateID,
                                        es.ToOSD()
                                    });
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                catch
                {
                }
                finally
                {
                    dr.DataReader.Close();
                    genericData.CloseDatabase(dr);
                }
            }
        }
 public static string ToXmlString(Packet packet)
 {
     return(OSDParser.SerializeLLSDXmlString(GetLLSD(packet)));
 }
 public static byte[] ToBinary(Packet packet)
 {
     return(OSDParser.SerializeLLSDBinary(GetLLSD(packet)));
 }
        /// <summary>
        ///   Unpack agent circuit data map into an AgentCiruitData object
        /// </summary>
        /// <param name = "args"></param>
        public virtual void UnpackAgentCircuitData(OSDMap args)
        {
            if (args["agent_id"] != null)
            {
                AgentID = args["agent_id"].AsUUID();
            }
            if (args["caps_path"] != null)
            {
                CapsPath = args["caps_path"].AsString();
            }
            if (args["reallyischild"] != null)
            {
                reallyischild = args["reallyischild"].AsBoolean();
            }
            if (args["child"] != null)
            {
                child = args["child"].AsBoolean();
            }
            if (args["circuit_code"] != null)
            {
                UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode);
            }
            if (args["secure_session_id"] != null)
            {
                SecureSessionID = args["secure_session_id"].AsUUID();
            }
            if (args["session_id"] != null)
            {
                SessionID = args["session_id"].AsUUID();
            }
            if (args["service_session_id"] != null)
            {
                ServiceSessionID = args["service_session_id"].AsString();
            }
            if (args["client_ip"] != null)
            {
                IPAddress = args["client_ip"].AsString();
            }
            if (args["first_name"] != null)
            {
                firstname = args["first_name"].AsString();
            }
            if (args["last_name"] != null)
            {
                lastname = args["last_name"].AsString();
            }

            if (args["start_pos"] != null)
            {
                Vector3.TryParse(args["start_pos"].AsString(), out startpos);
            }

            if (args["teleport_flags"] != null)
            {
                teleportFlags = args["teleport_flags"].AsUInteger();
            }
            if (args["draw_distance"] != null)
            {
                DrawDistance = args["draw_distance"];
            }

            // DEBUG ON
            //MainConsole.Instance.WarnFormat("[AGENTCIRCUITDATA] agentid={0}, child={1}, startpos={2}", AgentID, child, startpos.ToString());
            // DEBUG OFF

            try
            {
                // Unpack various appearance elements
                Appearance = new AvatarAppearance(AgentID);

                // Eventually this code should be deprecated, use full appearance
                // packing in packed_appearance
                if (args["appearance_serial"] != null)
                {
                    Appearance.Serial = args["appearance_serial"].AsInteger();
                }

                if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map))
                {
                    Appearance.Unpack((OSDMap)args["packed_appearance"]);
                    // DEBUG ON
                    //MainConsole.Instance.WarnFormat("[AGENTCIRCUITDATA] unpacked appearance");
                    // DEBUG OFF
                }
                // DEBUG ON
                else
                {
                    MainConsole.Instance.Warn("[AGENTCIRCUITDATA] failed to find a valid packed_appearance, dne ? " +
                                              !args.ContainsKey("packed_appearance"));
                }
                // DEBUG OFF
            }
            catch (Exception e)
            {
                MainConsole.Instance.ErrorFormat("[AGENTCIRCUITDATA] failed to unpack appearance; {0}", e);
            }

            if (args.ContainsKey("otherInfo"))
            {
                OtherInformation = (OSDMap)OSDParser.DeserializeLLSDXml(args["otherInfo"].AsString());
            }

            ServiceURLs = new Dictionary <string, object>();
            // Try parse the new way, OSDMap
            if (args.ContainsKey("serviceurls") && args["serviceurls"] != null &&
                (args["serviceurls"]).Type == OSDType.Map)
            {
                OSDMap urls = (OSDMap)(args["serviceurls"]);
                foreach (KeyValuePair <String, OSD> kvp in urls)
                {
                    ServiceURLs[kvp.Key] = kvp.Value.AsString();
                    //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]);
                }
            }
        }
        private bool AddToQueue(OSD ev, UUID avatarID, ulong regionHandle, bool runasync)
        {
            //MainConsole.Instance.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);

            if (ev == null)
            {
                return(false);
            }
            try
            {
                OSDMap request = new OSDMap {
                    { "AgentID", avatarID }, { "RegionHandle", regionHandle }
                };
                OSDArray events = new OSDArray {
                    OSDParser.SerializeLLSDXmlString(ev)
                };
                //Note: we HAVE to convert it to xml, otherwise things like byte[] arrays will not be passed through correctly!

                request.Add("Events", events);

                IConfigurationService configService = m_registry.RequestModuleInterface <IConfigurationService>();
                List <string>         serverURIs    = configService.FindValueOf(avatarID.ToString(), regionHandle.ToString(),
                                                                                "EventQueueServiceURI");
                foreach (string serverURI in serverURIs)
                {
                    if (serverURI != "")
                    {
                        if (runasync)
                        {
                            /*AsynchronousRestObjectRequester.MakeRequest("POST", serverURI + "/CAPS/EQMPOSTER",
                             * OSDParser.SerializeJsonString(request),
                             * delegate(string resp)
                             * {
                             *  return RequestHandler(resp, events, avatarID, regionHandle);
                             * });
                             *
                             * return true;*/
                            string resp = SynchronousRestFormsRequester.MakeRequest("POST", serverURI + "/CAPS/EQMPOSTER", OSDParser.SerializeJsonString(request));
                            return(RequestHandler(resp, events, avatarID, regionHandle));
                        }
                        else
                        {
                            string resp = SynchronousRestFormsRequester.MakeRequest("POST", serverURI + "/CAPS/EQMPOSTER", OSDParser.SerializeJsonString(request));
                            return(RequestHandler(resp, events, avatarID, regionHandle));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MainConsole.Instance.Error("[EVENTQUEUE] Caught exception: " + e);
            }

            return(false);
        }
        /// <summary>
        ///   Get the user's display name, currently not used?
        /// </summary>
        /// <param name = "mDhttpMethod"></param>
        /// <param name = "agentID"></param>
        /// <returns></returns>
        private byte[] ProcessGetDisplayName(string path, Stream request, OSHttpRequest httpRequest,
                                             OSHttpResponse httpResponse)
        {
            //I've never seen this come in, so for now... do nothing
            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);

            string[] ids      = query.GetValues("ids");
            string   username = query.GetOne("username");

            OSDMap   map           = new OSDMap();
            OSDArray agents        = new OSDArray();
            OSDArray bad_ids       = new OSDArray();
            OSDArray bad_usernames = new OSDArray();

            if (ids != null)
            {
                foreach (string id in ids)
                {
                    UserAccount account = m_userService.GetUserAccount(UUID.Zero, UUID.Parse(id));
                    if (account != null)
                    {
                        IUserProfileInfo info =
                            DataManager.RequestPlugin <IProfileConnector>().GetUserProfile(account.PrincipalID);
                        if (info != null)
                        {
                            PackUserInfo(info, account, ref agents);
                        }
                        else
                        {
                            PackUserInfo(info, account, ref agents);
                        }
                        //else //Technically is right, but needs to be packed no matter what for OS based grids
                        //    bad_ids.Add (id);
                    }
                }
            }
            else if (username != null)
            {
                UserAccount account = m_userService.GetUserAccount(UUID.Zero, username.Replace('.', ' '));
                if (account != null)
                {
                    IUserProfileInfo info =
                        DataManager.RequestPlugin <IProfileConnector>().GetUserProfile(account.PrincipalID);
                    if (info != null)
                    {
                        PackUserInfo(info, account, ref agents);
                    }
                    else
                    {
                        bad_usernames.Add(username);
                    }
                }
            }

            map["agents"]        = agents;
            map["bad_ids"]       = bad_ids;
            map["bad_usernames"] = bad_usernames;

            byte[] m = OSDParser.SerializeLLSDXmlBytes(map);
            httpResponse.Body.Write(m, 0, m.Length);
            httpResponse.StatusCode = (int)HttpStatusCode.OK;
            httpResponse.Send();
            return(null);
        }
Exemple #15
0
        private bool UpdateAgent(GridRegion destination, IAgentData cAgentData)
        {
            // Try local first
            if (cAgentData is AgentData)
            {
                if (m_localBackend.UpdateAgent(destination, (AgentData)cAgentData))
                {
                    return(true);
                }
            }
            else if (cAgentData is AgentPosition)
            {
                if (m_localBackend.UpdateAgent(destination, (AgentPosition)cAgentData))
                {
                    return(true);
                }
            }

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
            {
                // Eventually, we want to use a caps url instead of the agentID
                string uri = MakeUri(destination, true) + cAgentData.AgentID + "/";

                if (m_blackListedRegions.ContainsKey(uri))
                {
                    //Check against time
                    if (m_blackListedRegions[uri] > 3 &&
                        Util.EnvironmentTickCountSubtract(m_blackListedRegions[uri]) > 0)
                    {
                        MainConsole.Instance.Warn("[SimServiceConnector]: Blacklisted region " + destination.RegionName + " requested");
                        //Still blacklisted
                        return(false);
                    }
                }
                try
                {
                    OSDMap args = cAgentData.Pack();

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

                    string result = WebUtils.PutToService(uri, args);
                    if (result == "")
                    {
                        if (m_blackListedRegions.ContainsKey(uri))
                        {
                            if (m_blackListedRegions[uri] == 3)
                            {
                                //add it to the blacklist as the request completely failed 3 times
                                m_blackListedRegions[uri] = Util.EnvironmentTickCount() + 60 * 1000; //60 seconds
                            }
                            else if (m_blackListedRegions[uri] == 0)
                            {
                                m_blackListedRegions[uri]++;
                            }
                        }
                        else
                        {
                            m_blackListedRegions[uri] = 0;
                        }
                        return(false);
                    }
                    //Clear out the blacklist if it went through
                    m_blackListedRegions.Remove(uri);

                    OSDMap innerResult = (OSDMap)OSDParser.DeserializeJson(result);
                    return(innerResult["Updated"].AsBoolean());
                }
                catch (Exception e)
                {
                    MainConsole.Instance.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e);
                }

                return(false);
            }

            return(false);
        }
Exemple #16
0
        public void DeserializeUndef()
        {
            OSD llsdUndef = OSDParser.DeserializeLLSDBinary(binaryUndef);

            Assert.AreEqual(OSDType.Unknown, llsdUndef.Type);
        }
Exemple #17
0
        private UserSession ParseViewerStats(string request, UUID agentID)
        {
            UserSession     uid = new UserSession();
            UserSessionData usd;
            OSD             message = OSDParser.DeserializeLLSDXml(request);
            OSDMap          mmap;

            lock (m_sessions)
            {
                if (agentID != UUID.Zero)
                {
                    if (!m_sessions.ContainsKey(agentID))
                    {
                        m_log.WarnFormat("[WEB STATS MODULE]: no session for stat disclosure for agent {0}", agentID);
                        return(new UserSession());
                    }

                    uid = m_sessions[agentID];

//                    m_log.DebugFormat("[WEB STATS MODULE]: Got session {0} for {1}", uid.session_id, agentID);
                }
                else
                {
                    // parse through the beginning to locate the session
                    if (message.Type != OSDType.Map)
                    {
                        return(new UserSession());
                    }

                    mmap = (OSDMap)message;
                    {
                        UUID sessionID = mmap["session_id"].AsUUID();

                        if (sessionID == UUID.Zero)
                        {
                            return(new UserSession());
                        }


                        // search through each session looking for the owner
                        foreach (UUID usersessionid in m_sessions.Keys)
                        {
                            // got it!
                            if (m_sessions[usersessionid].session_id == sessionID)
                            {
                                agentID = usersessionid;
                                uid     = m_sessions[usersessionid];
                                break;
                            }
                        }

                        // can't find a session
                        if (agentID == UUID.Zero)
                        {
                            return(new UserSession());
                        }
                    }
                }
            }

            usd = uid.session_data;

            if (message.Type != OSDType.Map)
            {
                return(new UserSession());
            }

            mmap = (OSDMap)message;
            {
                if (mmap["agent"].Type != OSDType.Map)
                {
                    return(new UserSession());
                }
                OSDMap agent_map = (OSDMap)mmap["agent"];
                usd.agent_id        = agentID;
                usd.name_f          = uid.name_f;
                usd.name_l          = uid.name_l;
                usd.region_id       = uid.region_id;
                usd.a_language      = agent_map["language"].AsString();
                usd.mem_use         = (float)agent_map["mem_use"].AsReal();
                usd.meters_traveled = (float)agent_map["meters_traveled"].AsReal();
                usd.regions_visited = agent_map["regions_visited"].AsInteger();
                usd.run_time        = (float)agent_map["run_time"].AsReal();
                usd.start_time      = (float)agent_map["start_time"].AsReal();
                usd.client_version  = agent_map["version"].AsString();

                UserSessionUtil.UpdateMultiItems(ref usd, agent_map["agents_in_view"].AsInteger(),
                                                 (float)agent_map["ping"].AsReal(),
                                                 (float)agent_map["sim_fps"].AsReal(),
                                                 (float)agent_map["fps"].AsReal());

                if (mmap["downloads"].Type != OSDType.Map)
                {
                    return(new UserSession());
                }
                OSDMap downloads_map = (OSDMap)mmap["downloads"];
                usd.d_object_kb  = (float)downloads_map["object_kbytes"].AsReal();
                usd.d_texture_kb = (float)downloads_map["texture_kbytes"].AsReal();
                usd.d_world_kb   = (float)downloads_map["workd_kbytes"].AsReal();

//                m_log.DebugFormat("[WEB STATS MODULE]: mmap[\"session_id\"] = [{0}]", mmap["session_id"].AsUUID());

                usd.session_id = mmap["session_id"].AsUUID();

                if (mmap["system"].Type != OSDType.Map)
                {
                    return(new UserSession());
                }
                OSDMap system_map = (OSDMap)mmap["system"];

                usd.s_cpu = system_map["cpu"].AsString();
                usd.s_gpu = system_map["gpu"].AsString();
                usd.s_os  = system_map["os"].AsString();
                usd.s_ram = system_map["ram"].AsInteger();

                if (mmap["stats"].Type != OSDType.Map)
                {
                    return(new UserSession());
                }

                OSDMap stats_map = (OSDMap)mmap["stats"];
                {
                    if (stats_map["failures"].Type != OSDType.Map)
                    {
                        return(new UserSession());
                    }
                    OSDMap stats_failures = (OSDMap)stats_map["failures"];
                    usd.f_dropped        = stats_failures["dropped"].AsInteger();
                    usd.f_failed_resends = stats_failures["failed_resends"].AsInteger();
                    usd.f_invalid        = stats_failures["invalid"].AsInteger();
                    usd.f_resent         = stats_failures["resent"].AsInteger();
                    usd.f_send_packet    = stats_failures["send_packet"].AsInteger();

                    if (stats_map["net"].Type != OSDType.Map)
                    {
                        return(new UserSession());
                    }
                    OSDMap stats_net = (OSDMap)stats_map["net"];
                    {
                        if (stats_net["in"].Type != OSDType.Map)
                        {
                            return(new UserSession());
                        }

                        OSDMap net_in = (OSDMap)stats_net["in"];
                        usd.n_in_kb = (float)net_in["kbytes"].AsReal();
                        usd.n_in_pk = net_in["packets"].AsInteger();

                        if (stats_net["out"].Type != OSDType.Map)
                        {
                            return(new UserSession());
                        }
                        OSDMap net_out = (OSDMap)stats_net["out"];

                        usd.n_out_kb = (float)net_out["kbytes"].AsReal();
                        usd.n_out_pk = net_out["packets"].AsInteger();
                    }
                }
            }

            uid.session_data    = usd;
            m_sessions[agentID] = uid;

//            m_log.DebugFormat(
//                "[WEB STATS MODULE]: Parse data for {0} {1}, session {2}", uid.name_f, uid.name_l, uid.session_id);

            return(uid);
        }
Exemple #18
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);
        }
Exemple #19
0
            public void LoadModuleFromArchive(byte [] data, string filePath, TarArchiveReader.TarEntryType type,
                                              IScene scene)
            {
                if (filePath.StartsWith("parcels/", StringComparison.Ordinal))
                {
                    if (!m_merge)
                    {
                        //Only use if we are not merging
                        LandData parcel     = new LandData();
                        OSD      parcelData = OSDParser.DeserializeLLSDBinary(data);
                        parcel.FromOSD((OSDMap)parcelData);
                        m_parcels.Add(parcel);
                    }
                }
                #region New Style Terrain Loading

                else if (filePath.StartsWith("newstyleterrain/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();
                    terrainModule.TerrainMap = ReadTerrain(data, scene);
                }
                else if (filePath.StartsWith("newstylerevertterrain/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();
                    terrainModule.TerrainRevertMap = ReadTerrain(data, scene);
                }
                else if (filePath.StartsWith("newstylewater/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();
                    terrainModule.TerrainWaterMap = ReadTerrain(data, scene);
                }
                else if (filePath.StartsWith("newstylerevertwater/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();
                    terrainModule.TerrainWaterRevertMap = ReadTerrain(data, scene);
                }
                #endregion
                #region Old Style Terrain Loading

                else if (filePath.StartsWith("terrain/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                else if (filePath.StartsWith("revertterrain/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadRevertMapFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                else if (filePath.StartsWith("water/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadWaterFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                else if (filePath.StartsWith("revertwater/", StringComparison.Ordinal))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule> ();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadWaterRevertMapFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                #endregion

                else if (filePath.StartsWith("entities/", StringComparison.Ordinal))
                {
                    MemoryStream ms          = new MemoryStream(data);
                    ISceneEntity sceneObject = SceneEntitySerializer.SceneObjectSerializer.FromXml2Format(ref ms, scene);
                    ms.Close();
                    m_groups.Add(sceneObject);
                }
                else if (filePath.StartsWith("assets/", StringComparison.Ordinal))
                {
                    if (m_loadAssets)
                    {
                        AssetBase asset = new AssetBase();
                        asset.Unpack(OSDParser.DeserializeJson(Encoding.UTF8.GetString(data)));
                        scene.AssetService.Store(asset);
                    }
                }
            }
Exemple #20
0
        protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID)
        {
            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]);
                }
            }

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

            resp["success"] = OSD.FromBoolean(result);
            resp["reason"]  = OSD.FromString(reason);
            string legacyVersion = String.Format("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 #21
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
                if (OSDParser.DeserializeLLSDXml(responseData) is OSDMap result)
                {
                    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)
                {
                    // Filter out some of the status requests to skip handling
                    switch (webException.Status)
                    {
                    case WebExceptionStatus.RequestCanceled:
                    case WebExceptionStatus.KeepAliveFailure:
                        goto HandlingDone;
                    }

                    if (webException.Response != null)
                    {
                        code = ((HttpWebResponse)webException.Response).StatusCode;
                    }
                }

                switch (code)
                {
                case HttpStatusCode.NotFound:
                case HttpStatusCode.Gone:
                    Logger.Log($"Closing event queue at {_Address} due to missing caps URI", Helpers.LogLevel.Info);

                    _Running = false;
                    _Dead    = true;
                    break;

                case (HttpStatusCode)499:     // weird error returned occasionally, ignore for now
                case 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
                    break;

                default:
                    ++_errorCount;

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

                #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(Math.Min(REQUEST_BACKOFF_SECONDS + _errorCount * REQUEST_BACKOFF_SECONDS_INC, REQUEST_BACKOFF_SECONDS_MAX));
                }

                // Resume the connection. The event handler for the connection opening
                // just sets class _Request variable to the current HttpWebRequest
                CapsBase.UploadDataAsync(_Address, null, REQUEST_CONTENT_TYPE, 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)
            {
                return;
            }
            // Fire callbacks for each event received
            foreach (var osd in events)
            {
                var    evt  = (OSDMap)osd;
                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 #22
0
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            EntityTransferContext ctx = new EntityTransferContext();

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

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

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

            AgentDestinationData data = CreateAgentDestinationData();

            UnpackData(args, data, request);

            GridRegion destination = new GridRegion();

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

            GridRegion gatekeeper = ExtractGatekeeper(data);

            AgentCircuitData aCircuit = new AgentCircuitData();

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

            GridRegion source = null;

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

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

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

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

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

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

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
Exemple #23
0
        public void ExportToFile(string filename, uint localID)
        {
            Primitive exportPrim;
            uint      localid;

            ExportDirectory = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename));
            Directory.CreateDirectory(ExportDirectory);

            exportPrim = Client.Network.CurrentSim.ObjectsPrimitives.Find(
                delegate(Primitive prim) { return(prim.LocalID == localID); }
                );

            if (exportPrim != null)
            {
                if (exportPrim.ParentID != 0)
                {
                    localid = exportPrim.ParentID;
                }
                else
                {
                    localid = exportPrim.LocalID;
                }

                uLocalID = localid;
                // Check for export permission first
                Client.Objects.RequestObjectPropertiesFamily(Client.Network.CurrentSim, exportPrim.ID);
                GotPermissionsEvent.WaitOne(1000 * 10, false);

                if (!GotPermissions)
                {
                    throw new Exception("Couldn't fetch permissions for the requested object, try again");
                }
                else
                {
                    GotPermissions = false;

                    // Must be Owner and Creator of the item to export, per Linden Lab's TOS
                    if (!(Properties.CreatorID == Client.Self.AgentID &&
                          Properties.OwnerID == Client.Self.AgentID))
                    {
                        string msg = "That object is owned by {0}, Created by {1} we don't have permission to export it. Your UUID: {2}";
                        throw new Exception(String.Format(msg, Properties.OwnerID, Properties.CreatorID, Client.Self.AgentID));
                    }

                    List <Primitive> prims = Client.Network.CurrentSim.ObjectsPrimitives.FindAll(
                        delegate(Primitive prim)
                    {
                        return(prim.LocalID == localid || prim.ParentID == localid);
                    }
                        );

                    bool complete = RequestObjectProperties(prims, 250);

                    string output = OSDParser.SerializeLLSDXmlString(Helpers.PrimListToOSD(prims));
                    File.WriteAllText(filename, output);

                    List <ImageRequest> textureRequests = new List <ImageRequest>();

                    lock (Textures)
                    {
                        for (int i = 0; i < prims.Count; i++)
                        {
                            Primitive prim = prims[i];
                            UUID      texture;

                            if (prim.Textures.DefaultTexture.TextureID != Primitive.TextureEntry.WHITE_TEXTURE &&
                                !Textures.Contains(prim.Textures.DefaultTexture.TextureID))
                            {
                                texture = new UUID(prim.Textures.DefaultTexture.TextureID);
                                Textures.Add(texture);
                            }

                            for (int j = 0; j < prim.Textures.FaceTextures.Length; j++)
                            {
                                if (prim.Textures.FaceTextures[j] != null &&
                                    prim.Textures.FaceTextures[j].TextureID != Primitive.TextureEntry.WHITE_TEXTURE &&
                                    !Textures.Contains(prim.Textures.FaceTextures[j].TextureID))
                                {
                                    texture = new UUID(prim.Textures.FaceTextures[j].TextureID);
                                    Textures.Add(texture);
                                }
                            }

                            if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero && !Textures.Contains(prim.Sculpt.SculptTexture))
                            {
                                texture = new UUID(prim.Sculpt.SculptTexture);
                                Textures.Add(texture);
                            }
                        }

                        FindImagesInInventory();

                        for (int i = 0; i < Textures.Count; i++)
                        {
                            textureRequests.Add(new ImageRequest(Textures[i], ImageType.Normal, 1013000.0f, 0));
                        }

                        foreach (ImageRequest request in textureRequests)
                        {
                            Client.Assets.RequestImage(request.ImageID, request.Type, Assets_OnImageReceived);
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Couldn't find id " + localID.ToString() + " in the " +
                                    Client.Network.CurrentSim.ObjectsPrimitives.Count +
                                    " objects currently indexed in the current simulator.");
            }
        }
Exemple #24
0
        /// <summary>
        ///   Save a backup of the sim
        /// </summary>
        /// <param name = "appendedFilePath">The file path where the backup will be saved</param>
        protected virtual void SaveBackup(string appendedFilePath, bool saveAssets)
        {
            if (appendedFilePath == "/")
            {
                appendedFilePath = "";
            }
            if (m_scene.RegionInfo.HasBeenDeleted)
            {
                return;
            }
            IBackupModule backupModule = m_scene.RequestModuleInterface <IBackupModule>();

            if (backupModule != null && backupModule.LoadingPrims) //Something is changing lots of prims
            {
                MainConsole.Instance.Info("[Backup]: Not saving backup because the backup module is loading prims");
                return;
            }

            //Save any script state saves that might be around
            IScriptModule[] engines = m_scene.RequestModuleInterfaces <IScriptModule>();
            try
            {
                if (engines != null)
                {
#if (!ISWIN)
                    foreach (IScriptModule engine in engines)
                    {
                        if (engine != null)
                        {
                            engine.SaveStateSaves();
                        }
                    }
#else
                    foreach (IScriptModule engine in engines.Where(engine => engine != null))
                    {
                        engine.SaveStateSaves();
                    }
#endif
                }
            }
            catch (Exception ex)
            {
                MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
            }

            MainConsole.Instance.Info("[FileBasedSimulationData]: Saving backup for region " + m_scene.RegionInfo.RegionName);
            string fileName = appendedFilePath + m_scene.RegionInfo.RegionName + m_saveAppendedFileName + ".abackup";
            if (File.Exists(fileName))
            {
                //Do new style saving here!
                GZipStream m_saveStream = new GZipStream(new FileStream(fileName + ".tmp", FileMode.Create),
                                                         CompressionMode.Compress);
                TarArchiveWriter writer       = new TarArchiveWriter(m_saveStream);
                GZipStream       m_loadStream = new GZipStream(new FileStream(fileName, FileMode.Open),
                                                               CompressionMode.Decompress);
                TarArchiveReader reader = new TarArchiveReader(m_loadStream);

                writer.WriteDir("parcels");

                IParcelManagementModule module = m_scene.RequestModuleInterface <IParcelManagementModule>();
                if (module != null)
                {
                    List <ILandObject> landObject = module.AllParcels();
                    foreach (ILandObject parcel in landObject)
                    {
                        OSDMap parcelMap = parcel.LandData.ToOSD();
                        var    binary    = OSDParser.SerializeLLSDBinary(parcelMap);
                        writer.WriteFile("parcels/" + parcel.LandData.GlobalID.ToString(),
                                         binary);
                        binary    = null;
                        parcelMap = null;
                    }
                }

                writer.WriteDir("newstyleterrain");
                writer.WriteDir("newstylerevertterrain");

                writer.WriteDir("newstylewater");
                writer.WriteDir("newstylerevertwater");

                ITerrainModule tModule = m_scene.RequestModuleInterface <ITerrainModule>();
                if (tModule != null)
                {
                    try
                    {
                        byte[] sdata = WriteTerrainToStream(tModule.TerrainMap);
                        writer.WriteFile("newstyleterrain/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain", sdata);
                        sdata = null;

                        sdata = WriteTerrainToStream(tModule.TerrainRevertMap);
                        writer.WriteFile(
                            "newstylerevertterrain/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain", sdata);
                        sdata = null;

                        if (tModule.TerrainWaterMap != null)
                        {
                            sdata = WriteTerrainToStream(tModule.TerrainWaterMap);
                            writer.WriteFile("newstylewater/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain",
                                             sdata);
                            sdata = null;

                            sdata = WriteTerrainToStream(tModule.TerrainWaterRevertMap);
                            writer.WriteFile(
                                "newstylerevertwater/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain", sdata);
                            sdata = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                    }
                }

                IDictionary <UUID, AssetType> assets = new Dictionary <UUID, AssetType>();
                UuidGatherer assetGatherer           = new UuidGatherer(m_scene.AssetService);

                ISceneEntity[] saveentities   = m_scene.Entities.GetEntities();
                List <UUID>    entitiesToSave = new List <UUID>();
                foreach (ISceneEntity entity in saveentities)
                {
                    try
                    {
                        if (entity.IsAttachment ||
                            ((entity.RootChild.Flags & PrimFlags.Temporary) == PrimFlags.Temporary) ||
                            ((entity.RootChild.Flags & PrimFlags.TemporaryOnRez) == PrimFlags.TemporaryOnRez))
                        {
                            continue;
                        }
                        if (entity.HasGroupChanged)
                        {
                            entity.HasGroupChanged = false;
                            //Write all entities
                            byte[] xml = ((ISceneObject)entity).ToBinaryXml2();
                            writer.WriteFile("entities/" + entity.UUID.ToString(), xml);
                            xml = null;
                        }
                        else
                        {
                            entitiesToSave.Add(entity.UUID);
                        }
                        if (saveAssets)
                        {
                            assetGatherer.GatherAssetUuids(entity, assets, m_scene);
                        }
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                        entitiesToSave.Add(entity.UUID);
                    }
                }


                byte[] data;
                string filePath;
                TarArchiveReader.TarEntryType entryType;
                //Load the archive data that we need
                try
                {
                    while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
                    {
                        if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
                        {
                            continue;
                        }
                        if (filePath.StartsWith("entities/"))
                        {
                            UUID entityID = UUID.Parse(filePath.Remove(0, 9));
                            if (entitiesToSave.Contains(entityID))
                            {
                                writer.WriteFile(filePath, data);
                                entitiesToSave.Remove(entityID);
                            }
                        }
                        data = null;
                    }
                }
                catch (Exception ex)
                {
                    MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                }

                if (entitiesToSave.Count > 0)
                {
                    MainConsole.Instance.Fatal(entitiesToSave.Count + " PRIMS WERE NOT GOING TO BE SAVED! FORCE SAVING NOW! ");
                    foreach (ISceneEntity entity in saveentities)
                    {
                        if (entitiesToSave.Contains(entity.UUID))
                        {
                            if (entity.IsAttachment ||
                                ((entity.RootChild.Flags & PrimFlags.Temporary) == PrimFlags.Temporary) ||
                                ((entity.RootChild.Flags & PrimFlags.TemporaryOnRez) == PrimFlags.TemporaryOnRez))
                            {
                                continue;
                            }
                            //Write all entities
                            byte[] xml = ((ISceneObject)entity).ToBinaryXml2();
                            writer.WriteFile("entities/" + entity.UUID.ToString(), xml);
                            xml = null;
                        }
                    }
                }

                if (saveAssets)
                {
                    foreach (UUID assetID in new List <UUID>(assets.Keys))
                    {
                        try
                        {
                            WriteAsset(assetID.ToString(), m_scene.AssetService.Get(assetID.ToString()), writer);
                        }
                        catch (Exception ex)
                        {
                            MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
                        }
                    }
                }

                reader.Close();
                writer.Close();
                m_loadStream.Close();
                m_saveStream.Close();
                GC.Collect();

                if (m_keepOldSave && !m_oldSaveHasBeenSaved)
                {
                    //Havn't moved it yet, so make sure the directory exists, then move it
                    m_oldSaveHasBeenSaved = true;
                    if (!Directory.Exists(m_oldSaveDirectory))
                    {
                        Directory.CreateDirectory(m_oldSaveDirectory);
                    }
                    File.Copy(fileName + ".tmp",
                              Path.Combine(m_oldSaveDirectory,
                                           m_scene.RegionInfo.RegionName + SerializeDateTime() + m_saveAppendedFileName +
                                           ".abackup"));
                }
                //Just remove the file
                File.Delete(fileName);
            }
            else
            {
                //Add the .temp since we might need to make a backup and so that if something goes wrong, we don't corrupt the main backup
                GZipStream m_saveStream = new GZipStream(new FileStream(fileName + ".tmp", FileMode.Create),
                                                         CompressionMode.Compress);
                TarArchiveWriter      writer   = new TarArchiveWriter(m_saveStream);
                IAuroraBackupArchiver archiver = m_scene.RequestModuleInterface <IAuroraBackupArchiver>();

                //Turn off prompting so that we don't ask the user questions every time we need to save the backup
                archiver.AllowPrompting = false;
                archiver.SaveRegionBackup(writer, m_scene);
                archiver.AllowPrompting = true;

                m_saveStream.Close();
                writer.Close();
                GC.Collect();
            }
            File.Move(fileName + ".tmp", fileName);
            ISceneEntity[] entities = m_scene.Entities.GetEntities();
            try
            {
#if (!ISWIN)
                foreach (ISceneEntity entity in entities)
                {
                    if (entity.HasGroupChanged)
                    {
                        entity.HasGroupChanged = false;
                    }
                }
#else
                foreach (ISceneEntity entity in entities.Where(entity => entity.HasGroupChanged))
                {
                    entity.HasGroupChanged = false;
                }
#endif
            }
            catch (Exception ex)
            {
                MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
            }
            //Now make it the full file again
            MapTileNeedsGenerated = true;
            MainConsole.Instance.Info("[FileBasedSimulationData]: Saved Backup for region " + m_scene.RegionInfo.RegionName);
        }
Exemple #25
0
        public void TestRegionPing()
        {
            RegionInfo info = new RegionInfo
            {
                ExternalHostName = "localhost",
                InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
                HttpPort         = 9000,
                OutsideIP        = "127.0.0.1",
                RegionID         = UUID.Random(),
                RegionLocX       = 1100,
                RegionLocY       = 1000,
            };

            WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");

            req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
            req.Timeout = 10000;
            req.Method  = "POST";

            byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());

            var rs = req.GetRequestStream();

            rs.Write(serRegInfo, 0, serRegInfo.Length);
            rs.Flush();

            var          response = req.GetResponse();
            StreamReader sr       = new StreamReader(response.GetResponseStream());

            response.Dispose();

            var neighbors = srm.GetNeighborsSnapshot();
            var firstPing = neighbors[0].LastPingReceivedOn;

            Thread.Sleep(1000);

            req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/heartbeat");
            req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
            req.Timeout = 10000;
            req.Method  = "POST";

            serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());

            rs = req.GetRequestStream();
            rs.Write(serRegInfo, 0, serRegInfo.Length);
            rs.Flush();

            response = req.GetResponse();
            Assert.AreEqual(2, response.ContentLength);
            sr = new StreamReader(response.GetResponseStream());
            Assert.AreEqual("OK", sr.ReadToEnd());

            neighbors = srm.GetNeighborsSnapshot();
            Assert.AreEqual(1, neighbors.Count);

            Assert.Greater(neighbors[0].LastPingReceivedOn, firstPing);

            response.Dispose();

            Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborPing]);
            stateChangeCounts.Clear();
        }
Exemple #26
0
        protected virtual void ReadBackup(IScene scene)
        {
            MainConsole.Instance.Debug("[FileBasedSimulationData]: Reading file for " + scene.RegionInfo.RegionName);
            List <uint> foundLocalIDs = new List <uint>();
            var         stream        = ArchiveHelpers.GetStream((m_loadDirectory == "" || m_loadDirectory == "/")
                                                      ? m_fileName
                                                      : Path.Combine(m_loadDirectory, m_fileName));

            if (stream == null)
            {
                return;
            }

            GZipStream       m_loadStream = new GZipStream(stream, CompressionMode.Decompress);
            TarArchiveReader reader       = new TarArchiveReader(m_loadStream);

            byte[] data;
            string filePath;

            TarArchiveReader.TarEntryType entryType;
            System.Collections.Concurrent.ConcurrentQueue <byte[]> groups = new System.Collections.Concurrent.ConcurrentQueue <byte[]>();
            //Load the archive data that we need
            while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
            {
                if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
                {
                    continue;
                }

                if (filePath.StartsWith("parcels/"))
                {
                    //Only use if we are not merging
                    LandData parcel     = new LandData();
                    OSD      parcelData = OSDParser.DeserializeLLSDBinary(data);
                    parcel.FromOSD((OSDMap)parcelData);
                    m_parcels.Add(parcel);
                }
                else if (filePath.StartsWith("terrain/"))
                {
                    m_oldstyleterrain = data;
                }
                else if (filePath.StartsWith("revertterrain/"))
                {
                    m_oldstylerevertTerrain = data;
                }
                else if (filePath.StartsWith("newstyleterrain/"))
                {
                    m_terrain = data;
                }
                else if (filePath.StartsWith("newstylerevertterrain/"))
                {
                    m_revertTerrain = data;
                }
                else if (filePath.StartsWith("newstylewater/"))
                {
                    m_water = data;
                }
                else if (filePath.StartsWith("newstylerevertwater/"))
                {
                    m_revertWater = data;
                }
                else if (filePath.StartsWith("entities/"))
                {
                    groups.Enqueue(data);
                }
                data = null;
            }
            m_loadStream.Close();
            m_loadStream = null;

            int threadCount = groups.Count > 16 ? 16 : groups.Count;

            System.Threading.Thread[] threads = new System.Threading.Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                threads[i] = new System.Threading.Thread(() =>
                {
                    byte[] groupData;
                    while (groups.TryDequeue(out groupData))
                    {
                        MemoryStream ms = new MemoryStream(groupData);
                        SceneObjectGroup sceneObject = SceneObjectSerializer.FromXml2Format(ref ms, scene);
                        ms.Close();
                        ms   = null;
                        data = null;
                        if (sceneObject != null)
                        {
                            foreach (ISceneChildEntity part in sceneObject.ChildrenEntities())
                            {
                                lock (foundLocalIDs)
                                {
                                    if (!foundLocalIDs.Contains(part.LocalId))
                                    {
                                        foundLocalIDs.Add(part.LocalId);
                                    }
                                    else
                                    {
                                        part.LocalId = 0;     //Reset it! Only use it once!
                                    }
                                }
                            }
                            m_groups.Add(sceneObject);
                        }
                    }
                });
                threads[i].Start();
            }
            for (int i = 0; i < threadCount; i++)
            {
                threads[i].Join();
            }


            foundLocalIDs.Clear();
            GC.Collect();
        }
        ///<summary>
        ///
        ///</summary>
        private void UploadMapTile(IScene scene)
        {
            m_log.DebugFormat("[SIMIAN MAPTILE]: upload maptile for {0}", scene.RegionInfo.RegionName);

            // Create a PNG map tile and upload it to the AddMapTile API
            byte[]             pngData       = Utils.EmptyBytes;
            IMapImageGenerator tileGenerator = scene.RequestModuleInterface <IMapImageGenerator>();

            if (tileGenerator == null)
            {
                m_log.Warn("[SIMIAN MAPTILE]: Cannot upload PNG map tile without an ImageGenerator");
                return;
            }

            using (Image mapTile = tileGenerator.CreateMapTile())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    mapTile.Save(stream, ImageFormat.Png);
                    pngData = stream.ToArray();
                }
            }

            List <MultipartForm.Element> postParameters = new List <MultipartForm.Element>()
            {
                new MultipartForm.Parameter("X", scene.RegionInfo.RegionLocX.ToString()),
                new MultipartForm.Parameter("Y", scene.RegionInfo.RegionLocY.ToString()),
                new MultipartForm.File("Tile", "tile.png", "image/png", pngData)
            };

            string errorMessage = null;
            int    tickstart    = Util.EnvironmentTickCount();

            // Make the remote storage request
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl);
                request.Timeout          = 20000;
                request.ReadWriteTimeout = 5000;

                using (HttpWebResponse response = MultipartForm.Post(request, postParameters))
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        string responseStr = responseStream.GetStreamString();
                        OSD    responseOSD = OSDParser.Deserialize(responseStr);
                        if (responseOSD.Type == OSDType.Map)
                        {
                            OSDMap responseMap = (OSDMap)responseOSD;
                            if (responseMap["Success"].AsBoolean())
                            {
                                return;
                            }

                            errorMessage = "Upload failed: " + responseMap["Message"].AsString();
                        }
                        else
                        {
                            errorMessage = "Response format was invalid:\n" + 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);
                m_log.DebugFormat("[SIMIAN MAPTILE]: map tile uploaded in {0}ms", tickdiff);
            }

            m_log.WarnFormat("[SIMIAN MAPTILE]: Failed to store {0} byte tile for {1}: {2}",
                             pngData.Length, scene.RegionInfo.RegionName, errorMessage);
        }
Exemple #28
0
        public virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags,
                                        AgentData data, out int requestedUDPPort, out string reason)
        {
            reason = String.Empty;
            // Try local first
            if (m_localBackend.CreateAgent(destination, aCircuit, teleportFlags, data, out requestedUDPPort,
                                           out reason))
            {
                return(true);
            }
            requestedUDPPort = destination.ExternalEndPoint.Port; //Just make sure..

            reason = String.Empty;

            string uri = MakeUri(destination, true) + aCircuit.AgentID + "/";

            try
            {
                OSDMap args = aCircuit.PackAgentCircuitData();

                args["destination_x"]    = OSD.FromString(destination.RegionLocX.ToString());
                args["destination_y"]    = OSD.FromString(destination.RegionLocY.ToString());
                args["destination_name"] = OSD.FromString(destination.RegionName);
                args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
                args["teleport_flags"]   = OSD.FromString(teleportFlags.ToString());
                if (data != null)
                {
                    args["agent_data"] = data.Pack();
                }

                string resultStr = WebUtils.PostToService(uri, args);
                //Pull out the result and set it as the reason
                if (resultStr == "")
                {
                    return(false);
                }
                OSDMap result = OSDParser.DeserializeJson(resultStr) as OSDMap;
                reason = result["reason"] != null ? result["reason"].AsString() : "";
                if (result["success"].AsBoolean())
                {
                    //Not right... don't return true except for opensim combatibility :/
                    if (reason == "" || reason == "authorized")
                    {
                        return(true);
                    }
                    //We were able to contact the region
                    try
                    {
                        //We send the CapsURLs through, so we need these
                        OSDMap responseMap = (OSDMap)OSDParser.DeserializeJson(reason);
                        if (responseMap.ContainsKey("Reason"))
                        {
                            reason = responseMap["Reason"].AsString();
                        }
                        if (responseMap.ContainsKey("requestedUDPPort"))
                        {
                            requestedUDPPort = responseMap["requestedUDPPort"];
                        }
                        return(result["success"].AsBoolean());
                    }
                    catch
                    {
                        //Something went wrong
                        return(false);
                    }
                }

                reason = result.ContainsKey("Message") ? result["Message"].AsString() : "Could not contact the region";
                return(false);
            }
            catch (Exception e)
            {
                MainConsole.Instance.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e);
                reason = e.Message;
            }

            return(false);
        }
        public string RenderMaterialsPostCap(string request, UUID agentID)
        {
            OSDMap req  = (OSDMap)OSDParser.DeserializeLLSDXml(request);
            OSDMap resp = new OSDMap();

            OSDArray respArr = new OSDArray();

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

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

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null && osd is OSDArray)
                    {
                        foreach (OSD elem in (OSDArray)osd)
                        {
                            try
                            {
                                UUID id = new UUID(elem.AsBinary(), 0);

                                lock (m_Materials)
                                {
                                    if (m_Materials.ContainsKey(id))
                                    {
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"]       = OSD.FromBinary(id.GetBytes());
                                        matMap["Material"] = m_Materials[id];
                                        respArr.Add(matMap);
                                    }
                                    else
                                    {
                                        m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());

                                        // Theoretically we could try to load the material from the assets service,
                                        // but that shouldn't be necessary because the viewer should only request
                                        // materials that exist in a prim on the region, and all of these materials
                                        // are already stored in m_regionMaterials.
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                m_log.Error("Error getting materials in response to viewer request", e);
                                continue;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
                    //return "";
                }
            }

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

            //m_log.Debug("[Materials]: cap request: " + request);
            //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            //m_log.Debug("[Materials]: cap response: " + response);
            return(response);
        }
Exemple #30
0
        /// <summary>
        /// Does the actual remote mapitem request
        /// This should be called from an asynchronous thread
        /// Request failures get blacklisted until region restart so we don't
        /// continue to spend resources trying to contact regions that are down.
        /// </summary>
        /// <param name="httpserver">blank string, we discover this in the process</param>
        /// <param name="id">Agent ID that we are making this request on behalf</param>
        /// <param name="flags">passed in from packet</param>
        /// <param name="EstateID">passed in from packet</param>
        /// <param name="godlike">passed in from packet</param>
        /// <param name="itemtype">passed in from packet</param>
        /// <param name="regionhandle">Region we're looking up</param>
        /// <returns></returns>
        private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags,
                                            uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
        {
            bool blacklisted = false;

            lock (m_blacklistedregions)
            {
                if (m_blacklistedregions.ContainsKey(regionhandle))
                {
                    blacklisted = true;
                }
            }

            if (blacklisted)
            {
                return(new OSDMap());
            }

            UUID requestID = UUID.Random();

            lock (m_cachedRegionMapItemsAddress)
            {
                if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
                {
                    httpserver = m_cachedRegionMapItemsAddress[regionhandle];
                }
            }
            if (String.IsNullOrEmpty(httpserver))
            {
                RegionInfo mreg = m_scene.SceneGridService.RequestNeighbouringRegionInfo(regionhandle);

                if (mreg != null)
                {
                    httpserver = "http://" + mreg.ExternalHostName + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString();
                    lock (m_cachedRegionMapItemsAddress)
                    {
                        if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
                        {
                            m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver);
                        }
                    }
                }
                else
                {
                    lock (m_blacklistedregions)
                    {
                        if (!m_blacklistedregions.ContainsKey(regionhandle))
                        {
                            m_blacklistedregions.Add(regionhandle, Environment.TickCount);
                        }
                    }
                    m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString());
                }
            }

            blacklisted = false;
            lock (m_blacklistedurls)
            {
                if (m_blacklistedurls.ContainsKey(httpserver))
                {
                    blacklisted = true;
                }
            }

            // Can't find the http server
            if (String.IsNullOrEmpty(httpserver) || blacklisted)
            {
                return(new OSDMap());
            }

            MapRequestState mrs = new MapRequestState();

            mrs.agentID      = id;
            mrs.EstateID     = EstateID;
            mrs.flags        = flags;
            mrs.godlike      = godlike;
            mrs.itemtype     = itemtype;
            mrs.regionhandle = regionhandle;

            lock (m_openRequests)
                m_openRequests.Add(requestID, mrs);

            WebRequest mapitemsrequest = WebRequest.Create(httpserver);

            mapitemsrequest.Method      = "POST";
            mapitemsrequest.ContentType = "application/xml+llsd";
            OSDMap RAMap = new OSDMap();

            // string RAMapString = RAMap.ToString();
            OSD LLSDofRAMap = RAMap; // RENAME if this works

            byte[] buffer      = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap);
            OSDMap responseMap = new OSDMap();

            responseMap["requestID"] = OSD.FromUUID(requestID);

            Stream os = null;

            try
            {                                                  // send the Post
                mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send
                os = mapitemsrequest.GetRequestStream();
                os.Write(buffer, 0, buffer.Length);            //Send it
                os.Close();
                //m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver);
            }
            catch (WebException ex)
            {
                m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message);
                responseMap["connect"] = OSD.FromBoolean(false);
                lock (m_blacklistedurls)
                {
                    if (!m_blacklistedurls.ContainsKey(httpserver))
                    {
                        m_blacklistedurls.Add(httpserver, Environment.TickCount);
                    }
                }

                m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);

                return(responseMap);
            }

            string response_mapItems_reply = null;

            { // get the response
                try
                {
                    WebResponse webResponse = mapitemsrequest.GetResponse();
                    if (webResponse != null)
                    {
                        StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                        response_mapItems_reply = sr.ReadToEnd().Trim();
                    }
                    else
                    {
                        return(new OSDMap());
                    }
                }
                catch (WebException)
                {
                    responseMap["connect"] = OSD.FromBoolean(false);
                    lock (m_blacklistedurls)
                    {
                        if (!m_blacklistedurls.ContainsKey(httpserver))
                        {
                            m_blacklistedurls.Add(httpserver, Environment.TickCount);
                        }
                    }

                    m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);

                    return(responseMap);
                }
                OSD rezResponse = null;
                try
                {
                    rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply);

                    responseMap = (OSDMap)rezResponse;
                    responseMap["requestID"] = OSD.FromUUID(requestID);
                }
                catch (Exception)
                {
                    //m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message);
                    responseMap["connect"] = OSD.FromBoolean(false);

                    return(responseMap);
                }
            }
            return(responseMap);
        }