Ejemplo n.º 1
0
        public void IncomingCapsRequest(UUID agentID, Aurora.Framework.Services.GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_agentID          = agentID;
            m_moneyModule      = simbase.ApplicationRegistry.RequestModuleInterface <IMoneyModule>();
            m_assetService     = simbase.ApplicationRegistry.RequestModuleInterface <IAssetService>();
            m_inventoryService = simbase.ApplicationRegistry.RequestModuleInterface <IInventoryService>();
            m_libraryService   = simbase.ApplicationRegistry.RequestModuleInterface <ILibraryService>();
            m_inventoryData    = Framework.Utilities.DataManager.RequestPlugin <IInventoryData>();

            HttpServerHandle method = delegate(string path, Stream request, OSHttpRequest httpRequest,
                                               OSHttpResponse httpResponse)
            { return(HandleWebFetchInventoryDescendents(request, m_agentID)); };

            string uri = "/CAPS/FetchInventoryDescendents/" + UUID.Random() + "/";

            capURLs["WebFetchInventoryDescendents"] = MainServer.Instance.ServerURI + uri;
            capURLs["FetchInventoryDescendents"]    = MainServer.Instance.ServerURI + uri;
            capURLs["FetchInventoryDescendents2"]   = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, method));

            method = delegate(string path, Stream request, OSHttpRequest httpRequest,
                              OSHttpResponse httpResponse)
            { return(HandleFetchLibDescendents(request, m_agentID)); };
            uri = "/CAPS/FetchLibDescendents/" + UUID.Random() + "/";
            capURLs["FetchLibDescendents"]  = MainServer.Instance.ServerURI + uri;
            capURLs["FetchLibDescendents2"] = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, method));

            method = delegate(string path, Stream request, OSHttpRequest httpRequest,
                              OSHttpResponse httpResponse)
            { return(HandleFetchInventory(request, m_agentID)); };
            uri = "/CAPS/FetchInventory/" + UUID.Random() + "/";
            capURLs["FetchInventory"]  = MainServer.Instance.ServerURI + uri;
            capURLs["FetchInventory2"] = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, method));

            method = delegate(string path, Stream request, OSHttpRequest httpRequest,
                              OSHttpResponse httpResponse)
            { return(HandleFetchLib(request, m_agentID)); };
            uri = "/CAPS/FetchLib/" + UUID.Random() + "/";
            capURLs["FetchLib"]  = MainServer.Instance.ServerURI + uri;
            capURLs["FetchLib2"] = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, method));


            uri = "/CAPS/NewFileAgentInventory/" + UUID.Random() + "/";
            capURLs["NewFileAgentInventory"] = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, NewAgentInventoryRequest));

            uri = "/CAPS/NewFileAgentInventoryVariablePrice/" + UUID.Random() + "/";
            capURLs["NewFileAgentInventoryVariablePrice"] = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, NewAgentInventoryRequestVariablePrice));

            uri = "/CAPS/CreateInventoryCategory/" + UUID.Random() + "/";
            capURLs["CreateInventoryCategory"] = MainServer.Instance.ServerURI + uri;
            m_uris.Add(uri);
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", uri, CreateInventoryCategory));
        }
Ejemplo n.º 2
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(UUID id, uint flags,
                                            uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
        {
            string httpserver  = "";
            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 (httpserver.Length == 0)
            {
                uint x = 0, y = 0;
                Utils.LongToUInts(regionhandle, out x, out y);
                GridRegion mreg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);

                if (mreg != null)
                {
                    httpserver = mreg.ServerURI + "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 (httpserver.Length == 0 || 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 = null;

            try
            {
                mapitemsrequest = WebRequest.Create(httpserver);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[WORLD MAP]: Access to {0} failed with {1}", httpserver, e);
                return(new OSDMap());
            }

            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 {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);
            }
            catch
            {
                m_log.DebugFormat("[WORLD MAP]: RequestMapItems failed for {0}", httpserver);
                responseMap["connect"] = OSD.FromBoolean(false);
                return(responseMap);
            }

            string response_mapItems_reply = null;

            { // get the response
                StreamReader sr = null;
                try
                {
                    WebResponse webResponse = mapitemsrequest.GetResponse();
                    if (webResponse != null)
                    {
                        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);
                }
                catch
                {
                    m_log.DebugFormat("[WORLD MAP]: RequestMapItems failed for {0}", httpserver);
                    responseMap["connect"] = OSD.FromBoolean(false);
                    lock (m_blacklistedregions)
                    {
                        if (!m_blacklistedregions.ContainsKey(regionhandle))
                        {
                            m_blacklistedregions.Add(regionhandle, Environment.TickCount);
                        }
                    }

                    return(responseMap);
                }
                finally
                {
                    if (sr != null)
                    {
                        sr.Close();
                    }
                }

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

                    responseMap = (OSDMap)rezResponse;
                    responseMap["requestID"] = OSD.FromUUID(requestID);
                }
                catch (Exception ex)
                {
                    m_log.InfoFormat("[WORLD MAP]: exception on parse of RequestMapItems reply from {0}: {1}", httpserver, ex.Message);
                    responseMap["connect"] = OSD.FromBoolean(false);
                    lock (m_blacklistedregions)
                    {
                        if (!m_blacklistedregions.ContainsKey(regionhandle))
                        {
                            m_blacklistedregions.Add(regionhandle, Environment.TickCount);
                        }
                    }

                    return(responseMap);
                }
            }

            if (!responseMap.ContainsKey(itemtype.ToString())) // remote sim doesnt have the stated region handle
            {
                m_log.DebugFormat("[WORLD MAP]: Remote sim does not have the stated region. Blacklisting.");
                lock (m_blacklistedregions)
                {
                    if (!m_blacklistedregions.ContainsKey(regionhandle))
                    {
                        m_blacklistedregions.Add(regionhandle, Environment.TickCount);
                    }
                }
            }

            return(responseMap);
        }
        public UUID StartHttpRequest(
            uint localID, UUID itemID, string url, List <string> parameters, Dictionary <string, string> headers, string body,
            out HttpInitialRequestStatus status)
        {
            if (!CheckAllowed(new Uri(url)))
            {
                status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
                return(UUID.Zero);
            }

            UUID             reqID = UUID.Random();
            HttpRequestClass htc   = new HttpRequestClass();

            // Partial implementation: support for parameter flags needed
            //   see http://wiki.secondlife.com/wiki/LlHTTPRequest
            //
            // Parameters are expected in {key, value, ... , key, value}
            if (parameters != null)
            {
                string[] parms = parameters.ToArray();
                for (int i = 0; i < parms.Length; i += 2)
                {
                    switch (Int32.Parse(parms[i]))
                    {
                    case (int)HttpRequestConstants.HTTP_METHOD:

                        htc.HttpMethod = parms[i + 1];
                        break;

                    case (int)HttpRequestConstants.HTTP_MIMETYPE:

                        htc.HttpMIMEType = parms[i + 1];
                        break;

                    case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:

                        int len;
                        if (int.TryParse(parms[i + 1], out len))
                        {
                            if (len > HttpRequestClass.HttpBodyMaxLenMAX)
                            {
                                len = HttpRequestClass.HttpBodyMaxLenMAX;
                            }
                            else if (len < 64)    //???
                            {
                                len = 64;
                            }
                            htc.HttpBodyMaxLen = len;
                        }
                        break;

                    case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
                        htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
                        break;

                    case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:

                        // TODO implement me
                        break;

                    case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
                        //Parameters are in pairs and custom header takes
                        //arguments in pairs so adjust for header marker.
                        ++i;

                        //Maximum of 8 headers are allowed based on the
                        //Second Life documentation for llHTTPRequest.
                        for (int count = 1; count <= 8; ++count)
                        {
                            //Not enough parameters remaining for a header?
                            if (parms.Length - i < 2)
                            {
                                break;
                            }

                            if (htc.HttpCustomHeaders == null)
                            {
                                htc.HttpCustomHeaders = new List <string>();
                            }

                            htc.HttpCustomHeaders.Add(parms[i]);
                            htc.HttpCustomHeaders.Add(parms[i + 1]);
                            int nexti = i + 2;
                            if (nexti >= parms.Length || Char.IsDigit(parms[nexti][0]))
                            {
                                break;
                            }

                            i = nexti;
                        }
                        break;

                    case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
                        htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
                        break;
                    }
                }
            }

            htc.RequestModule   = this;
            htc.LocalID         = localID;
            htc.ItemID          = itemID;
            htc.Url             = url;
            htc.ReqID           = reqID;
            htc.HttpTimeout     = m_httpTimeout;
            htc.OutboundBody    = body;
            htc.ResponseHeaders = headers;
            htc.proxyurl        = m_proxyurl;
            htc.proxyexcepts    = m_proxyexcepts;

            // Same number as default HttpWebRequest.MaximumAutomaticRedirections
            htc.MaxRedirects = 50;

            lock (m_httpListLock)
                m_pendingRequests.Add(reqID, htc);

            htc.Process();
            status = HttpInitialRequestStatus.OK;
            return(reqID);
        }
Ejemplo n.º 4
0
        public UUID CreateAvatar(string firstName, string lastName, IScene scene, AvatarAppearance avatarApp,
                                 UUID creatorID, Vector3 startPos)
        {
            //Add the circuit data so they can login
            AgentCircuitData m_aCircuitData = new AgentCircuitData
            {
                IsChildAgent = false,
                CircuitCode  = (uint)Util.RandomClass.Next()
            };

            //Create the new bot data
            BotClientAPI m_character = new BotClientAPI(scene, m_aCircuitData);

            m_character.Name       = firstName + " " + lastName;
            m_aCircuitData.AgentID = m_character.AgentId;

            //Set up appearance
            var origOwner = avatarApp.Owner;

            avatarApp.Owner = m_character.AgentId;
            List <AvatarAttachment> attachments = avatarApp.GetAttachments();

            avatarApp.ClearAttachments();
            // get original attachments
            foreach (AvatarAttachment t in attachments)
            {
                InventoryItemBase item = scene.InventoryService.GetItem(origOwner, t.ItemID);
                if (item != null)
                {
                    item.ID     = UUID.Random();
                    item.Owner  = m_character.AgentId;
                    item.Folder = UUID.Zero;
                    scene.InventoryService.AddCacheItemAsync(item);
                    //Now fix the ItemID
                    avatarApp.SetAttachment(t.AttachPoint, item.ID, t.AssetID);
                }
            }

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

            IScenePresence SP = scene.GetScenePresence(m_character.AgentId);

            if (SP == null)
            {
                return(UUID.Zero); //Failed!
            }
            IAvatarAppearanceModule appearance = SP.RequestModuleInterface <IAvatarAppearanceModule>();

            appearance.Appearance = avatarApp;
            appearance.InitialHasWearablesBeenSent = true;
            Bot bot = new Bot();

            bot.Initialize(SP, creatorID);
            try {
                SP.MakeRootAgent(startPos, false, true);
            } catch {
                MainConsole.Instance.ErrorFormat("[BotManager]: Error creating bot {0} as root agent!", m_character.AgentId);
            }
            //Move them
            SP.Teleport(startPos);

            foreach (var presence in scene.GetScenePresences())
            {
                presence.SceneViewer.QueuePresenceForUpdate(SP, PrimUpdateFlags.ForcedFullUpdate);
            }
            IAttachmentsModule attModule = SP.Scene.RequestModuleInterface <IAttachmentsModule>();

            if (attModule != null)
            {
                foreach (AvatarAttachment att in attachments)
                {
                    attModule.RezSingleAttachmentFromInventory(SP.ControllingClient, att.ItemID, att.AssetID, 0, true);
                }
            }

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

            MainConsole.Instance.InfoFormat("[BotManager]: Added bot {0} to region {1}",
                                            m_character.Name, scene.RegionInfo.RegionName);

            //Return their UUID
            return(m_character.AgentId);
        }
Ejemplo n.º 5
0
        public void ProcessMessages()
        {
            if (m_transmitter.PendingSessionCount > 0)
            {
                Session tmp = m_transmitter.AcceptPendingSession();
                m_sessions.Add(tmp);
                m_sessionsToClient.Add(tmp);
            }

            List <Session> tmpRemove = new List <Session>();

            foreach (Session session in m_sessionsToClient)
            {
                while (session.AvailableMessages > 0)
                {
                    Message message = session.Receive();

                    if (message.GetType() == typeof(JoinRequestMessage))
                    {
                        JoinRequestMessage joinRequestMessage = (JoinRequestMessage)message;

                        m_log.Info("[MXP ClientStack]: Session join request: " + session.SessionId + " (" +
                                   (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" +
                                   session.RemoteEndPoint.Port + ")");

                        try
                        {
                            if (joinRequestMessage.BubbleId == Guid.Empty)
                            {
                                foreach (Scene scene in m_scenes.Values)
                                {
                                    if (scene.RegionInfo.RegionName == joinRequestMessage.BubbleName)
                                    {
                                        m_log.Info("[MXP ClientStack]: Resolved region by name: " + joinRequestMessage.BubbleName + " (" + scene.RegionInfo.RegionID + ")");
                                        joinRequestMessage.BubbleId = scene.RegionInfo.RegionID.Guid;
                                    }
                                }
                            }

                            if (joinRequestMessage.BubbleId == Guid.Empty)
                            {
                                m_log.Warn("[MXP ClientStack]: Failed to resolve region by name: " + joinRequestMessage.BubbleName);
                            }

                            UUID sceneId = new UUID(joinRequestMessage.BubbleId);

                            bool regionExists = true;
                            if (!m_scenes.ContainsKey(sceneId))
                            {
                                m_log.Info("[MXP ClientStack]: No such region: " + sceneId);
                                regionExists = false;
                            }

                            UUID        userId     = UUID.Zero;
                            UserAccount account    = null;
                            bool        authorized = regionExists ? AuthoriseUser(joinRequestMessage.ParticipantName,
                                                                                  joinRequestMessage.ParticipantPassphrase,
                                                                                  new UUID(joinRequestMessage.BubbleId), out account)
                                                            : false;

                            if (authorized)
                            {
                                Scene scene        = m_scenes[sceneId];
                                UUID  mxpSessionID = UUID.Random();

                                string reason;

                                m_log.Debug("[MXP ClientStack]: Session join request success: " + session.SessionId + " (" +
                                            (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" +
                                            session.RemoteEndPoint.Port + ")");

                                m_log.Debug("[MXP ClientStack]: Attaching UserAgent to UserProfile...");
                                UUID secureSession = UUID.Zero;
                                AttachUserAgentToUserProfile(account, session, mxpSessionID, sceneId, out secureSession);
                                m_log.Debug("[MXP ClientStack]: Attached UserAgent to UserProfile.");
                                m_log.Debug("[MXP ClientStack]: Preparing Scene to Connection...");
                                if (!PrepareSceneForConnection(mxpSessionID, secureSession, sceneId, account, out reason))
                                {
                                    m_log.DebugFormat("[MXP ClientStack]: Scene refused connection: {0}", reason);
                                    DeclineConnection(session, joinRequestMessage);
                                    tmpRemove.Add(session);
                                    continue;
                                }
                                m_log.Debug("[MXP ClientStack]: Prepared Scene to Connection.");
                                m_log.Debug("[MXP ClientStack]: Accepting connection...");
                                AcceptConnection(session, joinRequestMessage, mxpSessionID, userId);
                                m_log.Info("[MXP ClientStack]: Accepted connection.");

                                m_log.Debug("[MXP ClientStack]: Creating ClientView....");
                                MXPClientView client = new MXPClientView(session, mxpSessionID, userId, scene, account.FirstName, account.LastName);
                                m_clients.Add(client);
                                m_log.Debug("[MXP ClientStack]: Created ClientView.");

                                client.MXPSendSynchronizationBegin(m_scenes[new UUID(joinRequestMessage.BubbleId)].SceneContents.GetTotalObjectsCount());

                                m_log.Debug("[MXP ClientStack]: Starting ClientView...");
                                try
                                {
                                    client.Start();
                                    m_log.Debug("[MXP ClientStack]: Started ClientView.");
                                }
                                catch (Exception e)
                                {
                                    m_log.Error(e);
                                }

                                m_log.Debug("[MXP ClientStack]: Connected");
                            }
                            else
                            {
                                m_log.Info("[MXP ClientStack]: Session join request failure: " + session.SessionId + " (" +
                                           (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" +
                                           session.RemoteEndPoint.Port + ")");

                                DeclineConnection(session, joinRequestMessage);
                            }
                        }
                        catch (Exception e)
                        {
                            m_log.Error("[MXP ClientStack]: Session join request failure: " + session.SessionId + " (" +
                                        (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" +
                                        session.RemoteEndPoint.Port + "): " + e.ToString() + " :" + e.StackTrace.ToString());
                        }
                        tmpRemove.Add(session);
                    }
                }
            }

            foreach (Session session in tmpRemove)
            {
                m_sessionsToClient.Remove(session);
            }

            foreach (MXPClientView clientView in m_clients)
            {
                int     messagesProcessedCount = 0;
                Session session = clientView.Session;

                while (session.AvailableMessages > 0)
                {
                    Message message = session.Receive();

                    if (message.GetType() == typeof(LeaveRequestMessage))
                    {
                        LeaveResponseMessage leaveResponseMessage = (LeaveResponseMessage)MessageFactory.Current.ReserveMessage(
                            typeof(LeaveResponseMessage));

                        m_log.Debug("[MXP ClientStack]: Session leave request: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")");

                        leaveResponseMessage.RequestMessageId = message.MessageId;
                        leaveResponseMessage.FailureCode      = 0;
                        session.Send(leaveResponseMessage);

                        if (session.SessionState != SessionState.Disconnected)
                        {
                            session.SetStateDisconnected();
                        }

                        m_log.Debug("[MXP ClientStack]: Removing Client from Scene");
                        //clientView.Scene.RemoveClient(clientView.AgentId);
                    }
                    if (message.GetType() == typeof(LeaveResponseMessage))
                    {
                        LeaveResponseMessage leaveResponseMessage = (LeaveResponseMessage)message;

                        m_log.Debug("[MXP ClientStack]: Session leave response: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")");

                        if (leaveResponseMessage.FailureCode == 0)
                        {
                            session.SetStateDisconnected();
                        }

                        m_log.Debug("[MXP ClientStack]: Removing Client from Scene");
                        //clientView.Scene.RemoveClient(clientView.AgentId);
                    }
                    else
                    {
                        clientView.MXPPRocessMessage(message);
                    }

                    MessageFactory.Current.ReleaseMessage(message);
                    messagesProcessedCount++;
                    if (messagesProcessedCount > 1000)
                    {
                        break;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private byte[] HandleHttpStartSession(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            DoExpire();

            Hashtable post = DecodePostString(request.ReadUntilEnd());

            httpResponse.StatusCode  = 401;
            httpResponse.ContentType = "text/plain";
            if (m_UserName == String.Empty)
            {
                return(MainServer.BlankResponse);
            }

            if (post["USER"] == null || post["PASS"] == null)
            {
                return(MainServer.BlankResponse);
            }

            if (m_UserName != post["USER"].ToString() ||
                m_Password != post["PASS"].ToString())
            {
                return(MainServer.BlankResponse);
            }

            ConsoleConnection c = new ConsoleConnection {
                last = Environment.TickCount, lastLineSeen = 0
            };

            UUID sessionID = UUID.Random();

            lock (m_Connections)
            {
                m_Connections[sessionID] = c;
            }

            string uri = "/ReadResponses/" + sessionID.ToString() + "/";

            m_Server.AddPollServiceHTTPHandler(uri, new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents,
                                                                             sessionID));

            XmlDocument xmldoc  = new XmlDocument();
            XmlNode     xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
                                                    "", "");

            xmldoc.AppendChild(xmlnode);
            XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
                                                          "");

            xmldoc.AppendChild(rootElement);

            XmlElement id = xmldoc.CreateElement("", "SessionID", "");

            id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));

            rootElement.AppendChild(id);

            XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");

            prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));

            rootElement.AppendChild(prompt);

            httpResponse.StatusCode  = 200;
            httpResponse.ContentType = "text/xml";
            return(Encoding.UTF8.GetBytes(xmldoc.InnerXml));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Try to set up the estate owner for the given scene.
        /// </summary>
        /// <remarks>
        /// The involves asking the user for information about the user on the console.  If the user does not already
        /// exist then it is created.
        /// </remarks>
        /// <param name="scene"></param>
        private void SetUpEstateOwner(Scene scene)
        {
            RegionInfo regionInfo = scene.RegionInfo;

            string estateOwnerFirstName = null;
            string estateOwnerLastName  = null;
            string estateOwnerEMail     = null;
            string estateOwnerPassword  = null;
            string rawEstateOwnerUuid   = null;

            if (Config.Configs[ESTATE_SECTION_NAME] != null)
            {
                string defaultEstateOwnerName
                    = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerName", "").Trim();
                string[] ownerNames = defaultEstateOwnerName.Split(' ');

                if (ownerNames.Length >= 2)
                {
                    estateOwnerFirstName = ownerNames[0];
                    estateOwnerLastName  = ownerNames[1];
                }

                // Info to be used only on Standalone Mode
                rawEstateOwnerUuid  = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerUUID", null);
                estateOwnerEMail    = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerEMail", null);
                estateOwnerPassword = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerPassword", null);
            }

            MainConsole.Instance.Output("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName);
            List <char> excluded = new List <char>(new char[1] {
                ' '
            });


            if (estateOwnerFirstName == null || estateOwnerLastName == null)
            {
                estateOwnerFirstName = MainConsole.Instance.Prompt("Estate owner first name", "Test", excluded);
                estateOwnerLastName  = MainConsole.Instance.Prompt("Estate owner last name", "User", excluded);
            }

            UserAccount account
                = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, estateOwnerFirstName, estateOwnerLastName);

            if (account == null)
            {
                // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than
                // itself!
                //                    if (scene.UserAccountService is LocalUserAccountServicesConnector)
                //                    {
                //                        IUserAccountService innerUas
                //                            = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService;
                //
                //                        m_log.DebugFormat("B {0}", innerUas.GetType());
                //
                //                        if (innerUas is UserAccountService)
                //                        {

                if (scene.UserAccountService is UserAccountService)
                {
                    if (estateOwnerPassword == null)
                    {
                        estateOwnerPassword = MainConsole.Instance.Prompt("Password", null, null, false);
                    }

                    if (estateOwnerEMail == null)
                    {
                        estateOwnerEMail = MainConsole.Instance.Prompt("Email");
                    }

                    if (rawEstateOwnerUuid == null)
                    {
                        rawEstateOwnerUuid = MainConsole.Instance.Prompt("User ID", UUID.Random().ToString());
                    }

                    UUID estateOwnerUuid = UUID.Zero;
                    if (!UUID.TryParse(rawEstateOwnerUuid, out estateOwnerUuid))
                    {
                        m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawEstateOwnerUuid);
                        return;
                    }

                    // If we've been given a zero uuid then this signals that we should use a random user id
                    if (estateOwnerUuid == UUID.Zero)
                    {
                        estateOwnerUuid = UUID.Random();
                    }

                    account
                        = ((UserAccountService)scene.UserAccountService).CreateUser(
                              regionInfo.ScopeID,
                              estateOwnerUuid,
                              estateOwnerFirstName,
                              estateOwnerLastName,
                              estateOwnerPassword,
                              estateOwnerEMail);
                }
            }

            if (account == null)
            {
                m_log.ErrorFormat(
                    "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first at the grid level.");
            }
            else
            {
                regionInfo.EstateSettings.EstateOwner = account.PrincipalID;
                m_estateDataService.StoreEstateSettings(regionInfo.EstateSettings);
            }
        }
Ejemplo n.º 8
0
        public void AgentPositionTest01()
        {
            UUID    AgentId1     = UUID.Random();
            UUID    SessionId1   = UUID.Random();
            uint    CircuitCode1 = uint.MinValue;
            Vector3 Size1        = Vector3.UnitZ;
            Vector3 Position1    = Vector3.UnitX;
            Vector3 LeftAxis1    = Vector3.UnitY;
            Vector3 UpAxis1      = Vector3.UnitZ;
            Vector3 AtAxis1      = Vector3.UnitX;

            ulong RegionHandle1 = ulong.MinValue;

            byte[] Throttles1 = new byte[] { 0, 1, 0 };

            Vector3 Velocity1 = Vector3.Zero;
            float   Far1      = 256;

            bool    ChangedGrid1 = false;
            Vector3 Center1      = Vector3.Zero;

            AgentPosition position1 = new AgentPosition();

            position1.AgentID      = AgentId1;
            position1.SessionID    = SessionId1;
            position1.CircuitCode  = CircuitCode1;
            position1.Size         = Size1;
            position1.Position     = Position1;
            position1.LeftAxis     = LeftAxis1;
            position1.UpAxis       = UpAxis1;
            position1.AtAxis       = AtAxis1;
            position1.RegionHandle = RegionHandle1;
            position1.Throttles    = Throttles1;
            position1.Velocity     = Velocity1;
            position1.Far          = Far1;
            position1.ChangedGrid  = ChangedGrid1;
            position1.Center       = Center1;

            ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();

            cadu.AgentID        = AgentId1.Guid;
            cadu.ActiveGroupID  = UUID.Zero.Guid;
            cadu.throttles      = Throttles1;
            cadu.drawdistance   = Far1;
            cadu.Position       = Position1;
            cadu.Velocity       = Velocity1;
            cadu.regionHandle   = RegionHandle1;
            cadu.cameraPosition = Center1;
            cadu.AVHeight       = Size1.Z;

            AgentPosition position2 = new AgentPosition();

            position2.CopyFrom(cadu, position1.SessionID);

            Assert.IsTrue(
                position2.AgentID == position1.AgentID &&
                position2.Size == position1.Size &&
                position2.Position == position1.Position &&
                position2.Velocity == position1.Velocity &&
                position2.Center == position1.Center &&
                position2.RegionHandle == position1.RegionHandle &&
                position2.Far == position1.Far

                , "Copy From ChildAgentDataUpdate failed");

            position2 = new AgentPosition();

            Assert.IsFalse(position2.AgentID == position1.AgentID, "Test Error, position2 should be a blank uninitialized AgentPosition");
            EntityTransferContext ctx = new EntityTransferContext();

            position2.Unpack(position1.Pack(ctx), null, ctx);

            Assert.IsTrue(position2.AgentID == position1.AgentID, "Agent ID didn't unpack the same way it packed");
            Assert.IsTrue(position2.Position == position1.Position, "Position didn't unpack the same way it packed");
            Assert.IsTrue(position2.Velocity == position1.Velocity, "Velocity didn't unpack the same way it packed");
            Assert.IsTrue(position2.SessionID == position1.SessionID, "SessionID didn't unpack the same way it packed");
            Assert.IsTrue(position2.CircuitCode == position1.CircuitCode, "CircuitCode didn't unpack the same way it packed");
            Assert.IsTrue(position2.LeftAxis == position1.LeftAxis, "LeftAxis didn't unpack the same way it packed");
            Assert.IsTrue(position2.UpAxis == position1.UpAxis, "UpAxis didn't unpack the same way it packed");
            Assert.IsTrue(position2.AtAxis == position1.AtAxis, "AtAxis didn't unpack the same way it packed");
            Assert.IsTrue(position2.RegionHandle == position1.RegionHandle, "RegionHandle didn't unpack the same way it packed");
            Assert.IsTrue(position2.ChangedGrid == position1.ChangedGrid, "ChangedGrid didn't unpack the same way it packed");
            Assert.IsTrue(position2.Center == position1.Center, "Center didn't unpack the same way it packed");
            Assert.IsTrue(position2.Size == position1.Size, "Size didn't unpack the same way it packed");
        }
        protected void ConstructDefaultIarBytesForTestLoad()
        {
//            log4net.Config.XmlConfigurator.Configure();

            InventoryArchiverModule archiverModule = new InventoryArchiverModule();
            Scene scene = SceneHelpers.SetupScene();

            SceneHelpers.SetupSceneModules(scene, archiverModule);

            UserAccountHelpers.CreateUserWithInventory(scene, m_uaLL1, "hampshire");

            MemoryStream archiveWriteStream = new MemoryStream();

            // Create scene object asset
            UUID             ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
            SceneObjectGroup object1 = SceneHelpers.CreateSceneObject(1, ownerId, "Ray Gun Object", 0x50);

            UUID      asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
            AssetBase asset1   = AssetHelpers.CreateAsset(asset1Id, object1);

            scene.AssetService.Store(asset1);

            // Create scene object item
            InventoryItemBase item1 = new InventoryItemBase();

            item1.Name            = m_item1Name;
            item1.ID              = UUID.Parse("00000000-0000-0000-0000-000000000020");
            item1.AssetID         = asset1.FullID;
            item1.GroupID         = UUID.Random();
            item1.CreatorIdAsUuid = m_uaLL1.PrincipalID;
            item1.Owner           = m_uaLL1.PrincipalID;
            item1.Folder          = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID;
            scene.AddInventoryItem(item1);

            // Create coalesced objects asset
            SceneObjectGroup cobj1 = SceneHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object1", 0x120);

            cobj1.AbsolutePosition = new Vector3(15, 30, 45);

            SceneObjectGroup cobj2 = SceneHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object2", 0x140);

            cobj2.AbsolutePosition = new Vector3(25, 50, 75);

            CoalescedSceneObjects coa = new CoalescedSceneObjects(m_uaLL1.PrincipalID, cobj1, cobj2);

            AssetBase coaAsset = AssetHelpers.CreateAsset(0x160, coa);

            scene.AssetService.Store(coaAsset);

            // Create coalesced objects inventory item
            InventoryItemBase coaItem = new InventoryItemBase();

            coaItem.Name            = m_coaItemName;
            coaItem.ID              = UUID.Parse("00000000-0000-0000-0000-000000000180");
            coaItem.AssetID         = coaAsset.FullID;
            coaItem.GroupID         = UUID.Random();
            coaItem.CreatorIdAsUuid = m_uaLL1.PrincipalID;
            coaItem.Owner           = m_uaLL1.PrincipalID;
            coaItem.Folder          = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID;
            scene.AddInventoryItem(coaItem);

            archiverModule.ArchiveInventory(
                Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, "/*", "hampshire", archiveWriteStream);

            m_iarStreamBytes = archiveWriteStream.ToArray();
        }
Ejemplo n.º 10
0
 private void ProcessMoneyTransferRequest(UUID fromID, UUID toID, int amount, int type, string description)
 {
     if (toID != UUID.Zero)
     {
         ISceneManager manager = m_registry.RequestModuleInterface <ISceneManager>();
         if (manager != null)
         {
             bool paid = false;
             foreach (IScene scene in manager.Scenes)
             {
                 ISceneChildEntity ent = scene.GetSceneObjectPart(toID);
                 if (ent != null)
                 {
                     bool success = m_connector.UserCurrencyTransfer(ent.OwnerID, fromID, ent.UUID, ent.Name, UUID.Zero, "",
                                                                     (uint)amount, description, (TransactionType)type, UUID.Random());
                     if (success)
                     {
                         FireObjectPaid(toID, fromID, amount);
                     }
                     paid = true;
                     break;
                 }
             }
             if (!paid)
             {
                 m_connector.UserCurrencyTransfer(toID, fromID, (uint)amount, description,
                                                  (TransactionType)type, UUID.Random());
             }
         }
     }
 }
Ejemplo n.º 11
0
 private bool ValidateLandBuy(EventManager.LandBuyArgs e)
 {
     return(m_connector.UserCurrencyTransfer(e.parcelOwnerID, e.agentId,
                                             (uint)e.parcelPrice, "Land Purchase", TransactionType.LandSale,
                                             UUID.Random()));
 }
        /// <summary>
        /// The default override for TestClient commands
        /// </summary>
        /// <param name="args"></param>
        /// <param name="fromAgentId"></param>
        /// <returns></returns>
        public override string Execute(string[] args, UUID fromAgentId)
        {
            if (args.Length < 1)
            {
                return("Usage: uploadscript filename.lsl");
            }

            var file = args.Aggregate(string.Empty, (current, t) => $"{current}{t} ");

            file = file.TrimEnd();

            if (!File.Exists(file))
            {
                return($"Filename '{file}' does not exist");
            }

            try
            {
                using (var reader = new StreamReader(file))
                {
                    var body = reader.ReadToEnd();
                    var desc = $"{file} created by OpenMetaverse TestClient {DateTime.Now}";
                    // create the asset
                    Client.Inventory.RequestCreateItem(Client.Inventory.FindFolderForType(AssetType.LSLText),
                                                       file, desc, AssetType.LSLText, UUID.Random(),
                                                       InventoryType.LSL, PermissionMask.All, (success, item) =>
                    {
                        if (success)
                        {
                            // upload the asset
                            Client.Inventory.RequestUpdateScriptAgentInventory(
                                System.Text.Encoding.UTF8.GetBytes(body), item.UUID, true,
                                (uploadSuccess, uploadStatus, compileSuccess, compileMessages, itemId, assetId) =>
                            {
                                var log = $"Filename: {file}";
                                if (uploadSuccess)
                                {
                                    log += $" Script successfully uploaded, ItemID {itemId} AssetID {assetId}";
                                }
                                else
                                {
                                    log += $" Script failed to upload, ItemID {itemId}";
                                }

                                if (compileSuccess)
                                {
                                    log += " compilation successful";
                                }
                                else
                                {
                                    log += " compilation failed";
                                }

                                Logger.Log(log, Helpers.LogLevel.Info, Client);
                            });
                        }
                    });
                }
                return($"Filename: {file} is being uploaded.");
            }
            catch (Exception e)
            {
                Logger.Log(e.ToString(), Helpers.LogLevel.Error, Client);
                return($"Error creating script for {file}");
            }
        }
Ejemplo n.º 13
0
 private void btnDecline_Click(object sender, EventArgs e)
 {
     client.Self.TeleportLureRespond(targetUUID, UUID.Random(), false);
     CloseTab();
 }
        /// <summary>
        ///     Parses ad request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="AgentId"></param>
        /// <returns></returns>
        public byte[] ProcessAdd(Stream request, OSHttpResponse response, UUID AgentId)
        {
            IScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
            {
                return(MainServer.BlankResponse);
            }

            OSDMap r = (OSDMap)OSDParser.Deserialize(HttpServerHandlerHelpers.ReadFully(request));
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();

            try
            {
                message.Deserialize(r);
            }
            catch (Exception ex)
            {
                MainConsole.Instance.Error("[UploadObjectAssetModule]: Error de-serializing message " + ex);
                message = null;
            }

            if (message == null)
            {
                response.StatusCode = 400; //501; //410; //404;
                return
                    (Encoding.UTF8.GetBytes(
                         "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>"));
            }

            Vector3    pos     = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
            Quaternion rot     = Quaternion.Identity;
            Vector3    rootpos = Vector3.Zero;

            SceneObjectGroup rootGroup = null;

            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
                }


                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;


                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
                // }

                //pbs.ExtraParams = extraparams;
                foreach (UploadObjectAssetMessage.Object.ExtraParam extraParam in obj.ExtraParams)
                {
                    switch ((ushort)extraParam.Type)
                    {
                    case (ushort)ExtraParamType.Sculpt:
                        Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                        pbs.SculptEntry = true;

                        pbs.SculptTexture = obj.SculptID;
                        pbs.SculptType    = (byte)sculpt.Type;

                        break;

                    case (ushort)ExtraParamType.Flexible:
                        Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                        pbs.FlexiEntry    = true;
                        pbs.FlexiDrag     = flex.Drag;
                        pbs.FlexiForceX   = flex.Force.X;
                        pbs.FlexiForceY   = flex.Force.Y;
                        pbs.FlexiForceZ   = flex.Force.Z;
                        pbs.FlexiGravity  = flex.Gravity;
                        pbs.FlexiSoftness = flex.Softness;
                        pbs.FlexiTension  = flex.Tension;
                        pbs.FlexiWind     = flex.Wind;
                        break;

                    case (ushort)ExtraParamType.Light:
                        Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                        pbs.LightColorA    = light.Color.A;
                        pbs.LightColorB    = light.Color.B;
                        pbs.LightColorG    = light.Color.G;
                        pbs.LightColorR    = light.Color.R;
                        pbs.LightCutoff    = light.Cutoff;
                        pbs.LightEntry     = true;
                        pbs.LightFalloff   = light.Falloff;
                        pbs.LightIntensity = light.Intensity;
                        pbs.LightRadius    = light.Radius;
                        break;

                    case 0x40:
                        pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                        break;
                    }
                }
                pbs.PathBegin        = (ushort)obj.PathBegin;
                pbs.PathCurve        = (byte)obj.PathCurve;
                pbs.PathEnd          = (ushort)obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte)obj.RadiusOffset;
                pbs.PathRevolutions  = (byte)obj.Revolutions;
                pbs.PathScaleX       = (byte)obj.ScaleX;
                pbs.PathScaleY       = (byte)obj.ScaleY;
                pbs.PathShearX       = (byte)obj.ShearX;
                pbs.PathShearY       = (byte)obj.ShearY;
                pbs.PathSkew         = (sbyte)obj.Skew;
                pbs.PathTaperX       = (sbyte)obj.TaperX;
                pbs.PathTaperY       = (sbyte)obj.TaperY;
                pbs.PathTwist        = (sbyte)obj.Twist;
                pbs.PathTwistBegin   = (sbyte)obj.TwistBegin;
                pbs.HollowShape      = (HollowShape)obj.ProfileHollow;
                pbs.PCode            = (byte)PCode.Prim;
                pbs.ProfileBegin     = (ushort)obj.ProfileBegin;
                pbs.ProfileCurve     = (byte)obj.ProfileCurve;
                pbs.ProfileEnd       = (ushort)obj.ProfileEnd;
                pbs.Scale            = obj.Scale;
                pbs.State            = 0;
                SceneObjectPart prim = new SceneObjectPart(AgentId, pbs, obj.Position, obj.Rotation,
                                                           Vector3.Zero, obj.Name)
                {
                    UUID      = UUID.Random(),
                    CreatorID = AgentId,
                    OwnerID   = AgentId,
                    GroupID   = obj.GroupID
                };
                prim.LastOwnerID  = prim.OwnerID;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name         = obj.Name;
                prim.Description  = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint)j);

                    primFace.Bump       = face.Bump;
                    primFace.RGBA       = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow       = face.Glow;
                    primFace.TextureID  = face.ImageID;
                    primFace.Rotation   = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU    = face.OffsetS;
                    primFace.OffsetV    = face.OffsetT;
                    primFace.RepeatU    = face.ScaleS;
                    primFace.RepeatV    = face.ScaleT;
                    primFace.TexMapType = (MappingType)(face.MediaFlags & 6);
                }
                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape       = pbs;
                prim.Scale       = obj.Scale;

                SceneObjectGroup grp = new SceneObjectGroup(prim, m_scene);

                prim.ParentID = 0;
                if (i == 0)
                {
                    rootGroup = grp;
                }

                grp.AbsolutePosition = obj.Position;
                prim.SetRotationOffset(true, obj.Rotation, true);

                grp.RootPart.IsAttachment = false;

                string reason;
                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos, out reason))
                {
                    m_scene.SceneGraph.AddPrimToScene(grp);
                    grp.AbsolutePosition = obj.Position;
                }
                else
                {
                    //Stop now then
                    avatar.ControllingClient.SendAlertMessage("You do not have permission to rez objects here: " +
                                                              reason);
                    return(MainServer.BlankResponse);
                }
                allparts[i] = grp;
            }

            if (rootGroup != null)
            {
                for (int j = 1; j < allparts.Length; j++)
                {
                    rootGroup.LinkToGroup(allparts [j]);
                }

                rootGroup.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
                pos = m_scene.SceneGraph.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, 1, 1, true,
                                                           allparts [0].GroupScale(), false);
            }
            else
            {
                MainConsole.Instance.Error("[UploadObjectAssetModule]: Unable to locate root group!");
            }

            OSDMap map = new OSDMap();

            map["local_id"] = allparts[0].LocalId;
            return(OSDParser.SerializeLLSDXmlBytes(map));
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Set up a test scene
 /// </summary>
 /// <remarks>
 /// Automatically starts services, as would the normal runtime.
 /// </remarks>
 /// <returns></returns>
 public TestScene SetupScene()
 {
     return(SetupScene("Unit test region", UUID.Random(), 1000, 1000));
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Set up a scene.
        /// </summary>
        /// <param name="name">Name of the region</param>
        /// <param name="id">ID of the region</param>
        /// <param name="x">X co-ordinate of the region</param>
        /// <param name="y">Y co-ordinate of the region</param>
        /// <param name="sizeX">X size of scene</param>
        /// <param name="sizeY">Y size of scene</param>
        /// <param name="configSource"></param>
        /// <returns></returns>
        public TestScene SetupScene(
            string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource)
        {
            Console.WriteLine("Setting up test scene {0}", name);

            // We must set up a console otherwise setup of some modules may fail
            MainConsole.Instance = new MockConsole();

            RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1");

            regInfo.RegionName  = name;
            regInfo.RegionID    = id;
            regInfo.RegionSizeX = sizeX;
            regInfo.RegionSizeY = sizeY;

            TestScene testScene = new TestScene(
                regInfo, m_acm, SimDataService, m_estateDataService, configSource, null);

            INonSharedRegionModule godsModule = new GodsModule();

            godsModule.Initialise(new IniConfigSource());
            godsModule.AddRegion(testScene);

            // Add scene to physics
            ((INonSharedRegionModule)m_physicsScene).AddRegion(testScene);
            ((INonSharedRegionModule)m_physicsScene).RegionLoaded(testScene);

            // Add scene to services
            m_assetService.AddRegion(testScene);

            if (m_cache != null)
            {
                m_cache.AddRegion(testScene);
                m_cache.RegionLoaded(testScene);
                testScene.AddRegionModule(m_cache.Name, m_cache);
            }

            m_assetService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_assetService.Name, m_assetService);

            m_authenticationService.AddRegion(testScene);
            m_authenticationService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_authenticationService.Name, m_authenticationService);

            m_inventoryService.AddRegion(testScene);
            m_inventoryService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_inventoryService.Name, m_inventoryService);

            m_gridService.AddRegion(testScene);
            m_gridService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_gridService.Name, m_gridService);

            m_userAccountService.AddRegion(testScene);
            m_userAccountService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService);

            m_presenceService.AddRegion(testScene);
            m_presenceService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_presenceService.Name, m_presenceService);

            testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random();
            testScene.SetModuleInterfaces();

            testScene.LandChannel = new TestLandChannel(testScene);
            testScene.LoadWorldMap();

            testScene.RegionInfo.EstateSettings = new EstateSettings();
            testScene.LoginsEnabled             = true;
            testScene.RegisterRegionWithGrid();

            SceneManager.Add(testScene);

            return(testScene);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Set up a scene.
        /// </summary>
        /// <param name="name">Name of the region</param>
        /// <param name="id">ID of the region</param>
        /// <param name="x">X co-ordinate of the region</param>
        /// <param name="y">Y co-ordinate of the region</param>
        /// <param name="sizeX">X size of scene</param>
        /// <param name="sizeY">Y size of scene</param>
        /// <param name="configSource"></param>
        /// <returns></returns>
        public TestScene SetupScene(
            string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource)
        {
            Console.WriteLine("Setting up test scene {0}", name);

            // We must set up a console otherwise setup of some modules may fail
            MainConsole.Instance = new MockConsole();

            RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1");

            regInfo.RegionName  = name;
            regInfo.RegionID    = id;
            regInfo.RegionSizeX = sizeX;
            regInfo.RegionSizeY = sizeY;

            SceneCommunicationService scs = new SceneCommunicationService();

            PhysicsPluginManager physicsPluginManager = new PhysicsPluginManager();

            physicsPluginManager.LoadPluginsFromAssembly("Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll");
            Vector3      regionExtent = new Vector3(regInfo.RegionSizeX, regInfo.RegionSizeY, regInfo.RegionSizeZ);
            PhysicsScene physicsScene
                = physicsPluginManager.GetPhysicsScene(
                      "basicphysics", "ZeroMesher", new IniConfigSource(), "test", regionExtent);

            TestScene testScene = new TestScene(
                regInfo, m_acm, physicsScene, scs, SimDataService, m_estateDataService, configSource, null);

            INonSharedRegionModule godsModule = new GodsModule();

            godsModule.Initialise(new IniConfigSource());
            godsModule.AddRegion(testScene);

            // Add scene to services
            m_assetService.AddRegion(testScene);

            if (m_cache != null)
            {
                m_cache.AddRegion(testScene);
                m_cache.RegionLoaded(testScene);
                testScene.AddRegionModule(m_cache.Name, m_cache);
            }

            m_assetService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_assetService.Name, m_assetService);

            m_authenticationService.AddRegion(testScene);
            m_authenticationService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_authenticationService.Name, m_authenticationService);

            m_inventoryService.AddRegion(testScene);
            m_inventoryService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_inventoryService.Name, m_inventoryService);

            m_gridService.AddRegion(testScene);
            m_gridService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_gridService.Name, m_gridService);

            m_userAccountService.AddRegion(testScene);
            m_userAccountService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService);

            m_presenceService.AddRegion(testScene);
            m_presenceService.RegionLoaded(testScene);
            testScene.AddRegionModule(m_presenceService.Name, m_presenceService);

            testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random();
            testScene.SetModuleInterfaces();

            testScene.LandChannel = new TestLandChannel(testScene);
            testScene.LoadWorldMap();

            testScene.RegionInfo.EstateSettings = new EstateSettings();
            testScene.LoginsEnabled             = true;
            testScene.RegisterRegionWithGrid();

            SceneManager.Add(testScene);

            return(testScene);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Add a test object
 /// </summary>
 /// <param name="scene"></param>
 /// <returns></returns>
 public static SceneObjectGroup AddSceneObject(Scene scene)
 {
     return(AddSceneObject(scene, "Test Object", UUID.Random()));
 }
Ejemplo n.º 19
0
        private void ReadNiniConfig(IConfigSource source, string name)
        {
//            bool creatingNew = false;

            if (source.Configs.Count == 0)
            {
                MainConsole.Instance.Output("=====================================\n");
                MainConsole.Instance.Output("We are now going to ask a couple of questions about your region.\n");
                MainConsole.Instance.Output("You can press 'enter' without typing anything to use the default\n");
                MainConsole.Instance.Output("the default is displayed between [ ] brackets.\n");
                MainConsole.Instance.Output("=====================================\n");

                if (name == String.Empty)
                {
                    while (name.Trim() == string.Empty)
                    {
                        name = MainConsole.Instance.CmdPrompt("New region name", name);
                        if (name.Trim() == string.Empty)
                        {
                            MainConsole.Instance.Output("Cannot interactively create region with no name");
                        }
                    }
                }

                source.AddConfig(name);

//                creatingNew = true;
            }

            if (name == String.Empty)
            {
                name = source.Configs[0].Name;
            }

            if (source.Configs[name] == null)
            {
                source.AddConfig(name);
            }

            RegionName = name;
            IConfig config = source.Configs[name];

            // Track all of the keys in this config and remove as they are processed
            // The remaining keys will be added to generic key-value storage for
            // whoever might need it
            HashSet <String> allKeys = new HashSet <String>();

            foreach (string s in config.GetKeys())
            {
                allKeys.Add(s);
            }

            // RegionUUID
            //
            allKeys.Remove("RegionUUID");
            string regionUUID = config.GetString("RegionUUID", string.Empty);

            if (!UUID.TryParse(regionUUID.Trim(), out RegionID))
            {
                UUID newID = UUID.Random();
                while (RegionID == UUID.Zero)
                {
                    regionUUID = MainConsole.Instance.CmdPrompt("RegionUUID", newID.ToString());
                    if (!UUID.TryParse(regionUUID.Trim(), out RegionID))
                    {
                        MainConsole.Instance.Output("RegionUUID must be a valid UUID");
                    }
                }
                config.Set("RegionUUID", regionUUID);
            }

            originRegionID = RegionID; // What IS this?! (Needed for RegionCombinerModule?)

            // Location
            //
            allKeys.Remove("Location");
            string location = config.GetString("Location", String.Empty);

            if (location == String.Empty)
            {
                location = MainConsole.Instance.CmdPrompt("Region Location", "1000,1000");
                config.Set("Location", location);
            }

            string[] locationElements = location.Split(new char[] { ',' });

            m_regionLocX = Convert.ToUInt32(locationElements[0]);
            m_regionLocY = Convert.ToUInt32(locationElements[1]);

            // InternalAddress
            //
            IPAddress address;

            allKeys.Remove("InternalAddress");
            if (config.Contains("InternalAddress"))
            {
                address = IPAddress.Parse(config.GetString("InternalAddress", String.Empty));
            }
            else
            {
                address = IPAddress.Parse(MainConsole.Instance.CmdPrompt("Internal IP address", "0.0.0.0"));
                config.Set("InternalAddress", address.ToString());
            }

            // InternalPort
            //
            int port;

            allKeys.Remove("InternalPort");
            if (config.Contains("InternalPort"))
            {
                port = config.GetInt("InternalPort", 9000);
            }
            else
            {
                port = Convert.ToInt32(MainConsole.Instance.CmdPrompt("Internal port", "9000"));
                config.Set("InternalPort", port);
            }
            m_internalEndPoint = new IPEndPoint(address, port);

            // AllowAlternatePorts
            //
            allKeys.Remove("AllowAlternatePorts");
            if (config.Contains("AllowAlternatePorts"))
            {
                m_allow_alternate_ports = config.GetBoolean("AllowAlternatePorts", true);
            }
            else
            {
                m_allow_alternate_ports = Convert.ToBoolean(MainConsole.Instance.CmdPrompt("Allow alternate ports", "False"));

                config.Set("AllowAlternatePorts", m_allow_alternate_ports.ToString());
            }

            // ExternalHostName
            //
            allKeys.Remove("ExternalHostName");
            string externalName;

            if (config.Contains("ExternalHostName"))
            {
                externalName = config.GetString("ExternalHostName", "SYSTEMIP");
            }
            else
            {
                externalName = MainConsole.Instance.CmdPrompt("External host name", "SYSTEMIP");
                config.Set("ExternalHostName", externalName);
            }
            if (externalName == "SYSTEMIP")
            {
                m_externalHostName = Util.GetLocalHost().ToString();
                m_log.InfoFormat(
                    "[REGIONINFO]: Resolving SYSTEMIP to {0} for external hostname of region {1}",
                    m_externalHostName, name);
            }
            else
            {
                m_externalHostName = externalName;
            }

            // RegionType
            m_regionType = config.GetString("RegionType", String.Empty);
            allKeys.Remove("RegionType");

            #region Prim and map stuff

            m_nonphysPrimMin = config.GetFloat("NonPhysicalPrimMin", 0);
            allKeys.Remove("NonPhysicalPrimMin");

            m_nonphysPrimMax = config.GetInt("NonPhysicalPrimMax", 0);
            allKeys.Remove("NonPhysicalPrimMax");

            m_physPrimMin = config.GetFloat("PhysicalPrimMin", 0);
            allKeys.Remove("PhysicalPrimMin");

            m_physPrimMax = config.GetInt("PhysicalPrimMax", 0);
            allKeys.Remove("PhysicalPrimMax");

            m_clampPrimSize = config.GetBoolean("ClampPrimSize", false);
            allKeys.Remove("ClampPrimSize");

            m_objectCapacity = config.GetInt("MaxPrims", 15000);
            allKeys.Remove("MaxPrims");

            m_linksetCapacity = config.GetInt("LinksetPrims", 0);
            allKeys.Remove("LinksetPrims");

            allKeys.Remove("MaptileStaticUUID");
            string mapTileStaticUUID = config.GetString("MaptileStaticUUID", UUID.Zero.ToString());
            if (UUID.TryParse(mapTileStaticUUID.Trim(), out m_maptileStaticUUID))
            {
                config.Set("MaptileStaticUUID", m_maptileStaticUUID.ToString());
            }

            #endregion

            m_agentCapacity = config.GetInt("MaxAgents", 100);
            allKeys.Remove("MaxAgents");

            // Multi-tenancy
            //
            ScopeID = new UUID(config.GetString("ScopeID", UUID.Zero.ToString()));
            allKeys.Remove("ScopeID");

            foreach (String s in allKeys)
            {
                SetOtherSetting(s, config.GetString(s));
            }
        }
Ejemplo n.º 20
0
        public UUID StartHttpRequest(uint localID, UUID itemID, string url, List <string> parameters, Dictionary <string, string> headers, string body)
        {
            UUID             reqID = UUID.Random();
            HttpRequestClass htc   = new HttpRequestClass();

            // Partial implementation: support for parameter flags needed
            //   see http://wiki.secondlife.com/wiki/LlHTTPRequest
            //
            // Parameters are expected in {key, value, ... , key, value}
            if (parameters != null)
            {
                string[] parms = parameters.ToArray();
                for (int i = 0; i < parms.Length; i += 2)
                {
                    switch (Int32.Parse(parms[i]))
                    {
                    case (int)HttpRequestConstants.HTTP_METHOD:

                        htc.HttpMethod = parms[i + 1];
                        break;

                    case (int)HttpRequestConstants.HTTP_MIMETYPE:

                        htc.HttpMIMEType = parms[i + 1];
                        break;

                    case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:

                        // TODO implement me
                        break;

                    case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
                        htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
                        break;

                    case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:

                        // TODO implement me
                        break;

                    case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
                        //Parameters are in pairs and custom header takes
                        //arguments in pairs so adjust for header marker.
                        ++i;

                        //Maximum of 8 headers are allowed based on the
                        //Second Life documentation for llHTTPRequest.
                        for (int count = 1; count <= 8; ++count)
                        {
                            //Not enough parameters remaining for a header?
                            if (parms.Length - i < 2)
                            {
                                break;
                            }

                            //Have we reached the end of the list of headers?
                            //End is marked by a string with a single digit.
                            //We already know we have at least one parameter
                            //so it is safe to do this check at top of loop.
                            if (Char.IsDigit(parms[i][0]))
                            {
                                break;
                            }

                            if (htc.HttpCustomHeaders == null)
                            {
                                htc.HttpCustomHeaders = new List <string>();
                            }

                            htc.HttpCustomHeaders.Add(parms[i]);
                            htc.HttpCustomHeaders.Add(parms[i + 1]);

                            i += 2;
                        }
                        break;

                    case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
                        htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
                        break;
                    }
                }
            }

            htc.LocalID         = localID;
            htc.ItemID          = itemID;
            htc.Url             = url;
            htc.ReqID           = reqID;
            htc.HttpTimeout     = httpTimeout;
            htc.OutboundBody    = body;
            htc.ResponseHeaders = headers;
            htc.proxyurl        = m_proxyurl;
            htc.proxyexcepts    = m_proxyexcepts;

            m_pendingRequests.Add(reqID, htc);

            htc.Process();

            return(reqID);
        }
Ejemplo n.º 21
0
        public virtual string RegisterRegion(GridRegion regionInfos, UUID oldSessionID, out UUID SessionID,
                                             out List <GridRegion> neighbors)
        {
            SessionID = UUID.Zero;
            neighbors = new List <GridRegion>();
            if (m_DisableRegistrations)
            {
                return("Registrations are disabled.");
            }

            UUID NeedToDeletePreviousRegion = UUID.Zero;

            IConfig gridConfig = m_config.Configs["GridService"];

            //Get the range of this so that we get the full count and make sure that we are not overlapping smaller regions
            List <GridRegion> regions = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY,
                                                       regionInfos.RegionLocX + regionInfos.RegionSizeX - 1,
                                                       regionInfos.RegionLocY + regionInfos.RegionSizeY - 1,
                                                       regionInfos.ScopeID);

            if (regions.Count > 1)
            {
                //More than one region is here... it is overlapping stuff
                MainConsole.Instance.WarnFormat(
                    "[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.",
                    regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, regionInfos.ScopeID);
                return("Region overlaps another region");
            }

            GridRegion region = regions.Count > 0 ? regions[0] : null;

            if (!m_AllowNewRegistrations && region == null)
            {
                MainConsole.Instance.WarnFormat("[GRID SERVICE]: Region {0} tried to register but registrations are disabled.",
                                                regionInfos.RegionName);
                return("Registrations are disabled.");
            }

            if (m_maxRegionSize != 0 &&
                (regionInfos.RegionSizeX > m_maxRegionSize || regionInfos.RegionSizeY > m_maxRegionSize))
            {
                //Too big... kick it out
                MainConsole.Instance.WarnFormat("[GRID SERVICE]: Region {0} tried to register with too large of a size {1},{2}.",
                                                regionInfos.RegionName, regionInfos.RegionSizeX, regionInfos.RegionSizeY);
                return("Region overlaps another region");
            }

            if ((region != null) && (region.RegionID != regionInfos.RegionID))
            {
                MainConsole.Instance.WarnFormat(
                    "[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.",
                    regionInfos.RegionName, regionInfos.RegionLocX, regionInfos.RegionLocY, regionInfos.ScopeID);
                return("Region overlaps another region");
            }

            if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
                ((region.RegionLocX != regionInfos.RegionLocX) || (region.RegionLocY != regionInfos.RegionLocY)))
            {
                if ((region.Flags & (int)RegionFlags.NoMove) != 0)
                {
                    return("Can't move this region," + region.RegionLocX + "," + region.RegionLocY);
                }

                // Region reregistering in other coordinates. Delete the old entry
                MainConsole.Instance.DebugFormat(
                    "[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
                    regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);

                NeedToDeletePreviousRegion = regionInfos.RegionID;
            }

            if (region != null)
            {
                // There is a preexisting record
                //
                // Get it's flags
                //
                RegionFlags rflags = (RegionFlags)region.Flags;

                // Is this a reservation?
                //
                if ((rflags & RegionFlags.Reservation) != 0)
                {
                    // Regions reserved for the null key cannot be taken.
                    if (region.SessionID == UUID.Zero)
                    {
                        return("Region location is reserved");
                    }

                    // Treat it as an auth request
                    //
                    // NOTE: Fudging the flags value here, so these flags
                    //       should not be used elsewhere. Don't optimize
                    //       this with the later retrieval of the same flags!
                    rflags |= RegionFlags.Authenticate;
                }

                if ((rflags & RegionFlags.Authenticate) != 0)
                {
                    // Can we authenticate at all?
                    //
                    if (m_AuthenticationService == null)
                    {
                        return("No authentication possible");
                    }
                    //Make sure the key exists
                    if (!m_AuthenticationService.CheckExists(regionInfos.SessionID, "SessionID"))
                    {
                        return("Bad authentication");
                    }
                    //Now verify the key
                    if (!m_AuthenticationService.Verify(regionInfos.SessionID, "SessionID", regionInfos.AuthToken, 30))
                    {
                        return("Bad authentication");
                    }
                }
            }

            if (!m_AllowDuplicateNames)
            {
                List <GridRegion> dupe = m_Database.Get(regionInfos.RegionName, regionInfos.ScopeID);
                if (dupe != null && dupe.Count > 0)
                {
#if (!ISWIN)
                    foreach (GridRegion d in dupe)
                    {
                        if (d.RegionID != regionInfos.RegionID)
                        {
                            MainConsole.Instance.WarnFormat("[GRID SERVICE]: Region {0} tried to register duplicate name with ID {1}.", regionInfos.RegionName, regionInfos.RegionID);
                            return("Duplicate region name");
                        }
                    }
#else
                    if (dupe.Any(d => d.RegionID != regionInfos.RegionID))
                    {
                        MainConsole.Instance.WarnFormat("[GRID SERVICE]: Region {0} tried to register duplicate name with ID {1}.",
                                                        regionInfos.RegionName, regionInfos.RegionID);
                        return("Duplicate region name");
                    }
#endif
                }
            }

            if (region != null)
            {
                //If we are locked out, we can't come in
                if ((region.Flags & (int)RegionFlags.LockedOut) != 0)
                {
                    return("Region locked out");
                }

                //Remove the reservation if we are there now
                region.Flags &= ~(int)RegionFlags.Reservation;

                regionInfos.Flags = region.Flags; // Preserve flags
            }
            else
            {
                //Regions do not get to set flags, so wipe them
                regionInfos.Flags = 0;
                //See if we are in the configs anywhere and have flags set
                if ((gridConfig != null) && regionInfos.RegionName != string.Empty)
                {
                    int    newFlags   = 0;
                    string regionName = regionInfos.RegionName.Trim().Replace(' ', '_');
                    newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
                    newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
                    newFlags = ParseFlags(newFlags,
                                          gridConfig.GetString("Region_" + regionInfos.RegionID.ToString(), String.Empty));
                    regionInfos.Flags = newFlags;
                }
            }

            //Set these so that we can make sure the region is online later
            regionInfos.Flags   |= (int)RegionFlags.RegionOnline;
            regionInfos.Flags   |= (int)RegionFlags.Safe;
            regionInfos.LastSeen = Util.UnixTimeSinceEpoch();

            if (region != null)
            {
                //If we already have a session, we need to check it
                if (!VerifyRegionSessionID(region, oldSessionID))
                {
                    MainConsole.Instance.WarnFormat(
                        "[GRID SERVICE]: Region {0} called register, but the sessionID they provided is wrong!",
                        region.RegionName);
                    return("Wrong Session ID");
                }
            }

            //Update the sessionID, use the old so that we don't generate a bunch of these
            SessionID             = oldSessionID == UUID.Zero ? UUID.Random() : oldSessionID;
            regionInfos.SessionID = SessionID;

            // Everything is ok, let's register
            try
            {
                if (NeedToDeletePreviousRegion != UUID.Zero)
                {
                    m_Database.Delete(NeedToDeletePreviousRegion);
                }

                if (m_Database.Store(regionInfos))
                {
                    //Fire the event so that other modules notice
                    m_simulationBase.EventManager.FireGenericEventHandler("RegionRegistered", regionInfos);

                    //Get the neighbors for them
                    neighbors = GetNeighbors(regionInfos);
                    FixNeighbors(regionInfos, neighbors, false);

                    MainConsole.Instance.DebugFormat("[GRID SERVICE]: Region {0} registered successfully at {1}-{2}",
                                                     regionInfos.RegionName, regionInfos.RegionLocX, regionInfos.RegionLocY);
                    return(String.Empty);
                }
            }
            catch (Exception e)
            {
                MainConsole.Instance.WarnFormat("[GRID SERVICE]: Database exception: {0}", e);
            }

            return("Failed to save region into the database.");
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Create an item using details for the given scene object.
        /// </summary>
        /// <param name="action"></param>
        /// <param name="remoteClient"></param>
        /// <param name="so"></param>
        /// <param name="folderID"></param>
        /// <returns></returns>
        protected InventoryItemBase CreateItemForObject(
            DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID)
        {
            // Get the user info of the item destination
            //
            UUID userID = UUID.Zero;

            if (action == DeRezAction.Take || action == DeRezAction.TakeCopy ||
                action == DeRezAction.SaveToExistingUserInventoryItem)
            {
                // Take or take copy require a taker
                // Saving changes requires a local user
                //
                if (remoteClient == null)
                {
                    return(null);
                }

                userID = remoteClient.AgentId;

//                m_log.DebugFormat(
//                    "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}",
//                    action, remoteClient.Name, userID);
            }
            else if (so.RootPart.OwnerID == so.RootPart.GroupID)
            {
                // Group owned objects go to the last owner before the object was transferred.
                userID = so.RootPart.LastOwnerID;
            }
            else
            {
                // Other returns / deletes go to the object owner
                //
                userID = so.RootPart.OwnerID;

//                m_log.DebugFormat(
//                    "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}",
//                    action, userID);
            }

            if (userID == UUID.Zero) // Can't proceed
            {
                return(null);
            }

            // If we're returning someone's item, it goes back to the
            // owner's Lost And Found folder.
            // Delete is treated like return in this case
            // Deleting your own items makes them go to trash
            //

            InventoryFolderBase folder = null;
            InventoryItemBase   item   = null;

            if (DeRezAction.SaveToExistingUserInventoryItem == action)
            {
                item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID);
                item = m_Scene.InventoryService.GetItem(item);

                //item = userInfo.RootFolder.FindItem(
                //        objectGroup.RootPart.FromUserInventoryItemID);

                if (null == item)
                {
                    m_log.DebugFormat(
                        "[INVENTORY ACCESS MODULE]:  Object {0} {1} scheduled for save to inventory has already been deleted.",
                        so.Name, so.UUID);

                    return(null);
                }
            }
            else
            {
                // Folder magic
                //
                if (action == DeRezAction.Delete)
                {
                    // Deleting someone else's item
                    //
                    if (remoteClient == null ||
                        so.OwnerID != remoteClient.AgentId)
                    {
                        folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
                    }
                    else
                    {
                        folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
                    }
                }
                else if (action == DeRezAction.Return)
                {
                    // Dump to lost + found unconditionally
                    //
                    folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
                }

                if (folderID == UUID.Zero && folder == null)
                {
                    if (action == DeRezAction.Delete)
                    {
                        // Deletes go to trash by default
                        //
                        folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
                    }
                    else
                    {
                        if (remoteClient == null || so.OwnerID != remoteClient.AgentId)
                        {
                            // Taking copy of another person's item. Take to
                            // Objects folder.
                            folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object);
                        }
                        else
                        {
                            // Catch all. Use lost & found
                            //
                            folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
                        }
                    }
                }

                // Override and put into where it came from, if it came
                // from anywhere in inventory and the owner is taking it back.
                //
                if (action == DeRezAction.Take || action == DeRezAction.TakeCopy)
                {
                    if (so.FromFolderID != UUID.Zero && userID == remoteClient.AgentId)
                    {
                        InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID);
                        folder = m_Scene.InventoryService.GetFolder(f);
                    }
                }

                if (folder == null) // None of the above
                {
                    folder = new InventoryFolderBase(folderID);

                    if (folder == null) // Nowhere to put it
                    {
                        return(null);
                    }
                }

                item         = new InventoryItemBase();
                item.ID      = UUID.Random();
                item.InvType = (int)InventoryType.Object;
                item.Folder  = folder.ID;
                item.Owner   = userID;
            }

            return(item);
        }
Ejemplo n.º 23
0
        // End

        #region constructor

        public LandData()
        {
            _globalID = UUID.Random();
        }
Ejemplo n.º 24
0
        public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags,
                                                 uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
        {
            //All the parts are in for this, except for popular places and those are not in as they are not reqested anymore.

            List <mapItemReply> mapitems = new List <mapItemReply>();
            mapItemReply        mapitem  = new mapItemReply();
            uint xstart = 0;
            uint ystart = 0;

            OpenMetaverse.Utils.LongToUInts(remoteClient.Scene.RegionInfo.RegionHandle, out xstart, out ystart);
            OpenSim.Services.Interfaces.GridRegion GR = m_Scenes[0].GridService.GetRegionByPosition(UUID.Zero, (int)xstart, (int)ystart);

            #region Telehub
            if (itemtype == (uint)OpenMetaverse.GridItemType.Telehub)
            {
                IRegionConnector GF = DataManager.DataManager.RequestPlugin <IRegionConnector>();
                if (GF == null)
                {
                    return;
                }

                int tc = Environment.TickCount;
                //Find the telehub
                Telehub telehub = GF.FindTelehub(GR.RegionID, GR.RegionHandle);
                if (telehub != null)
                {
                    mapitem = new mapItemReply();
                    //The position is in GLOBAL coordinates (in meters)
                    mapitem.x  = (uint)(GR.RegionLocX + telehub.TelehubLocX);
                    mapitem.y  = (uint)(GR.RegionLocY + telehub.TelehubLocY);
                    mapitem.id = GR.RegionID;
                    //This is how the name is sent, go figure
                    mapitem.name = Util.Md5Hash(GR.RegionName + tc.ToString());
                    //Not sure, but this is what gets sent
                    mapitem.Extra  = 1;
                    mapitem.Extra2 = 0;

                    mapitems.Add(mapitem);
                    remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
                    mapitems.Clear();
                }
            }

            #endregion

            #region Land for sale

            //PG land that is for sale
            if (itemtype == (uint)OpenMetaverse.GridItemType.LandForSale)
            {
                if (directoryService == null)
                {
                    return;
                }
                //Find all the land, use "0" for the flags so we get all land for sale, no price or area checking
                DirLandReplyData[] Landdata = directoryService.FindLandForSale("0", int.MaxValue.ToString(), "0", 0, 0);

                int locX = 0;
                int locY = 0;
                foreach (DirLandReplyData landDir in Landdata)
                {
                    LandData landdata = directoryService.GetParcelInfo(landDir.parcelID);
                    if (landdata.Maturity != 0)
                    {
                        continue; //Not a PG land
                    }
                    foreach (Scene scene in m_Scenes)
                    {
                        if (scene.RegionInfo.RegionID == landdata.RegionID)
                        {
                            //Global coords, so add the meters
                            locX = scene.RegionInfo.RegionLocX;
                            locY = scene.RegionInfo.RegionLocY;
                        }
                    }
                    if (locY == 0 && locX == 0)
                    {
                        //Ask the grid service for the coordinates if the region is not local
                        OpenSim.Services.Interfaces.GridRegion r = m_Scenes[0].GridService.GetRegionByUUID(UUID.Zero, landdata.RegionID);
                        if (r != null)
                        {
                            locX = r.RegionLocX;
                            locY = r.RegionLocY;
                        }
                    }
                    if (locY == 0 && locX == 0) //Couldn't find the region, don't send
                    {
                        continue;
                    }

                    mapitem = new mapItemReply();
                    //Global coords, so make sure its in meters
                    mapitem.x      = (uint)(locX + landdata.UserLocation.X);
                    mapitem.y      = (uint)(locY + landdata.UserLocation.Y);
                    mapitem.id     = landDir.parcelID;
                    mapitem.name   = landDir.name;
                    mapitem.Extra  = landDir.actualArea;
                    mapitem.Extra2 = landDir.salePrice;
                    mapitems.Add(mapitem);
                }
                //Send all the map items
                if (mapitems.Count != 0)
                {
                    remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
                    mapitems.Clear();
                }
            }

            //Adult or mature land that is for sale
            if (itemtype == (uint)OpenMetaverse.GridItemType.AdultLandForSale)
            {
                if (directoryService == null)
                {
                    return;
                }
                //Find all the land, use "0" for the flags so we get all land for sale, no price or area checking
                DirLandReplyData[] Landdata = directoryService.FindLandForSale("0", int.MaxValue.ToString(), "0", 0, 0);

                int locX = 0;
                int locY = 0;
                foreach (DirLandReplyData landDir in Landdata)
                {
                    LandData landdata = directoryService.GetParcelInfo(landDir.parcelID);
                    if (landdata.Maturity == 0)
                    {
                        continue; //Its PG
                    }
                    foreach (Scene scene in m_Scenes)
                    {
                        if (scene.RegionInfo.RegionID == landdata.RegionID)
                        {
                            locX = scene.RegionInfo.RegionLocX;
                            locY = scene.RegionInfo.RegionLocY;
                        }
                    }
                    if (locY == 0 && locX == 0)
                    {
                        //Ask the grid service for the coordinates if the region is not local
                        OpenSim.Services.Interfaces.GridRegion r = m_Scenes[0].GridService.GetRegionByUUID(UUID.Zero, landdata.RegionID);
                        if (r != null)
                        {
                            locX = r.RegionLocX;
                            locY = r.RegionLocY;
                        }
                    }
                    if (locY == 0 && locX == 0) //Couldn't find the region, don't send
                    {
                        continue;
                    }

                    mapitem = new mapItemReply();
                    //Global coords, so make sure its in meters
                    mapitem.x      = (uint)(locX + landdata.UserLocation.X);
                    mapitem.y      = (uint)(locY + landdata.UserLocation.Y);
                    mapitem.id     = landDir.parcelID;
                    mapitem.name   = landDir.name;
                    mapitem.Extra  = landDir.actualArea;
                    mapitem.Extra2 = landDir.salePrice;

                    mapitems.Add(mapitem);
                }
                //Send the results if we have any
                if (mapitems.Count != 0)
                {
                    remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
                    mapitems.Clear();
                }
            }

            #endregion

            #region Events

            if (itemtype == (uint)OpenMetaverse.GridItemType.PgEvent ||
                itemtype == (uint)OpenMetaverse.GridItemType.MatureEvent ||
                itemtype == (uint)OpenMetaverse.GridItemType.AdultEvent)
            {
                if (directoryService == null)
                {
                    return;
                }

                //Find the maturity level
                int maturity = itemtype == (uint)OpenMetaverse.GridItemType.PgEvent ?
                               (int)DirectoryManager.EventFlags.PG :
                               (itemtype == (uint)GridItemType.MatureEvent) ?
                               (int)DirectoryManager.EventFlags.Mature :
                               (int)DirectoryManager.EventFlags.Adult;

                //Gets all the events occuring in the given region by maturity level
                DirEventsReplyData[] Eventdata = directoryService.FindAllEventsInRegion(GR.RegionName, maturity);

                foreach (DirEventsReplyData eventData in Eventdata)
                {
                    //Get more info on the event
                    EventData eventdata = directoryService.GetEventInfo(eventData.eventID.ToString());

                    Vector3 globalPos = eventdata.globalPos;
                    mapitem = new mapItemReply();

                    //Use global position plus half the region so that it doesn't always appear in the bottom corner
                    mapitem.x = (uint)(globalPos.X + (remoteClient.Scene.RegionInfo.RegionSizeX / 2));
                    mapitem.y = (uint)(globalPos.Y + (remoteClient.Scene.RegionInfo.RegionSizeY / 2));

                    mapitem.id     = UUID.Random();
                    mapitem.name   = eventData.name;
                    mapitem.Extra  = (int)eventdata.dateUTC;
                    mapitem.Extra2 = (int)eventdata.eventID;
                    mapitems.Add(mapitem);
                }
                //Send if we have any
                if (mapitems.Count != 0)
                {
                    remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
                    mapitems.Clear();
                }
            }

            #endregion

            #region Classified

            if (itemtype == (uint)OpenMetaverse.GridItemType.Classified)
            {
                if (directoryService == null)
                {
                    return;
                }
                //Get all the classifieds in this region
                Classified[] Classifieds = directoryService.GetClassifiedsInRegion(GR.RegionName);
                foreach (Classified classified in Classifieds)
                {
                    //Get the region so we have its position
                    OpenSim.Services.Interfaces.GridRegion region = m_Scenes[0].GridService.GetRegionByName(UUID.Zero, classified.SimName);

                    mapitem = new mapItemReply();

                    //Use global position plus half the sim so that all classifieds are not in the bottom corner
                    mapitem.x = (uint)(region.RegionLocX + classified.GlobalPos.X + (remoteClient.Scene.RegionInfo.RegionSizeX / 2));
                    mapitem.y = (uint)(region.RegionLocY + classified.GlobalPos.Y + (remoteClient.Scene.RegionInfo.RegionSizeY / 2));

                    mapitem.id     = classified.CreatorUUID;
                    mapitem.name   = classified.Name;
                    mapitem.Extra  = 0;
                    mapitem.Extra2 = 0;
                    mapitems.Add(mapitem);
                }
                //Send the events, if we have any
                if (mapitems.Count != 0)
                {
                    remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
                    mapitems.Clear();
                }
            }

            #endregion
        }
Ejemplo n.º 25
0
        public static InventoryItemBase GetEmbeddedItem(byte[] data, UUID itemID)
        {
            if (data == null || data.Length < 300)
            {
                return(null);
            }

            string note = Util.UTF8.GetString(data);

            if (String.IsNullOrWhiteSpace(note))
            {
                return(null);
            }

            // waste some time checking rigid versions
            string version = note.Substring(0, 21);

            if (!version.Equals("Linden text version 2"))
            {
                return(null);
            }

            version = note.Substring(24, 25);
            if (!version.Equals("LLEmbeddedItems version 1"))
            {
                return(null);
            }

            int indx = note.IndexOf(itemID.ToString(), 100);

            if (indx < 0)
            {
                return(null);
            }

            indx = note.IndexOf("permissions", indx, 100); // skip parentID
            if (indx < 0)
            {
                return(null);
            }

            string valuestr;

            indx = getField(note, indx, "base_mask", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint basemask))
            {
                return(null);
            }

            indx = getField(note, indx, "owner_mask", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint ownermask))
            {
                return(null);
            }

            indx = getField(note, indx, "group_mask", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint groupmask))
            {
                return(null);
            }

            indx = getField(note, indx, "everyone_mask", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint everyonemask))
            {
                return(null);
            }

            indx = getField(note, indx, "next_owner_mask", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint nextownermask))
            {
                return(null);
            }

            indx = getField(note, indx, "creator_id", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!UUID.TryParse(valuestr, out UUID creatorID))
            {
                return(null);
            }

            indx = getField(note, indx, "owner_id", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!UUID.TryParse(valuestr, out UUID ownerID))
            {
                return(null);
            }

            int limit = note.Length - indx;

            if (limit > 120)
            {
                limit = 120;
            }
            indx = note.IndexOf('}', indx, limit); // last owner
            if (indx < 0)
            {
                return(null);
            }

            int  curindx = indx;
            UUID assetID = UUID.Zero;

            indx = getField(note, indx, "asset_id", false, out valuestr);
            if (indx < 0)
            {
                indx = getField(note, curindx, "shadow_id", false, out valuestr);
                if (indx < 0)
                {
                    return(null);
                }
                if (!UUID.TryParse(valuestr, out assetID))
                {
                    return(null);
                }
                assetID = deMoronize(assetID);
            }
            else
            {
                if (!UUID.TryParse(valuestr, out assetID))
                {
                    return(null);
                }
            }

            indx = getField(note, indx, "type", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }

            AssetType assetType = SLAssetName2Type(valuestr);

            indx = getField(note, indx, "inv_type", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            FolderType invType = SLInvName2Type(valuestr);

            indx = getField(note, indx, "flags", false, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint flags))
            {
                return(null);
            }

            limit = note.Length - indx;
            if (limit > 120)
            {
                limit = 120;
            }
            indx = note.IndexOf('}', indx, limit); // skip sale
            if (indx < 0)
            {
                return(null);
            }

            indx = getField(note, indx, "name", true, out valuestr);
            if (indx < 0)
            {
                return(null);
            }

            string name = valuestr;

            indx = getField(note, indx, "desc", true, out valuestr);
            if (indx < 0)
            {
                return(null);
            }
            string desc = valuestr;

            InventoryItemBase item = new InventoryItemBase();

            item.AssetID            = assetID;
            item.AssetType          = (sbyte)assetType;
            item.BasePermissions    = basemask;
            item.CreationDate       = Util.UnixTimeSinceEpoch();
            item.CreatorData        = "";
            item.CreatorId          = creatorID.ToString();
            item.CurrentPermissions = ownermask;
            item.Description        = desc;
            item.Flags            = flags;
            item.Folder           = UUID.Zero;
            item.GroupID          = UUID.Zero;
            item.GroupOwned       = false;
            item.GroupPermissions = groupmask;
            item.InvType          = (sbyte)invType;
            item.Name             = name;
            item.NextPermissions  = nextownermask;
            item.Owner            = ownerID;
            item.SalePrice        = 0;
            item.SaleType         = (byte)SaleType.Not;
            item.ID = UUID.Random();
            return(item);
        }
Ejemplo n.º 26
0
        public void OnFileRequested(HttpRequest request, IDirectory directory)
        {
            //request.Response.SetHeader("Content-Type", "text/plain; charset=utf-8");
            request.Response.ResponseContent = new MemoryStream();
            StreamWriter  textwriter = new StreamWriter(request.Response.ResponseContent);
            GridClient    client;
            AvatarTracker avatars;
            Events        events;
            StreamReader  reader  = new StreamReader(request.PostData);
            string        qstring = reader.ReadToEnd();

            reader.Dispose();
            Dictionary <string, string> POST = AjaxLife.PostDecode(qstring);

            // Pull out the session.
            if (!POST.ContainsKey("sid"))
            {
                textwriter.WriteLine("Need an SID.");
                textwriter.Flush();
                return;
            }
            Guid guid = new Guid(POST["sid"]);
            User user = new User();

            lock (this.users)
            {
                if (!this.users.ContainsKey(guid))
                {
                    textwriter.WriteLine("Error: invalid SID");
                    textwriter.Flush();
                    return;
                }
                user             = this.users[guid];
                client           = user.Client;
                avatars          = user.Avatars;
                events           = user.Events;
                user.LastRequest = DateTime.Now;
            }
            // Get the message type.
            string messagetype = POST["MessageType"];

            // Check that the message is signed if it should be.
            if (Array.IndexOf(REQUIRED_SIGNATURES, messagetype) > -1)
            {
                if (!VerifySignature(user, qstring))
                {
                    textwriter.WriteLine("Error: Received hash and expected hash do not match.");
                    textwriter.Flush();
                    return;
                }
            }

            // Right. This file is fun. It takes information in POST paramaters and sends them to
            // the server in the appropriate format. Some will return data immediately, some will return
            // keys to data that will arrive in the message queue, some return nothing but you get
            // something in the message queue later, and some return nother ever.
            //
            // The joys of dealing with multiple bizarre message types.

            switch (messagetype)
            {
            case "SpatialChat":
                client.Self.Chat(POST["Message"], int.Parse(POST["Channel"]), (ChatType)((byte)int.Parse(POST["Type"])));
                break;

            case "SimpleInstantMessage":
                if (POST.ContainsKey("IMSessionID"))
                {
                    client.Self.InstantMessage(new UUID(POST["Target"]), POST["Message"], new UUID(POST["IMSessionID"]));
                }
                else
                {
                    client.Self.InstantMessage(new UUID(POST["Target"]), POST["Message"]);
                }
                break;

            case "GenericInstantMessage":
                client.Self.InstantMessage(
                    client.Self.FirstName + " " + client.Self.LastName,
                    new UUID(POST["Target"]),
                    POST["Message"],
                    new UUID(POST["IMSessionID"]),
                    (InstantMessageDialog)((byte)int.Parse(POST["Dialog"])),
                    (InstantMessageOnline)int.Parse(POST["Online"]),
                    client.Self.SimPosition,
                    client.Network.CurrentSim.ID,
                    new byte[0]);
                break;

            case "NameLookup":
                client.Avatars.RequestAvatarName(new UUID(POST["ID"]));
                break;

            case "Teleport":
            {
                Hashtable hash = new Hashtable();
                bool      status;
                if (POST.ContainsKey("Landmark"))
                {
                    status = client.Self.Teleport(new UUID(POST["Landmark"]));
                }
                else
                {
                    status = client.Self.Teleport(POST["Sim"], new Vector3(float.Parse(POST["X"]), float.Parse(POST["Y"]), float.Parse(POST["Z"])));
                }
                if (status)
                {
                    hash.Add("Success", true);
                    hash.Add("Sim", client.Network.CurrentSim.Name);
                    hash.Add("Position", client.Self.SimPosition);
                }
                else
                {
                    hash.Add("Success", false);
                    hash.Add("Reason", client.Self.TeleportMessage);
                }
                textwriter.WriteLine(MakeJson.FromHashtable(hash));
            }
            break;

            case "GoHome":
                client.Self.GoHome();
                break;

            case "GetPosition":
            {
                Hashtable hash = new Hashtable();
                hash.Add("Sim", client.Network.CurrentSim.Name);
                hash.Add("Position", client.Self.SimPosition);
                textwriter.WriteLine(JavaScriptConvert.SerializeObject(hash));
            }
            break;

            case "RequestBalance":
                client.Self.RequestBalance();
                break;

            case "GetStats":
            {
                Hashtable hash = new Hashtable();
                hash.Add("FPS", client.Network.CurrentSim.Stats.FPS);
                hash.Add("TimeDilation", client.Network.CurrentSim.Stats.Dilation);
                hash.Add("Objects", client.Network.CurrentSim.Stats.Objects);
                hash.Add("ActiveScripts", client.Network.CurrentSim.Stats.ActiveScripts);
                hash.Add("Agents", client.Network.CurrentSim.Stats.Agents);
                hash.Add("ChildAgents", client.Network.CurrentSim.Stats.ChildAgents);
                hash.Add("AjaxLifeSessions", users.Count);
                hash.Add("PingSim", client.Network.CurrentSim.Stats.LastLag);
                hash.Add("IncomingBPS", client.Network.CurrentSim.Stats.IncomingBPS);
                hash.Add("OutgoingBPS", client.Network.CurrentSim.Stats.OutgoingBPS);
                hash.Add("DroppedPackets", client.Network.CurrentSim.Stats.ReceivedResends + client.Network.CurrentSim.Stats.ResentPackets);
                textwriter.WriteLine(MakeJson.FromHashtable(hash));
            }
            break;

            case "TeleportLureRespond":
                client.Self.TeleportLureRespond(new UUID(POST["RequesterID"]), new UUID(POST["SessionID"]), bool.Parse(POST["Accept"]));
                break;

            case "GodlikeTeleportLureRespond":
            {
                UUID lurer   = new UUID(POST["RequesterID"]);
                UUID session = new UUID(POST["SessionID"]);
                client.Self.InstantMessage(client.Self.Name, lurer, "", UUID.Random(), InstantMessageDialog.AcceptTeleport, InstantMessageOnline.Offline, client.Self.SimPosition, UUID.Zero, new byte[0]);
                TeleportLureRequestPacket lure = new TeleportLureRequestPacket();
                lure.Info.AgentID       = client.Self.AgentID;
                lure.Info.SessionID     = client.Self.SessionID;
                lure.Info.LureID        = session;
                lure.Info.TeleportFlags = (uint)TeleportFlags.ViaGodlikeLure;
                client.Network.SendPacket(lure);
            }
            break;

            case "FindPeople":
            {
                Hashtable hash = new Hashtable();
                hash.Add("QueryID", client.Directory.StartPeopleSearch(POST["Search"], int.Parse(POST["Start"])));
                textwriter.WriteLine(MakeJson.FromHashtable(hash));
            }
            break;

            case "FindGroups":
            {
                Hashtable hash = new Hashtable();
                hash.Add("QueryID", client.Directory.StartGroupSearch(POST["Search"], int.Parse(POST["Start"])));
                textwriter.WriteLine(MakeJson.FromHashtable(hash));
            }
            break;

            case "GetAgentData":
                client.Avatars.RequestAvatarProperties(new UUID(POST["AgentID"]));
                break;

            case "StartAnimation":
                client.Self.AnimationStart(new UUID(POST["Animation"]), false);
                break;

            case "StopAnimation":
                client.Self.AnimationStop(new UUID(POST["Animation"]), true);
                break;

            case "SendAppearance":
                client.Appearance.RequestSetAppearance();
                break;

            case "GetMapItems":
            {
                MapItemRequestPacket req = new MapItemRequestPacket();
                req.AgentData.AgentID   = client.Self.AgentID;
                req.AgentData.SessionID = client.Self.SessionID;
                GridRegion region;
                client.Grid.GetGridRegion(POST["Region"], GridLayerType.Objects, out region);
                req.RequestData.RegionHandle = region.RegionHandle;
                req.RequestData.ItemType     = uint.Parse(POST["ItemType"]);
                client.Network.SendPacket((Packet)req);
            }
            break;

            case "GetMapBlocks":
            {
                MapBlockRequestPacket req = new MapBlockRequestPacket();
                req.AgentData.AgentID   = client.Self.AgentID;
                req.AgentData.SessionID = client.Self.SessionID;
                req.PositionData.MinX   = ushort.Parse(POST["MinX"]);
                req.PositionData.MinY   = ushort.Parse(POST["MinY"]);
                req.PositionData.MaxX   = ushort.Parse(POST["MaxX"]);
                req.PositionData.MaxY   = ushort.Parse(POST["MaxY"]);
                client.Network.SendPacket((Packet)req);
            }
            break;

            case "FindRegion":
            {
                OpenMetaverse.Packets.MapNameRequestPacket packet = new OpenMetaverse.Packets.MapNameRequestPacket();
                packet.NameData            = new MapNameRequestPacket.NameDataBlock();
                packet.NameData.Name       = Utils.StringToBytes(POST["Name"]);
                packet.AgentData.AgentID   = client.Self.AgentID;
                packet.AgentData.SessionID = client.Self.SessionID;
                client.Network.SendPacket((Packet)packet);
            }
            break;

            case "GetOfflineMessages":
            {
                RetrieveInstantMessagesPacket req = new RetrieveInstantMessagesPacket();
                req.AgentData.AgentID   = client.Self.AgentID;
                req.AgentData.SessionID = client.Self.SessionID;
                client.Network.SendPacket((Packet)req);
            }
            break;

            case "GetFriendList":
            {
                InternalDictionary <UUID, FriendInfo> friends = client.Friends.FriendList;
                List <Hashtable> friendlist = new List <Hashtable>();
                friends.ForEach(delegate(FriendInfo friend)
                    {
                        Hashtable friendhash = new Hashtable();
                        friendhash.Add("ID", friend.UUID.ToString());
                        friendhash.Add("Name", friend.Name);
                        friendhash.Add("Online", friend.IsOnline);
                        friendhash.Add("MyRights", friend.MyFriendRights);
                        friendhash.Add("TheirRights", friend.TheirFriendRights);
                        friendlist.Add(friendhash);
                    });
                textwriter.Write(MakeJson.FromObject(friendlist));
            }
            break;

            case "ChangeRights":
            {
                UUID uuid = new UUID(POST["Friend"]);
                client.Friends.GrantRights(uuid, (FriendRights)int.Parse(POST["Rights"]));
            }
            break;

            case "RequestLocation":
                client.Friends.MapFriend(new UUID(POST["Friend"]));
                break;

            case "RequestTexture":
            {
                // This one's confusing, so it gets some comments.
                // First, we get the image's UUID.
                UUID image = new UUID(POST["ID"]);
                // We prepare a query to ask if S3 has it. HEAD only to avoid wasting
                // GET requests and bandwidth.
                bool exists = false;
                // If we already know we have it, note this.
                if (AjaxLife.CachedTextures.Contains(image))
                {
                    exists = true;
                }
                else
                {
                    // If we're using S3, check the S3 bucket
                    if (AjaxLife.USE_S3)
                    {
                        // Otherwise, make that HEAD request and find out.
                        HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(AjaxLife.TEXTURE_ROOT + image + ".png");
                        webrequest.Method           = "HEAD";
                        webrequest.KeepAlive        = false;
                        webrequest.ReadWriteTimeout = 1000;
                        webrequest.Timeout          = 2500;
                        HttpWebResponse response = null;
                        try
                        {
                            response = (HttpWebResponse)webrequest.GetResponse();
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                exists = true;
                            }
                        }
                        catch (WebException e)
                        {
                            AjaxLife.Debug("SendMessage", "WebException (" + e.Status.ToString() + "): " + e.Message);
                        }
                        finally
                        {
                            request.Dispose();
                            if (response != null)
                            {
                                response.Close();
                            }
                        }
                    }
                    // If we aren't using S3, just check the texture cache.
                    else
                    {
                        exists = File.Exists(AjaxLife.TEXTURE_CACHE + image.ToString() + ".png");
                    }
                }
                // If it exists, reply with Ready = true and the URL to find it at.
                if (exists)
                {
                    textwriter.Write("{Ready: true, URL: \"" + AjaxLife.TEXTURE_ROOT + image + ".png\"}");
                }
                // If it doesn't, request the image from SL and note its lack of readiness.
                // Notification will arrive later in the message queue.
                else
                {
                    client.Assets.RequestImage(image, new TextureDownloadCallback(events.Assets_TextureDownloadCallback));
                    textwriter.Write("{Ready: false}");
                }
            }
            break;

            case "AcceptFriendship":
                client.Friends.AcceptFriendship(client.Self.AgentID, new UUID(POST["IMSessionID"]));
                break;

            case "DeclineFriendship":
                client.Friends.DeclineFriendship(client.Self.AgentID, new UUID(POST["IMSessionID"]));
                break;

            case "OfferFriendship":
                client.Friends.OfferFriendship(new UUID(POST["Target"]));
                break;

            case "TerminateFriendship":
                client.Friends.TerminateFriendship(new UUID(POST["Target"]));
                break;

            case "SendAgentMoney":
                client.Self.GiveAvatarMoney(new UUID(POST["Target"]), int.Parse(POST["Amount"]));
                break;

            case "RequestAvatarList":
            {
                List <Hashtable> list = new List <Hashtable>();
                foreach (KeyValuePair <uint, Avatar> pair in avatars.Avatars)
                {
                    Avatar    avatar = pair.Value;
                    Hashtable hash   = new Hashtable();
                    hash.Add("Name", avatar.Name);
                    hash.Add("ID", avatar.ID);
                    hash.Add("LocalID", avatar.LocalID);
                    hash.Add("Position", avatar.Position);
                    //hash.Add("Rotation", avatar.Rotation);
                    hash.Add("Scale", avatar.Scale);
                    hash.Add("GroupName", avatar.GroupName);
                    list.Add(hash);
                }
                textwriter.Write(MakeJson.FromObject(list));
            }
            break;

            case "LoadInventoryFolder":
                client.Inventory.RequestFolderContents(new UUID(POST["UUID"]), client.Self.AgentID, true, true, InventorySortOrder.ByDate | InventorySortOrder.SystemFoldersToTop);
                break;

            case "RequestAsset":
            {
                try
                {
                    UUID inventoryID = new UUID(POST["InventoryID"]);
                    client.Assets.RequestInventoryAsset(new UUID(POST["AssetID"]), inventoryID,
                                                        UUID.Zero, new UUID(POST["OwnerID"]), (AssetType)int.Parse(POST["AssetType"]), false,
                                                        delegate(AssetDownload transfer, OpenMetaverse.Assets.Asset asset) {
                            events.Assets_OnAssetReceived(transfer, asset, inventoryID);
                        }
                                                        );
                }
                catch         // Try catching the error that sometimes gets thrown... but sometimes doesn't.
                {
                }
            }
            break;

            case "SendTeleportLure":
                client.Self.SendTeleportLure(new UUID(POST["Target"]), POST["Message"]);
                break;

            case "ScriptPermissionResponse":
                client.Self.ScriptQuestionReply(client.Network.CurrentSim, new UUID(POST["ItemID"]), new UUID(POST["TaskID"]), (ScriptPermission)int.Parse(POST["Permissions"]));
                break;

            case "ScriptDialogReply":
            {
                ScriptDialogReplyPacket packet = new ScriptDialogReplyPacket();
                packet.AgentData.AgentID   = client.Self.AgentID;
                packet.AgentData.SessionID = client.Self.SessionID;
                packet.Data.ButtonIndex    = int.Parse(POST["ButtonIndex"]);
                packet.Data.ButtonLabel    = Utils.StringToBytes(POST["ButtonLabel"]);
                packet.Data.ChatChannel    = int.Parse(POST["ChatChannel"]);
                packet.Data.ObjectID       = new UUID(POST["ObjectID"]);
                client.Network.SendPacket((Packet)packet);
            }
            break;

            case "SaveNotecard":
                client.Inventory.RequestUploadNotecardAsset(Utils.StringToBytes(POST["AssetData"]), new UUID(POST["ItemID"]), new InventoryManager.InventoryUploadedAssetCallback(events.Inventory_OnNoteUploaded));
                break;

            case "CreateInventory":
                client.Inventory.RequestCreateItem(new UUID(POST["Folder"]), POST["Name"], POST["Description"], (AssetType)int.Parse(POST["AssetType"]), UUID.Random(), (InventoryType)int.Parse(POST["InventoryType"]), PermissionMask.All, new InventoryManager.ItemCreatedCallback(events.Inventory_OnItemCreated));
                break;

            case "CreateFolder":
            {
                UUID folder = client.Inventory.CreateFolder(new UUID(POST["Parent"]), POST["Name"]);
                textwriter.Write("{FolderID: \"" + folder + "\"}");
            }
            break;

            case "EmptyTrash":
                client.Inventory.EmptyTrash();
                break;

            case "MoveItem":
                client.Inventory.MoveItem(new UUID(POST["Item"]), new UUID(POST["TargetFolder"]), POST["NewName"]);
                break;

            case "MoveFolder":
                client.Inventory.MoveFolder(new UUID(POST["Folder"]), new UUID(POST["NewParent"]));
                break;

            case "MoveItems":
            case "MoveFolders":
            {
                Dictionary <UUID, UUID> dict = new Dictionary <UUID, UUID>();
                string[] moves = POST["ToMove"].Split(',');
                for (int i = 0; i < moves.Length; ++i)
                {
                    string[] move = moves[i].Split(' ');
                    dict.Add(new UUID(move[0]), new UUID(move[1]));
                }
                if (messagetype == "MoveItems")
                {
                    client.Inventory.MoveItems(dict);
                }
                else if (messagetype == "MoveFolders")
                {
                    client.Inventory.MoveFolders(dict);
                }
            }
            break;

            case "DeleteItem":
                client.Inventory.RemoveItem(new UUID(POST["Item"]));
                break;

            case "DeleteFolder":
                client.Inventory.RemoveFolder(new UUID(POST["Folder"]));
                break;

            case "DeleteMultiple":
            {
                string[]    items    = POST["Items"].Split(',');
                List <UUID> itemlist = new List <UUID>();
                for (int i = 0; i < items.Length; ++i)
                {
                    itemlist.Add(new UUID(items[i]));
                }
                string[]    folders    = POST["Folders"].Split(',');
                List <UUID> folderlist = new List <UUID>();
                for (int i = 0; i < items.Length; ++i)
                {
                    folderlist.Add(new UUID(folders[i]));
                }
                client.Inventory.Remove(itemlist, folderlist);
            }
            break;

            case "GiveInventory":
            {
                client.Inventory.GiveItem(new UUID(POST["ItemID"]), POST["ItemName"], (AssetType)int.Parse(POST["AssetType"]), new UUID(POST["Recipient"]), true);
            }
            break;

            case "UpdateItem":
            {
                InventoryItem item = client.Inventory.FetchItem(new UUID(POST["ItemID"]), new UUID(POST["OwnerID"]), 1000);
                if (POST.ContainsKey("Name"))
                {
                    item.Name = POST["Name"];
                }
                if (POST.ContainsKey("Description"))
                {
                    item.Description = POST["Description"];
                }
                if (POST.ContainsKey("NextOwnerMask"))
                {
                    item.Permissions.NextOwnerMask = (PermissionMask)uint.Parse(POST["NextOwnerMask"]);
                }
                if (POST.ContainsKey("SalePrice"))
                {
                    item.SalePrice = int.Parse(POST["SalePrice"]);
                }
                if (POST.ContainsKey("SaleType"))
                {
                    item.SaleType = (SaleType)int.Parse(POST["SaleType"]);                                       // This should be byte.Parse, but this upsets mono's compiler (CS1002)
                }
                client.Inventory.RequestUpdateItem(item);
            }
            break;

            case "UpdateFolder":
            {
                UpdateInventoryFolderPacket packet = new UpdateInventoryFolderPacket();
                packet.AgentData.AgentID      = client.Self.AgentID;
                packet.AgentData.SessionID    = client.Self.SessionID;
                packet.FolderData             = new UpdateInventoryFolderPacket.FolderDataBlock[1];
                packet.FolderData[0]          = new UpdateInventoryFolderPacket.FolderDataBlock();
                packet.FolderData[0].FolderID = new UUID(POST["FolderID"]);
                packet.FolderData[0].ParentID = new UUID(POST["ParentID"]);
                packet.FolderData[0].Type     = sbyte.Parse(POST["Type"]);
                packet.FolderData[0].Name     = Utils.StringToBytes(POST["Name"]);
                client.Network.SendPacket((Packet)packet);
            }
            break;

            case "FetchItem":
                client.Inventory.FetchItem(new UUID(POST["Item"]), new UUID(POST["Owner"]), 5000);
                break;

            case "ReRotate":
                user.Rotation = -Math.PI;
                break;

            case "StartGroupIM":
                AjaxLife.Debug("SendMessage", "RequestJoinGroupChat(" + POST["Group"] + ")");
                client.Self.RequestJoinGroupChat(new UUID(POST["Group"]));
                break;

            case "GroupInstantMessage":
                client.Self.InstantMessageGroup(new UUID(POST["Group"]), POST["Message"]);
                break;

            case "RequestGroupProfile":
                client.Groups.RequestGroupProfile(new UUID(POST["Group"]));
                break;

            case "RequestGroupMembers":
                client.Groups.RequestGroupMembers(new UUID(POST["Group"]));
                break;

            case "RequestGroupName":
                client.Groups.RequestGroupName(new UUID(POST["ID"]));
                break;

            case "JoinGroup":
                client.Groups.RequestJoinGroup(new UUID(POST["Group"]));
                break;

            case "LeaveGroup":
                client.Groups.LeaveGroup(new UUID(POST["Group"]));
                break;

            case "RequestCurrentGroups":
                client.Groups.RequestCurrentGroups();
                break;

            case "GetParcelID":
                textwriter.Write("{\"LocalID\": " + client.Parcels.GetParcelLocalID(client.Network.CurrentSim, new Vector3(float.Parse(POST["X"]), float.Parse(POST["Y"]), float.Parse(POST["Z"]))) + "}");
                break;

            case "RequestParcelProperties":
                client.Parcels.RequestParcelProperties(client.Network.CurrentSim, int.Parse(POST["LocalID"]), int.Parse(POST["SequenceID"]));
                break;
            }
            textwriter.Flush();
        }
Ejemplo n.º 27
0
        protected override void StoreFriendships(UUID agentID, UUID friendID)
        {
            Boolean agentIsLocal  = true;
            Boolean friendIsLocal = true;

            if (UserManagementModule != null)
            {
                agentIsLocal  = UserManagementModule.IsLocalGridUser(agentID);
                friendIsLocal = UserManagementModule.IsLocalGridUser(friendID);
            }

            // Are they both local users?
            if (agentIsLocal && friendIsLocal)
            {
                // local grid users
                m_log.DebugFormat("[HGFRIENDS MODULE]: Users are both local");
                DeletePreviousHGRelations(agentID, friendID);
                base.StoreFriendships(agentID, friendID);
                return;
            }

            // ok, at least one of them is foreigner, let's get their data
            IClientAPI       agentClient         = LocateClientObject(agentID);
            IClientAPI       friendClient        = LocateClientObject(friendID);
            AgentCircuitData agentClientCircuit  = null;
            AgentCircuitData friendClientCircuit = null;
            string           agentUUI            = string.Empty;
            string           friendUUI           = string.Empty;
            string           agentFriendService  = string.Empty;
            string           friendFriendService = string.Empty;

            if (agentClient != null)
            {
                agentClientCircuit = ((Scene)(agentClient.Scene)).AuthenticateHandler.GetAgentCircuitData(agentClient.CircuitCode);
                agentUUI           = Util.ProduceUserUniversalIdentifier(agentClientCircuit);
                agentFriendService = agentClientCircuit.ServiceURLs["FriendsServerURI"].ToString();
                RecacheFriends(agentClient);
            }
            if (friendClient != null)
            {
                friendClientCircuit = ((Scene)(friendClient.Scene)).AuthenticateHandler.GetAgentCircuitData(friendClient.CircuitCode);
                friendUUI           = Util.ProduceUserUniversalIdentifier(friendClientCircuit);
                friendFriendService = friendClientCircuit.ServiceURLs["FriendsServerURI"].ToString();
                RecacheFriends(friendClient);
            }

            m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}",
                              agentUUI, friendUUI, agentFriendService, friendFriendService);

            // Generate a random 8-character hex number that will sign this friendship
            string secret = UUID.Random().ToString().Substring(0, 8);

            string theFriendUUID = friendUUI + ";" + secret;
            string agentUUID     = agentUUI + ";" + secret;

            if (agentIsLocal) // agent is local, 'friend' is foreigner
            {
                // This may happen when the agent returned home, in which case the friend is not there
                // We need to look for its information in the friends list itself
                FriendInfo[] finfos     = null;
                bool         confirming = false;
                if (friendUUI == string.Empty)
                {
                    finfos = GetFriendsFromCache(agentID);
                    foreach (FriendInfo finfo in finfos)
                    {
                        if (finfo.TheirFlags == -1)
                        {
                            if (finfo.Friend.StartsWith(friendID.ToString()))
                            {
                                friendUUI     = finfo.Friend;
                                theFriendUUID = friendUUI;
                                UUID   utmp  = UUID.Zero;
                                string url   = String.Empty;
                                string first = String.Empty;
                                string last  = String.Empty;

                                // If it's confirming the friendship, we already have the full UUI with the secret
                                if (Util.ParseUniversalUserIdentifier(theFriendUUID, out utmp, out url, out first, out last, out secret))
                                {
                                    agentUUID = agentUUI + ";" + secret;
                                    m_uMan.AddUser(utmp, first, last, url);
                                }
                                confirming = true;
                                break;
                            }
                        }
                    }
                    if (!confirming)
                    {
                        friendUUI     = m_uMan.GetUserUUI(friendID);
                        theFriendUUID = friendUUI + ";" + secret;
                    }

                    friendFriendService = m_uMan.GetUserServerURL(friendID, "FriendsServerURI");

                    //            m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}",
                    //              agentUUI, friendUUI, agentFriendService, friendFriendService);
                }

                // Delete any previous friendship relations
                DeletePreviousRelations(agentID, friendID);

                // store in the local friends service a reference to the foreign friend
                FriendsService.StoreFriend(agentID.ToString(), theFriendUUID, 1);
                // and also the converse
                FriendsService.StoreFriend(theFriendUUID, agentID.ToString(), 1);

                //if (!confirming)
                //{
                // store in the foreign friends service a reference to the local agent
                HGFriendsServicesConnector friendsConn = null;
                if (friendClientCircuit != null)     // the friend is here, validate session
                {
                    friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID);
                }
                else     // the friend is not here, he initiated the request in his home world
                {
                    friendsConn = new HGFriendsServicesConnector(friendFriendService);
                }

                friendsConn.NewFriendship(friendID, agentUUID);
                //}
            }
            else if (friendIsLocal) // 'friend' is local,  agent is foreigner
            {
                // Delete any previous friendship relations
                DeletePreviousRelations(agentID, friendID);

                // store in the local friends service a reference to the foreign agent
                FriendsService.StoreFriend(friendID.ToString(), agentUUI + ";" + secret, 1);
                // and also the converse
                FriendsService.StoreFriend(agentUUI + ";" + secret, friendID.ToString(), 1);

                if (agentClientCircuit != null)
                {
                    // store in the foreign friends service a reference to the local agent
                    HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID);
                    friendsConn.NewFriendship(agentID, friendUUI + ";" + secret);
                }
            }
            else // They're both foreigners!
            {
                HGFriendsServicesConnector friendsConn;
                if (agentClientCircuit != null)
                {
                    friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID);
                    friendsConn.NewFriendship(agentID, friendUUI + ";" + secret);
                }
                if (friendClientCircuit != null)
                {
                    friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID);
                    friendsConn.NewFriendship(friendID, agentUUI + ";" + secret);
                }
            }
            // my brain hurts now
        }
Ejemplo n.º 28
0
        public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID,
                                   string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP)
        {
            bool success = false;
            UUID session = UUID.Random();

            m_log.InfoFormat("[LLOGIN SERVICE]: Login request for {0} {1} at {2} using viewer {3}, channel {4}, IP {5}, Mac {6}, Id0 {7}",
                             firstName, lastName, startLocation, clientVersion, channel, clientIP.Address.ToString(), mac, id0);

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

                    if (!am.Success)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is not allowed",
                            firstName, lastName, clientVersion);
                        return(LLFailedLoginResponse.LoginBlockedProblem);
                    }
                }

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

                    if (dm.Success)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is denied",
                            firstName, lastName, clientVersion);
                        return(LLFailedLoginResponse.LoginBlockedProblem);
                    }
                }

                //
                // Get the account and check that it exists
                //
                UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName);
                if (account == null)
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user not found", firstName, lastName);
                    return(LLFailedLoginResponse.UserProblem);
                }

                if (account.UserLevel < m_MinLoginLevel)
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user level is {2} but minimum login level is {3}",
                        firstName, lastName, account.UserLevel, m_MinLoginLevel);
                    return(LLFailedLoginResponse.LoginBlockedProblem);
                }

                // If a scope id is requested, check that the account is in
                // that scope, or unscoped.
                //
                if (scopeID != UUID.Zero)
                {
                    if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed, reason: user {0} {1} not found", firstName, lastName);
                        return(LLFailedLoginResponse.UserProblem);
                    }
                }
                else
                {
                    scopeID = account.ScopeID;
                }

                //
                // Authenticate this user
                //
                if (!passwd.StartsWith("$1$"))
                {
                    passwd = "$1$" + Util.Md5Hash(passwd);
                }
                passwd = passwd.Remove(0, 3); //remove $1$
                string token         = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
                UUID   secureSession = UUID.Zero;
                if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: authentication failed",
                        firstName, lastName);
                    return(LLFailedLoginResponse.UserProblem);
                }

                //
                // Get the user's inventory
                //
                if (m_RequireInventory && m_InventoryService == null)
                {
                    m_log.WarnFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: inventory service not set up",
                        firstName, lastName);
                    return(LLFailedLoginResponse.InventoryProblem);
                }

                if (m_HGInventoryService != null)
                {
                    // Give the Suitcase service a chance to create the suitcase folder.
                    // (If we're not using the Suitcase inventory service then this won't do anything.)
                    m_HGInventoryService.GetRootFolder(account.PrincipalID);
                }

                List <InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
                if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
                {
                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed, for {0} {1}, reason: unable to retrieve user inventory",
                        firstName, lastName);
                    return(LLFailedLoginResponse.InventoryProblem);
                }

                // Get active gestures
                List <InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
//                m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);

                //
                // Login the presence
                //
                if (m_PresenceService != null)
                {
                    success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);

                    if (!success)
                    {
                        m_log.InfoFormat(
                            "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: could not login presence",
                            firstName, lastName);
                        return(LLFailedLoginResponse.GridProblem);
                    }
                }

                //
                // Change Online status and get the home region
                //
                GridRegion   home   = null;
                GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString());

                // We are only going to complain about no home if the user actually tries to login there, to avoid
                // spamming the console.
                if (guinfo != null)
                {
                    if (guinfo.HomeRegionID == UUID.Zero && startLocation == "home")
                    {
                        m_log.WarnFormat(
                            "[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location but they have none set",
                            account.Name);
                    }
                    else if (m_GridService != null)
                    {
                        home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);

                        if (home == null && startLocation == "home")
                        {
                            m_log.WarnFormat(
                                "[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location with ID {1} but this was not found.",
                                account.Name, guinfo.HomeRegionID);
                        }
                    }
                }
                else
                {
                    // something went wrong, make something up, so that we don't have to test this anywhere else
                    m_log.DebugFormat("{0} Failed to fetch GridUserInfo. Creating empty GridUserInfo as home", LogHeader);
                    guinfo = new GridUserInfo();
                    guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
                }

                //
                // Find the destination region/grid
                //
                string where = string.Empty;
                Vector3       position   = Vector3.Zero;
                Vector3       lookAt     = Vector3.Zero;
                GridRegion    gatekeeper = null;
                TeleportFlags flags;
                GridRegion    destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags);
                if (destination == null)
                {
                    m_PresenceService.LogoutAgent(session);

                    m_log.InfoFormat(
                        "[LLOGIN SERVICE]: Login failed for {0} {1}, reason: destination not found",
                        firstName, lastName);
                    return(LLFailedLoginResponse.GridProblem);
                }
                else
                {
                    m_log.DebugFormat(
                        "[LLOGIN SERVICE]: Found destination {0}, endpoint {1} for {2} {3}",
                        destination.RegionName, destination.ExternalEndPoint, firstName, lastName);
                }

                if (account.UserLevel >= 200)
                {
                    flags |= TeleportFlags.Godlike;
                }
                //
                // Get the avatar
                //
                AvatarAppearance avatar = null;
                if (m_AvatarService != null)
                {
                    avatar = m_AvatarService.GetAppearance(account.PrincipalID);
                }

                //
                // Instantiate/get the simulation interface and launch an agent at the destination
                //
                string           reason = string.Empty;
                GridRegion       dest;
                AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where,
                                                              clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest);
                destination = dest;
                if (aCircuit == null)
                {
                    m_PresenceService.LogoutAgent(session);
                    m_log.InfoFormat("[LLOGIN SERVICE]: Login failed for {0} {1}, reason: {2}", firstName, lastName, reason);
                    return(new LLFailedLoginResponse("key", reason, "false"));
                }
                // Get Friends list
                FriendInfo[] friendsList = new FriendInfo[0];
                if (m_FriendsService != null)
                {
                    friendsList = m_FriendsService.GetFriends(account.PrincipalID);
//                    m_log.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
                }

                //
                // Finally, fill out the response and return it
                //
                LLLoginResponse response
                    = new LLLoginResponse(
                          account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
                          where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP,
                          m_MapTileURL, m_ProfileURL, m_OpenIDURL, m_SearchURL, m_Currency, m_DSTZone,
                          m_DestinationGuide, m_AvatarPicker, m_ClassifiedFee);

                m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to {0} {1}", firstName, lastName);

                return(response);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace);
                if (m_PresenceService != null)
                {
                    m_PresenceService.LogoutAgent(session);
                }
                return(LLFailedLoginResponse.InternalError);
            }
        }
Ejemplo n.º 29
0
 public BaseOpenSimServer() : base()
 {
     // Random uuid for private data
     m_osSecret = UUID.Random().ToString();
 }
Ejemplo n.º 30
0
        /// <summary>
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="assetDescription"></param>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="parentFolder"></param>
        /// <param name="data"></param>
        /// <param name="inventoryType"></param>
        /// <param name="assetType"></param>
        /// <param name="everyone_mask"></param>
        /// <param name="group_mask"></param>
        /// <param name="next_owner_mask"></param>
        public UUID UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, uint everyone_mask, uint group_mask, uint next_owner_mask)
        {
            sbyte assType = 0;
            sbyte inType  = 0;

            switch (inventoryType)
            {
            case "sound":
                inType  = 1;
                assType = 1;
                break;

            case "animation":
                inType  = 19;
                assType = 20;
                break;

            case "snapshot":
                inType  = 15;
                assType = 0;
                break;

            case "wearable":
                inType = 18;
                switch (assetType)
                {
                case "bodypart":
                    assType = 13;
                    break;

                case "clothing":
                    assType = 5;
                    break;
                }
                break;

            case "object":
            {
                inType  = (sbyte)InventoryType.Object;
                assType = (sbyte)AssetType.Object;

                List <Vector3>    positions     = new List <Vector3>();
                List <Quaternion> rotations     = new List <Quaternion>();
                OSDMap            request       = (OSDMap)OSDParser.DeserializeLLSDXml(data);
                OSDArray          instance_list = (OSDArray)request["instance_list"];
                OSDArray          mesh_list     = (OSDArray)request["mesh_list"];
                OSDArray          texture_list  = (OSDArray)request["texture_list"];
                SceneObjectGroup  grp           = null;

                List <UUID> textures = new List <UUID>();
                foreach (
                    AssetBase textureAsset in
                    texture_list.Select(t => new AssetBase(UUID.Random(), assetName, AssetType.Texture,
                                                           m_agentID)
                    {
                        Data = t.AsBinary()
                    }))
                {
                    textureAsset.ID = m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.ID);
                }

                InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType(m_agentID,
                                                                                     InventoryType.Mesh,
                                                                                     AssetType.Mesh);
                for (int i = 0; i < mesh_list.Count; i++)
                {
                    PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                    Primitive.TextureEntry textureEntry =
                        new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
                    OSDMap inner_instance_list = (OSDMap)instance_list[i];

                    OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
                    for (uint face = 0; face < face_list.Count; face++)
                    {
                        OSDMap faceMap = (OSDMap)face_list[(int)face];
                        Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                        if (faceMap.ContainsKey("fullbright"))
                        {
                            f.Fullbright = faceMap["fullbright"].AsBoolean();
                        }
                        if (faceMap.ContainsKey("diffuse_color"))
                        {
                            f.RGBA = faceMap["diffuse_color"].AsColor4();
                        }

                        int   textureNum = faceMap["image"].AsInteger();
                        float imagerot   = faceMap["imagerot"].AsInteger();
                        float offsets    = (float)faceMap["offsets"].AsReal();
                        float offsett    = (float)faceMap["offsett"].AsReal();
                        float scales     = (float)faceMap["scales"].AsReal();
                        float scalet     = (float)faceMap["scalet"].AsReal();

                        if (imagerot != 0)
                        {
                            f.Rotation = imagerot;
                        }
                        if (offsets != 0)
                        {
                            f.OffsetU = offsets;
                        }
                        if (offsett != 0)
                        {
                            f.OffsetV = offsett;
                        }
                        if (scales != 0)
                        {
                            f.RepeatU = scales;
                        }
                        if (scalet != 0)
                        {
                            f.RepeatV = scalet;
                        }
                        f.TextureID = textures.Count > textureNum
                                                  ? textures[textureNum]
                                                  : Primitive.TextureEntry.WHITE_TEXTURE;
                        textureEntry.FaceTextures[face] = f;
                    }
                    pbs.TextureEntry = textureEntry.GetBytes();

                    AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, AssetType.Mesh, m_agentID)
                    {
                        Data = mesh_list[i].AsBinary()
                    };
                    meshAsset.ID = m_assetService.Store(meshAsset);

                    if (meshFolder == null)
                    {
                        m_inventoryService.CreateUserInventory(m_agentID, false);
                        meshFolder = m_inventoryService.GetFolderForType(m_agentID, InventoryType.Mesh,
                                                                         AssetType.Mesh);
                    }

                    InventoryItemBase itemBase = new InventoryItemBase(UUID.Random(), m_agentID)
                    {
                        AssetType           = (sbyte)AssetType.Mesh,
                        AssetID             = meshAsset.ID,
                        CreatorId           = m_agentID.ToString(),
                        Folder              = meshFolder.ID,
                        InvType             = (int)InventoryType.Texture,
                        Name                = "(Mesh) - " + assetName,
                        CurrentPermissions  = (uint)PermissionMask.All,
                        BasePermissions     = (uint)PermissionMask.All,
                        EveryOnePermissions = everyone_mask,
                        GroupPermissions    = group_mask,
                        NextPermissions     = next_owner_mask
                    };
                    //Bad... but whatever
                    m_inventoryService.AddItem(itemBase);

                    pbs.SculptEntry   = true;
                    pbs.SculptTexture = meshAsset.ID;
                    pbs.SculptType    = (byte)SculptType.Mesh;
                    pbs.SculptData    = meshAsset.Data;

                    Vector3    position = inner_instance_list["position"].AsVector3();
                    Vector3    scale    = inner_instance_list["scale"].AsVector3();
                    Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

                    int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                    int material         = inner_instance_list["material"].AsInteger();
                    int mesh             = inner_instance_list["mesh"].AsInteger();

                    SceneObjectPart prim = new SceneObjectPart(m_agentID, pbs, position, Quaternion.Identity,
                                                               Vector3.Zero, assetName)
                    {
                        Scale = scale, AbsolutePosition = position
                    };

                    rotations.Add(rotation);
                    positions.Add(position);
                    prim.UUID         = UUID.Random();
                    prim.CreatorID    = m_agentID;
                    prim.OwnerID      = m_agentID;
                    prim.GroupID      = UUID.Zero;
                    prim.LastOwnerID  = m_agentID;
                    prim.CreationDate = Util.UnixTimeSinceEpoch();
                    prim.Name         = assetName;
                    prim.Description  = "";
                    prim.PhysicsType  = (byte)physicsShapeType;

                    prim.BaseMask      = (uint)PermissionMask.All;
                    prim.EveryoneMask  = everyone_mask;
                    prim.NextOwnerMask = next_owner_mask;
                    prim.GroupMask     = group_mask;
                    prim.OwnerMask     = (uint)PermissionMask.All;

                    if (grp == null)
                    {
                        grp = new SceneObjectGroup(prim, null);
                    }
                    else
                    {
                        grp.AddChild(prim, i + 1);
                    }
                    grp.RootPart.IsAttachment = false;
                }
                if (grp.ChildrenList.Count > 1)         //Fix first link #
                {
                    grp.RootPart.LinkNum++;
                }

                Vector3 rootPos = positions[0];
                grp.SetAbsolutePosition(false, rootPos);
                for (int i = 0; i < positions.Count; i++)
                {
                    Vector3 offset = positions[i] - rootPos;
                    grp.ChildrenList[i].SetOffsetPosition(offset);
                }
                for (int i = 0; i < rotations.Count; i++)
                {
                    if (i != 0)
                    {
                        grp.ChildrenList[i].SetRotationOffset(false, rotations[i], false);
                    }
                }
                grp.UpdateGroupRotationR(rotations[0]);
                data = Encoding.ASCII.GetBytes(grp.ToXml2());
            }
            break;
            }
            AssetBase asset = new AssetBase(assetID, assetName, (AssetType)assType, m_agentID)
            {
                Data = data
            };

            asset.ID = m_assetService.Store(asset);
            assetID  = asset.ID;

            InventoryItemBase item = new InventoryItemBase
            {
                Owner               = m_agentID,
                CreatorId           = m_agentID.ToString(),
                ID                  = inventoryItem,
                AssetID             = asset.ID,
                Description         = assetDescription,
                Name                = assetName,
                AssetType           = assType,
                InvType             = inType,
                Folder              = parentFolder,
                CurrentPermissions  = (uint)PermissionMask.All,
                BasePermissions     = (uint)PermissionMask.All,
                EveryOnePermissions = everyone_mask,
                NextPermissions     = next_owner_mask,
                GroupPermissions    = group_mask,
                CreationDate        = Util.UnixTimeSinceEpoch()
            };

            m_inventoryService.AddItem(item);

            return(assetID);
        }