public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // path = /wifi/...
            //m_log.DebugFormat("[Wifi]: path = {0}", path);
            //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint);
            //foreach (object o in httpRequest.Query.Keys)
            //    m_log.DebugFormat("  >> {0}={1}", o, httpRequest.Query[o]);

            string result = string.Empty;
            try
            {
                Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language")));
                Environment env = new Environment(request);

                result = m_WebApp.Services.LogoutRequest(env);

                httpResponse.ContentType = "text/html";
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[LOGOUT HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace);
            }

            return WebAppUtils.StringToBytes(result);
        }
        protected override byte[] ProcessRequest(string path, Stream request,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            bool result = false;

            string[] p = SplitParams(path);

            if (p.Length > 0)
            {
                if (m_allowedTypes != AllowedRemoteDeleteTypes.None)
                {
                    string assetID = p[0];

                    AssetBase asset = m_AssetService.Get(assetID);
                    if (asset != null)
                    {
                        if (m_allowedTypes == AllowedRemoteDeleteTypes.All
                            || (int)(asset.Flags & AssetFlags.Maptile) != 0)
                        {
                            result = m_AssetService.Delete(assetID);
                        }
                        else
                        {
                            m_log.DebugFormat(
                                "[ASSET SERVER DELETE HANDLER]: Request to delete asset {0}, but type is {1} and allowed remote delete types are {2}",
                                assetID, (AssetFlags)asset.Flags, m_allowedTypes);
                        }
                    }
                }
            }

            XmlSerializer xs = new XmlSerializer(typeof(bool));
            return ServerUtils.SerializeResult(xs, result);
        }
        public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            m_log.Info("-");
            Dictionary<string, object> request = Werkzeuge.createDictionaryFromHttpRequest(httpRequest);
            string data = Werkzeuge.createPOSTDataFromHttpRequest(httpRequest);

            httpResponse.StatusCode = (int)HttpStatusCode.OK;
            httpResponse.StatusDescription = "OK";
            httpResponse.ContentType = "test/plain";
            
            if (Werkzeuge.getValueFromDictionary(request, "methode").ToLower() == "stop")
            {
                m_log.Info("[WakeUpService] Region " + Werkzeuge.getValueFromDictionary(request, "uuid") + " wants to be stopped.");

                restData restDataObject = new restData();
                restDataObject.regionUUID = UUID.Parse(Werkzeuge.getValueFromDictionary(request, "uuid"));
                restDataObject.postDaten = Encoding.ASCII.GetBytes(data);
                restDataObject.startURI = Werkzeuge.getValueFromDictionary(request, "starturl");
                restDataObject.stoptURI = Werkzeuge.getValueFromDictionary(request, "stopurl");
                restDataObject.daten = data;
                restDataManager.add(restDataObject);

                Werkzeuge.makeHTTPCall(restDataObject.stoptURI, restDataObject.postDaten);
            }

            StreamWriter sw = new StreamWriter(httpResponse.OutputStream);
            sw.Write("ok");

            return new byte[0];
        }
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // Try to parse the texture ID from the request URL
            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
            string names = query.GetOne("names");
            string psize = query.GetOne("page_size");
            string pnumber = query.GetOne("page");

            if (m_PeopleService == null)
                return FailureResponse(names, (int)System.Net.HttpStatusCode.InternalServerError, httpResponse);

            if (string.IsNullOrEmpty(names) || names.Length < 3)
                return FailureResponse(names, (int)System.Net.HttpStatusCode.BadRequest, httpResponse);

            m_log.DebugFormat("[AVATAR PICKER SEARCH]: search for {0}", names);

            int page_size = (string.IsNullOrEmpty(psize) ? 500 : Int32.Parse(psize));
            int page_number = (string.IsNullOrEmpty(pnumber) ? 1 : Int32.Parse(pnumber));
            
            // Full content request
            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
            //httpResponse.ContentLength = ??;
            httpResponse.ContentType = "application/llsd+xml";

            List<UserData> users = m_PeopleService.GetUserData(names, page_size, page_number);

            LLSDAvatarPicker osdReply = new LLSDAvatarPicker();
            osdReply.next_page_url = httpRequest.RawUrl;
            foreach (UserData u in users)
                osdReply.agents.Array.Add(ConvertUserData(u));

            string reply = LLSDHelpers.SerialiseLLSDReply(osdReply);
            return System.Text.Encoding.UTF8.GetBytes(reply);
        }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // path = /wifi/...
            //m_log.DebugFormat("[Wifi]: path = {0}", path);
            //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint);
            //foreach (object o in httpRequest.Query.Keys)
            //    m_log.DebugFormat("  >> {0}={1}", o, httpRequest.Query[o]);
            httpResponse.ContentType = "text/html";
            string resource = GetParam(path);
            //m_log.DebugFormat("[USER ACCOUNT HANDLER GET]: resource {0}", resource);

            Request request = WifiUtils.CreateRequest(string.Empty, httpRequest);
            Diva.Wifi.Environment env = new Diva.Wifi.Environment(request);

            string result = string.Empty;
            UUID userID = UUID.Zero;
            if (resource == string.Empty || resource == "/")
            {
                result = m_WebApp.Services.NewAccountGetRequest(env);
            }
            else
            {
                //UUID.TryParse(resource.Trim(new char[] {'/'}), out userID);
                if (resource.Trim(new char[] {'/'}).StartsWith("edit"))
                    result = m_WebApp.Services.UserAccountGetRequest(env, userID);
            }

            return WifiUtils.StringToBytes(result);
        }
        protected override byte[] ProcessRequest(string path, Stream request,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            string[] p = SplitParams(path);

            if (p.Length > 0)
            {
                switch (p[0])
                {
                case "plain":
                    StreamReader sr = new StreamReader(request);
                    string body = sr.ReadToEnd();
                    sr.Close();

                    return DoPlainMethods(body);
                case "crypt":
                    byte[] buffer = new byte[request.Length];
                    long length = request.Length;
                    if (length > 16384)
                        length = 16384;
                    request.Read(buffer, 0, (int)length);

                    return DoEncryptedMethods(buffer);
                }
            }
            return new byte[0];
        }
Пример #7
0
        public string FetchInventoryRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
//            m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capabilty request");

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

            string reply;
            LLSDFetchInventory llsdReply = new LLSDFetchInventory();

            foreach (OSDMap osdItemId in itemsRequested)
            {
                UUID itemId = osdItemId["item_id"].AsUUID();

                InventoryItemBase item = m_inventoryService.GetItem(new InventoryItemBase(itemId, m_agentID));

                if (item != null)
                {
                    // We don't know the agent that this request belongs to so we'll use the agent id of the item
                    // which will be the same for all items.
                    llsdReply.agent_id = item.Owner;

                    llsdReply.items.Array.Add(ConvertInventoryItem(item));
                }
            }

            reply = LLSDHelpers.SerialiseLLSDReply(llsdReply);

            return reply;
        }
        protected override byte[] ProcessRequest(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            httpResponse.ContentType = "image/jpeg";

//            StreamReader sr = new StreamReader(requestData);
//            string body = sr.ReadToEnd();
//            sr.Close();
//            body = body.Trim();

            try
            {
                Dictionary<string, object> request =
                        new Dictionary<string, object>();
                foreach (string name in httpRequest.QueryString)
                    request[name] = httpRequest.QueryString[name];

                return SendWorldView(request);
            }
            catch (Exception e)
            {
                m_log.Debug("[WORLDVIEW]: Exception: " + e.ToString());
            }

            return new Byte[0];
        }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            string result = string.Empty;
            try
            {
                Request request = RequestFactory.CreateRequest(string.Empty, httpRequest);
                Diva.Wifi.Environment env = new Diva.Wifi.Environment(request);

                string resource = GetParam(path);
                //m_log.DebugFormat("[XXX]: resource {0}", resource);
                if (resource.StartsWith("/data/simulators"))
                {
                    result = m_WebApp.Services.ConsoleSimulatorsRequest(env);
                    httpResponse.ContentType = "application/xml";
                }
                else if (resource.StartsWith("/heartbeat"))
                {
                    result = m_WebApp.Services.ConsoleHeartbeat(env);
                    httpResponse.ContentType = "application/xml";
                }
                else
                {
                    result = m_WebApp.Services.ConsoleRequest(env);
                    httpResponse.ContentType = "text/html";
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[CONSOLE HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace);
            }

            return WebAppUtils.StringToBytes(result);
        }
        protected override byte[] ProcessRequest(string path, Stream request,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            AssetBase asset;
            XmlSerializer xs = new XmlSerializer(typeof(AssetBase));

            try
            {
                asset = (AssetBase)xs.Deserialize(request);
            }
            catch (Exception)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                return null;
            }

            string[] p = SplitParams(path);
            if (p.Length > 0)
            {
                string id = p[0];
                bool result = m_AssetService.UpdateContent(id, asset.Data);

                xs = new XmlSerializer(typeof(bool));
                return ServerUtils.SerializeResult(xs, result);
            }
            else
            {
                string id = m_AssetService.Store(asset);

                xs = new XmlSerializer(typeof(string));
                return ServerUtils.SerializeResult(xs, id);
            }
        }
Пример #11
0
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            string resource = GetParam(path);
            resource = resource.Trim(WebAppUtils.DirectorySeparatorChars);
            string resourcePath = System.IO.Path.Combine(m_LocalPath, resource);
            resourcePath = Uri.UnescapeDataString(resourcePath);
            m_log.DebugFormat("[Wifi]: resourcePath {0}", resourcePath);

            string type = WebAppUtils.GetContentType(resource);
            httpResponse.ContentType = type;
            //m_log.DebugFormat("[Wifi]: ContentType {0}", type);
            if (type.StartsWith("image"))
                return WebAppUtils.ReadBinaryResource(new string[] {resourcePath});

            if (type.StartsWith("application") || type.StartsWith("text"))
            {
                string res = WebAppUtils.ReadTextResource(new string[] {resourcePath}, WebApp.MissingPage, true);
                return WebAppUtils.StringToBytes(res);
            }

            m_log.WarnFormat("[Wifi]: Could not find resource {0} in local path {1}", resource, m_LocalPath);
            httpResponse.ContentType = "text/plain";
            string result = "Boo!";
            return WebAppUtils.StringToBytes(result);
        }
Пример #12
0
        public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            byte[] data = ReadFully(request);
            string param = GetParam(path);
            string responseString = m_method(data, path, param);

            return Encoding.UTF8.GetBytes(responseString);
        }
Пример #13
0
 public override byte[] Handle(string path, Stream request,
         IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
 {
     // Not implemented yet
     Console.WriteLine("--- Get region --- " + path);
     httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
     return new byte[] { };
 }
 private byte[] OKResponse(IOSHttpResponse httpResponse)
 {
     m_log.Debug("[HELO]: hi, GET was called");
     httpResponse.AddHeader("X-Handlers-Provided", m_HandlersType);
     httpResponse.StatusCode = (int)HttpStatusCode.OK;
     httpResponse.StatusDescription = "OK";
     return new byte[0];
 }
Пример #15
0
        public virtual void Handle(
            string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            RequestsReceived++;

            ProcessRequest(path, request, response, httpRequest, httpResponse);

            RequestsHandled++;
        }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // path = /wifi/...
            //m_log.DebugFormat("[Wifi]: path = {0}", path);
            //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint);
            //foreach (object o in httpRequest.Query.Keys)
            //    m_log.DebugFormat("  >> {0}={1}", o, httpRequest.Query[o]);

            string resource = GetParam(path);
            //m_log.DebugFormat("[Wifi]: resource {0}", resource);
            resource = Uri.UnescapeDataString(resource).Trim(WebAppUtils.DirectorySeparatorChars);

            Request request = RequestFactory.CreateRequest(resource, httpRequest);
            Diva.Wifi.Environment env = new Diva.Wifi.Environment(request);

            if (resource == string.Empty || resource.StartsWith("index."))
            {
                if (m_WebApp.StatisticsUpdateInterval != TimeSpan.Zero)
                    m_WebApp.Services.ComputeStatistics();

                httpResponse.ContentType = "text/html";

                return WebAppUtils.StringToBytes(m_WebApp.Services.DefaultRequest(env));
            }
            else
            {
                string resourcePath = System.IO.Path.Combine(WebApp.DocsPath, resource);
                string type = WebAppUtils.GetContentType(resource);
                httpResponse.ContentType = type;
                //m_log.DebugFormat("[Wifi]: ContentType {0}", type);
                if (type.StartsWith("image"))
                    return WebAppUtils.ReadBinaryResource(resourcePath);

                if (type.StartsWith("application"))
                {
                    string res = WebAppUtils.ReadTextResource(resourcePath, true);
                    return WebAppUtils.StringToBytes(res);
                }
                if (type.StartsWith("text"))
                {
                    if (m_WebApp.StatisticsUpdateInterval != TimeSpan.Zero)
                        m_WebApp.Services.ComputeStatistics();

                    resourcePath = Localization.LocalizePath(env, resource);
                    Processor p = new Processor(m_WebApp.WifiScriptFace, env);
                    string res = p.Process(WebAppUtils.ReadTextResource(resourcePath));
                    if (res == string.Empty)
                        res = m_WebApp.Services.DefaultRequest(env);
                    return WebAppUtils.StringToBytes(res);
                }
            }

            httpResponse.ContentType = "text/plain";
            string result = "Boo!";
            return WebAppUtils.StringToBytes(result);
        }
Пример #17
0
        protected override byte[] ProcessRequest(
            string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            string[] p = SplitParams(path);

            if (p.Length == 0)
                return new byte[0];

            return utf8.GetBytes(m_BakesService.Get(p[0]));
        }
        public string FetchInventoryRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            //m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capability request {0}", request);

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

            string reply;
            LLSDFetchInventory llsdReply = new LLSDFetchInventory();

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

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

            InventoryItemBase[] items = null;

            if (m_agentID != UUID.Zero)
            {
                items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs);

                if (items == null)
                {
                    // OMG!!! One by one!!! This is fallback code, in case the backend isn't updated
                    m_log.WarnFormat("[FETCH INVENTORY HANDLER]: GetMultipleItems failed. Falling back to fetching inventory items one by one.");
                    items = new InventoryItemBase[itemsRequested.Count];                   
                    foreach (UUID id in itemIDs)
                        items[i++] = m_inventoryService.GetItem(m_agentID, id);
                }
            }
            else
            {
                items = new InventoryItemBase[itemsRequested.Count];
                foreach (UUID id in itemIDs)
                    items[i++] = m_inventoryService.GetItem(UUID.Zero, id);
            }

            foreach (InventoryItemBase item in items)
            {
                if (item != null)
                {
                    // We don't know the agent that this request belongs to so we'll use the agent id of the item
                    // which will be the same for all items.
                    llsdReply.agent_id = item.Owner;
                    llsdReply.items.Array.Add(ConvertInventoryItem(item));
                }
            }

            reply = LLSDHelpers.SerialiseLLSDReply(llsdReply);

            return reply;
        }
Пример #19
0
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
//            m_log.DebugFormat("[GET_DISPLAY_NAMES]: called {0}", httpRequest.Url.Query);

            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
            string[] ids = query.GetValues("ids");


            if (m_UserManagement == null)
            {
                m_log.Error("[GET_DISPLAY_NAMES]: Cannot fetch display names without a user management component");
                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return new byte[0];
            }

            OSDMap osdReply = new OSDMap();
            OSDArray agents = new OSDArray();

            osdReply["agents"] = agents;
            foreach (string id in ids)
            {
                UUID uuid = UUID.Zero;
                if (UUID.TryParse(id, out uuid))
                {
                    string name = m_UserManagement.GetUserName(uuid);
                    if (!string.IsNullOrEmpty(name))
                    {
                        string[] parts = name.Split(new char[] {' '});
                        OSDMap osdname = new OSDMap();
                        // a date that is valid
//                        osdname["display_name_next_update"] = OSD.FromDate(new DateTime(1970,1,1));
                        // but send one that blocks edition, since we actually don't suport this
                        osdname["display_name_next_update"] = OSD.FromDate(DateTime.UtcNow.AddDays(8));        
                        osdname["display_name_expires"] = OSD.FromDate(DateTime.UtcNow.AddMonths(1));
                        osdname["display_name"] = OSD.FromString(name);
                        osdname["legacy_first_name"] = parts[0];
                        osdname["legacy_last_name"] = parts[1];
                        osdname["username"] = OSD.FromString(name);
                        osdname["id"] = OSD.FromUUID(uuid);
                        osdname["is_display_name_default"] = OSD.FromBoolean(true);

                        agents.Add(osdname);
                    }
                }
            }

            // Full content request
            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
            //httpResponse.ContentLength = ??;
            httpResponse.ContentType = "application/llsd+xml";

            string reply = OSDParser.SerializeLLSDXmlString(osdReply);
            return System.Text.Encoding.UTF8.GetBytes(reply);

        }
Пример #20
0
        public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // Try to parse the texture ID from the request URL
            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
            string textureStr = query.GetOne("texture_id");
            string format = query.GetOne("format");

            //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr);

            if (m_assetService == null)
            {
                m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service");
                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                return null;
            }

            UUID textureID;
            if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
            {
//                m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID);
                
                string[] formats;
                if (format != null && format != string.Empty)
                {
                    formats = new string[1] { format.ToLower() };
                }
                else
                {
                    formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept"));
                    if (formats.Length == 0)
                        formats = new string[1] { DefaultFormat }; // default

                }
                // OK, we have an array with preferred formats, possibly with only one entry

                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                foreach (string f in formats)
                {
                    if (FetchTexture(httpRequest, httpResponse, textureID, f))
                        break;
                }
            }
            else
            {
                m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url);
            }

//            m_log.DebugFormat(
//                "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}",
//                textureID, httpResponse.StatusCode, httpResponse.ContentLength);

            httpResponse.Send();
            return null;
        }
Пример #21
0
        public virtual byte[] Handle(
            string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            RequestsReceived++;

            byte[] result = ProcessRequest(path, request, httpRequest, httpResponse);

            RequestsHandled++;

            return result;
        }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            httpResponse.ContentType = "text/html";

            Request request = WifiUtils.CreateRequest(string.Empty, httpRequest);
            Diva.Wifi.Environment env = new Diva.Wifi.Environment(request);

            string result = m_WebApp.Services.ForgotPasswordGetRequest(env);

            return WifiUtils.StringToBytes(result);
        }
        public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            Dictionary<string, object> request = Werkzeuge.createDictionaryFromHttpRequest(httpRequest);

            if (Werkzeuge.getValueFromDictionary(request, "methode").ToLower() == "start")
            {
                m_log.Info("[WakeUpService] Region " + Werkzeuge.getValueFromDictionary(request, "uuid") + " will starts now.");
                startRegion(UUID.Parse(Werkzeuge.getValueFromDictionary(request, "uuid")));
            }

            return Werkzeuge.StringToByteArray("ok");
        }
Пример #24
0
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // Try to parse the texture ID from the request URL
            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
            string meshStr = query.GetOne("mesh_id");

//            m_log.DebugFormat("Fetching mesh {0}", meshStr);

            UUID meshID = UUID.Zero;
            if (!String.IsNullOrEmpty(meshStr) && UUID.TryParse(meshStr, out meshID))
            {
                if (m_assetService == null)
                {
                    httpResponse.StatusCode = 404;
                    httpResponse.ContentType = "text/plain";
                    byte[] data = Encoding.UTF8.GetBytes("The asset service is unavailable.  So is your mesh.");
                    httpResponse.Body.Write(data, 0, data.Length);
                    return null;
                }

                AssetBase mesh = m_assetService.Get(meshID.ToString());

                if (mesh != null)
                {
                    if (mesh.Type == (SByte)AssetType.Mesh)
                    {
                        byte[] data = mesh.Data;
                        httpResponse.Body.Write(data, 0, data.Length);
                        httpResponse.ContentType = "application/vnd.ll.mesh";
                        httpResponse.StatusCode = 200;
                    }
                    // Optionally add additional mesh types here
                    else
                    {
                        httpResponse.StatusCode = 404;
                        httpResponse.ContentType = "text/plain";
                        byte[] data = Encoding.UTF8.GetBytes("Unfortunately, this asset isn't a mesh.");
                        httpResponse.Body.Write(data, 0, data.Length);
                        httpResponse.KeepAlive = false;
                    }
                }
                else
                {
                    httpResponse.StatusCode = 404;
                    httpResponse.ContentType = "text/plain";
                    byte[] data = Encoding.UTF8.GetBytes("Your Mesh wasn't found.  Sorry!");
                    httpResponse.Body.Write(data, 0, data.Length);
                    httpResponse.KeepAlive = false;
                }
            }

            return null;
        }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            httpResponse.ContentType = "text/html";

            Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language")));
            Environment env = new Environment(request);

            string result = m_WebApp.Services.ForgotPasswordGetRequest(env);

            return WebAppUtils.StringToBytes(result);
        }
Пример #26
0
        public string PostHandler(string request, string path, string param,
                                  IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // foreach (string h in httpRequest.Headers.AllKeys)
            //     foreach (string v in httpRequest.Headers.GetValues(h))
            //         m_log.DebugFormat("{0} IsGod: {1} -> {2}", MsgID, h, v);

            MsgID = RequestID;
            m_log.DebugFormat("{0} POST path {1} param {2}", MsgID, path, param);

            try
            {
                // param empty: new region post
                if (!IsGod(httpRequest))
                    // XXX: this needs to be turned into a FailureUnauthorized(...)
                    return Failure(httpResponse, OSHttpStatusCode.ClientErrorUnauthorized,
                                   "GET", "you are not god");

                if (String.IsNullOrEmpty(param)) return CreateRegion(httpRequest, httpResponse);

                // Parse region ID and other parameters
                param = param.TrimEnd(new char[] {'/'});
                string[] comps = param.Split('/');
                UUID regionID = (UUID) comps[0];

                m_log.DebugFormat("{0} POST region UUID {1}", MsgID, regionID.ToString());
                if (UUID.Zero == regionID) throw new Exception("missing region ID");

                Scene scene = null;
                App.SceneManager.TryGetScene(regionID, out scene);
                if (null == scene)
                    return Failure(httpResponse, OSHttpStatusCode.ClientErrorNotFound,
                                   "POST", "cannot find region {0}", regionID.ToString());

                if (2 == comps.Length)
                {
                    // check for {prims}
                    switch (comps[1].ToLower())
                    {
                        case "prims":
                            return LoadPrims(request, httpRequest, httpResponse, scene);
                    }
                }

                return Failure(httpResponse, OSHttpStatusCode.ClientErrorNotFound,
                               "POST", "url {0} not supported", param);
            }
            catch (Exception e)
            {
                return Failure(httpResponse, OSHttpStatusCode.ServerErrorInternalError, "POST", e);
            }
        }
Пример #27
0
        public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            Encoding encoding = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(request, encoding);

            string requestBody = streamReader.ReadToEnd();
            streamReader.Close();

            string param = GetParam(path);
            string responseString = m_restMethod(requestBody, path, param, httpRequest, httpResponse);

            return Encoding.UTF8.GetBytes(responseString);
        }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // path = /wifi/...
            //m_log.DebugFormat("[Wifi]: path = {0}", path);

            // This is the content type of the response. Don't forget to set it to this in all your handlers.
            httpResponse.ContentType = "text/html";

            string resource = GetParam(path);
            //m_log.DebugFormat("[XXX]: resource {0}", resource);
            Request request = RequestFactory.CreateRequest(resource, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language")));
            Environment env = new Environment(request);

            string result = string.Empty;
            if (resource.StartsWith("/edit"))
            {
                // client invoked /wifi/admin/users/edit, possibly with the UUID parameter after
                UUID groupID = UUID.Zero;
                // SplitParams(path) returns an array of whatever parameters come after the path.
                // In this case it should return "edit" and "<uuid>"; we want "<uuid>", so [1]
                string[] pars = SplitParams(path);
                if (pars.Length >= 2)
                {
                    // indeed, client invoked /wifi/admin/groups/edit/<uuid>
                    // let's grab that uuid
                    UUID.TryParse(pars[1], out groupID);
                    result = m_WebApp.Services.GroupsEditGetRequest(env, groupID);
                }
            }
            else if (resource.StartsWith("/delete"))
            {
                // client invoked /wifi/admin/users/delete, possibly with the UUID parameter after
                UUID groupID = UUID.Zero;
                // SplitParams(path) returns an array of whatever parameters come after the path.
                // In this case it should return "delete" and "<uuid>"; we want "<uuid>", so [1]
                string[] pars = SplitParams(path);
                if (pars.Length >= 2)
                {
                    // indeed, client invoked /wifi/admin/groups/delete/<uuid>
                    // let's grab that uuid
                    UUID.TryParse(pars[1], out groupID);
                    result = m_WebApp.Services.GroupsDeleteGetRequest(env, groupID);
                }
            }

            if (string.IsNullOrEmpty(result))
                result = m_WebApp.Services.GroupsManagementGetRequest(env);

            return WebAppUtils.StringToBytes(result);
        }
Пример #29
0
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            byte[] result = new byte[0];

            string format = string.Empty;

            result = m_MapService.GetMapTile(path.Trim('/'), out format);
            if (result.Length > 0)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.OK;
                if (format.Equals(".png"))
                {
                    httpResponse.ContentType = "image/png";
                }
                else if (format.Equals(".jpg") || format.Equals(".jpeg"))
                {
                    httpResponse.ContentType = "image/jpeg";
                }
            }
            else
            {
                httpResponse.StatusCode  = (int)HttpStatusCode.NotFound;
                httpResponse.ContentType = "text/plain";
            }

            return(result);
        }
Пример #30
0
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            Encoding     encoding     = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(request, encoding);

            string requestBody = streamReader.ReadToEnd();

            streamReader.Close();

            string param          = GetParam(path);
            string responseString = m_restMethod(requestBody, path, param, httpRequest, httpResponse);

            return(Encoding.UTF8.GetBytes(responseString));
        }
Пример #31
0
 protected virtual byte[] ThrottledRequest(
     string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
 {
     return(new byte[0]);
 }
Пример #32
0
        public void RenderMaterialsPostCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
        {
            OSDMap req;

            try
            {
                req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream);
            }
            catch
            {
                response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            OSDArray respArr = new OSDArray();
            OSD      tmpOSD;

            if (req.TryGetValue("Zipped", out tmpOSD))
            {
                OSD osd = null;

                byte[] inBytes = tmpOSD.AsBinary();

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

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

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

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

            OSDMap resp = new OSDMap();

            resp["Zipped"]     = ZCompressOSD(respArr, false);
            response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp));

            //m_log.Debug("[Materials]: cap request: " + request);
            //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            //m_log.Debug("[Materials]: cap response: " + response);
        }
Пример #33
0
        public void RenderMaterialsPutCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
        {
            OSDMap req;

            try
            {
                req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream);
            }
            catch
            {
                response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            OSDMap   materialsFromViewer = null;
            OSDArray respArr             = new OSDArray();

            OSD tmpOSD;
            HashSet <SceneObjectPart> parts = new HashSet <SceneObjectPart>();

            if (req.TryGetValue("Zipped", out tmpOSD))
            {
                OSD osd = null;

                byte[] inBytes = tmpOSD.AsBinary();

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null && osd is OSDMap)
                    {
                        materialsFromViewer = osd as OSDMap;

                        if (materialsFromViewer.TryGetValue("FullMaterialsPerFace", out tmpOSD) && (tmpOSD is OSDArray))
                        {
                            OSDArray matsArr = tmpOSD as OSDArray;
                            try
                            {
                                foreach (OSDMap matsMap in matsArr)
                                {
                                    uint primLocalID = 0;
                                    try
                                    {
                                        primLocalID = matsMap["ID"].AsUInteger();
                                    }
                                    catch (Exception e)
                                    {
                                        m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
                                        continue;
                                    }

                                    SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
                                    if (sop == null)
                                    {
                                        m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
                                        continue;
                                    }

                                    if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
                                    {
                                        m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
                                        continue;
                                    }

                                    OSDMap mat = null;
                                    try
                                    {
                                        mat = matsMap["Material"] as OSDMap;
                                    }
                                    catch (Exception e)
                                    {
                                        m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
                                        continue;
                                    }

                                    Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
                                    if (te == null)
                                    {
                                        m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
                                        continue;
                                    }

                                    int  face  = -1;
                                    UUID oldid = UUID.Zero;
                                    Primitive.TextureEntryFace faceEntry = null;
                                    if (matsMap.TryGetValue("Face", out tmpOSD))
                                    {
                                        face      = tmpOSD.AsInteger();
                                        faceEntry = te.CreateFace((uint)face);
                                    }
                                    else
                                    {
                                        faceEntry = te.DefaultTexture;
                                    }

                                    if (faceEntry == null)
                                    {
                                        continue;
                                    }

                                    UUID         id;
                                    FaceMaterial newFaceMat = null;
                                    if (mat == null)
                                    {
                                        // This happens then the user removes a material from a prim
                                        id = UUID.Zero;
                                    }
                                    else
                                    {
                                        newFaceMat = new FaceMaterial(mat);
                                        if (newFaceMat.DiffuseAlphaMode == 1 &&
                                            newFaceMat.NormalMapID == UUID.Zero &&
                                            newFaceMat.SpecularMapID == UUID.Zero
                                            )
                                        {
                                            id = UUID.Zero;
                                        }
                                        else
                                        {
                                            newFaceMat.genID();
                                            id = newFaceMat.ID;
                                        }
                                    }

                                    oldid = faceEntry.MaterialID;

                                    if (oldid == id)
                                    {
                                        continue;
                                    }

                                    if (faceEntry != null)
                                    {
                                        faceEntry.MaterialID = id;
                                        //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
                                        // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
                                        sop.Shape.TextureEntry = te.GetBytes(9);
                                    }

                                    if (oldid != UUID.Zero)
                                    {
                                        RemoveMaterial(oldid);
                                    }

                                    lock (materialslock)
                                    {
                                        if (id != UUID.Zero)
                                        {
                                            if (m_Materials.ContainsKey(id))
                                            {
                                                m_MaterialsRefCount[id]++;
                                            }
                                            else
                                            {
                                                m_Materials[id]         = newFaceMat;
                                                m_MaterialsRefCount[id] = 1;
                                                m_changed[newFaceMat]   = Util.GetTimeStamp();
                                            }
                                        }
                                    }

                                    if (!parts.Contains(sop))
                                    {
                                        parts.Add(sop);
                                    }
                                }

                                foreach (SceneObjectPart sop in parts)
                                {
                                    if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted)
                                    {
                                        sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                        sop.ScheduleFullUpdate();
                                        sop.ParentGroup.HasGroupChanged = true;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                m_log.Warn("[Materials]: exception processing received material ", e);
                                response.StatusCode = (int)HttpStatusCode.BadRequest;
                                return;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return;
                }
            }

            OSDMap resp = new OSDMap();

            resp["Zipped"]     = ZCompressOSD(respArr, false);
            response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp));

            //m_log.Debug("[Materials]: cap request: " + request);
            //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            //m_log.Debug("[Materials]: cap response: " + response);
        }
Пример #34
0
 protected override byte[] ProcessRequest(string path, Stream request,
                                          IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
 {
     return(Util.UTF8.GetBytes("OK"));
 }
Пример #35
0
        /// -----------------------------------------------------------------
        /// <summary>
        /// </summary>
        // -----------------------------------------------------------------
        private byte[] HandleBinaryRequest(string domain, Stream bstream, IOSHttpRequest request, IOSHttpResponse response)
        {
            response.ContentType = "application/bson";
            response.StatusCode  = 200;
            response.KeepAlive   = true;

            ResponseBase resp = null;

            try
            {
                RequestBase req = RequestBase.DeserializeFromBinaryStream(bstream);
                if (req == null)
                {
                    resp = OperationFailed("Failed to deserialize request");
                    return(resp.SerializeToBinaryData());
                }

                // Check to see if this is an authentication request
                // Get a complete domain and find the handler
                if (String.IsNullOrEmpty(req._Domain))
                {
                    req._Domain = domain;
                }

                resp = InvokeHandler(req);
            }
            catch (Exception e)
            {
                resp = OperationFailed(String.Format("Fatal error; {0}", e.Message));
            }

            return(resp.SerializeToBinaryData());
        }
Пример #36
0
        /// -----------------------------------------------------------------
        /// <summary>
        /// </summary>
        // -----------------------------------------------------------------
        public byte[] HandleStreamRequest(string path, Stream stream, IOSHttpRequest request, IOSHttpResponse response)
        {
            string domain = path.Remove(0, m_httppath.Length);

            m_log.DebugFormat("[Dispatcher] path={0}, domain={1}, content-type={2}", path, domain, request.ContentType);

            switch (request.ContentType)
            {
            case "application/bson":
                return(HandleBinaryRequest(domain, stream, request, response));

            case "application/json":
            case "test/json":
                return(HandleTextRequest(domain, stream, request, response));

            default:
                m_log.WarnFormat("[Dispatcher] request with unhandled content type; {0}", request.ContentType);
                return(null);
            }
        }
Пример #37
0
 protected virtual byte[] ProcessRequest(
     string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
 {
     return(null);
 }
Пример #38
0
        protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            //m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path);
            string body;

            using (StreamReader sr = new StreamReader(httpRequest.InputStream))
                body = sr.ReadToEnd();
            body = body.Trim();

            httpRequest.InputStream.Dispose();

            try
            {
                Dictionary <string, object> request = ServerUtils.ParseQueryString(body);
                httpResponse.StatusCode = (int)HttpStatusCode.OK;

                if (!request.ContainsKey("X") || !request.ContainsKey("Y") || !request.ContainsKey("DATA"))
                {
                    httpResponse.RawBuffer = Util.ResultFailureMessage("Bad request.");
                    return;
                }

                int x = 0, y = 0;
                //UUID scopeID = new UUID("07f8d88e-cd5e-4239-a0ed-843f75d09992");
                UUID scopeID = UUID.Zero;
                Int32.TryParse(request["X"].ToString(), out x);
                Int32.TryParse(request["Y"].ToString(), out y);
                if (request.ContainsKey("SCOPE"))
                {
                    UUID.TryParse(request["SCOPE"].ToString(), out scopeID);
                }

                m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y);

                //string type = "image/jpeg";
                //if (request.ContainsKey("TYPE"))
                //    type = request["TYPE"].ToString();

                if (m_GridService != null)
                {
                    IPAddress  ipAddr = httpRequest.RemoteIPEndPoint.Address;
                    GridRegion r      = m_GridService.GetRegionByPosition(scopeID, (int)Util.RegionToWorldLoc((uint)x), (int)Util.RegionToWorldLoc((uint)y));
                    if (r != null)
                    {
                        if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString())
                        {
                            m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address);
                            httpResponse.RawBuffer = Util.ResultFailureMessage("IP address of caller does not match IP address of registered region");
                            //return;
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}",
                                         ipAddr, x, y);
                        httpResponse.RawBuffer = Util.ResultFailureMessage("Region not found at given coordinates");
                        //return;
                    }
                }

                byte[] data = Convert.FromBase64String(request["DATA"].ToString());

                bool result = m_MapService.AddMapTile(x, y, data, scopeID, out string reason);
                if (result)
                {
                    httpResponse.RawBuffer = Util.sucessResultSuccess;
                }
                else
                {
                    httpResponse.RawBuffer = Util.ResultFailureMessage(reason);
                }
                return;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
            }

            httpResponse.RawBuffer = Util.ResultFailureMessage("Unexpected server error");
        }
Пример #39
0
 public override byte[] Handle(string path, Stream requestData,
                               IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
 {
     return(Service.ServeMessage());
 }
        protected override byte[] ProcessRequest(string path, Stream request,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
//            m_log.DebugFormat("[SIMULATION]: Stream handler called");

            Hashtable keysvals   = new Hashtable();
            Hashtable headervals = new Hashtable();

            string[] querystringkeys = httpRequest.QueryString.AllKeys;
            string[] rHeaders        = httpRequest.Headers.AllKeys;

            keysvals.Add("uri", httpRequest.RawUrl);
            keysvals.Add("content-type", httpRequest.ContentType);
            keysvals.Add("http-method", httpRequest.HttpMethod);

            foreach (string queryname in querystringkeys)
            {
                keysvals.Add(queryname, httpRequest.QueryString[queryname]);
            }

            foreach (string headername in rHeaders)
            {
                headervals[headername] = httpRequest.Headers[headername];
            }

            keysvals.Add("headers", headervals);
            keysvals.Add("querystringkeys", querystringkeys);

            Stream inputStream;

            if (httpRequest.ContentType == "application/x-gzip")
            {
                inputStream = new GZipStream(request, CompressionMode.Decompress);
            }
            else
            {
                inputStream = request;
            }

            Encoding     encoding = Encoding.UTF8;
            StreamReader reader   = new StreamReader(inputStream, encoding);

            string requestBody = reader.ReadToEnd();

            reader.Close();
            keysvals.Add("body", requestBody);

            httpResponse.StatusCode  = 200;
            httpResponse.ContentType = "text/html";
            httpResponse.KeepAlive   = false;

            Hashtable responsedata = new Hashtable();

            UUID   agentID;
            UUID   regionID;
            string action;

            if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
            {
                m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);

                httpResponse.StatusCode = 404;

                return(encoding.GetBytes("false"));
            }

            DoAgentPut(keysvals, responsedata);

            httpResponse.StatusCode = (int)responsedata["int_response_code"];
            return(encoding.GetBytes((string)responsedata["str_response_string"]));
        }
Пример #41
0
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            StreamReader reader      = new StreamReader(request);
            string       requestBody = reader.ReadToEnd();

            OSD osd = OSDParser.DeserializeLLSDXml(requestBody);

            string      action    = ((OSDMap)osd)["action"].AsString();
            OSDArray    selection = (OSDArray)((OSDMap)osd)["selection"];
            List <uint> sel       = new List <uint>();

            for (int i = 0; i < selection.Count; i++)
            {
                sel.Add(selection[i].AsUInteger());
            }

            Util.FireAndForget(
                x => { m_module.HandleMenuSelection(action, m_agentID, sel); }, null, "DynamicMenuModule.HandleMenuSelection");

            Encoding encoding = Encoding.UTF8;

            return(encoding.GetBytes(OSDParser.SerializeLLSDXmlString(new OSD())));
        }
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

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

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

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                string method = request["METHOD"].ToString();

                switch (method)
                {
                case "register":
                    return(Register(request));

                case "deregister":
                    return(Deregister(request));

                case "get_neighbours":
                    return(GetNeighbours(request));

                case "get_region_by_uuid":
                    return(GetRegionByUUID(request));

                case "get_region_by_position":
                    return(GetRegionByPosition(request));

                case "get_region_by_name":
                    return(GetRegionByName(request));

                case "get_regions_by_name":
                    return(GetRegionsByName(request));

                case "get_region_range":
                    return(GetRegionRange(request));

                case "get_default_regions":
                    return(GetDefaultRegions(request));

                case "get_default_hypergrid_regions":
                    return(GetDefaultHypergridRegions(request));

                case "get_fallback_regions":
                    return(GetFallbackRegions(request));

                case "get_hyperlinks":
                    return(GetHyperlinks(request));

                case "get_region_flags":
                    return(GetRegionFlags(request));

                case "get_grid_extra_features":
                    return(GetGridExtraFeatures(request));
                }

                m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
            }

            return(FailureResult());
        }
Пример #43
0
        public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            //m_log.DebugFormat("[XXX]: FetchInventoryDescendentsRequest in {0}, {1}", (m_Scene == null) ? "none" : m_Scene.Name, request);

            Hashtable hash = new Hashtable();

            try
            {
                hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
            }
            catch (LLSD.LLSDParseException e)
            {
                m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
                m_log.Error("Request: " + request);
            }

            ArrayList foldersrequested = (ArrayList)hash["folders"];

            hash.Clear();

            List <LLSDFetchInventoryDescendents> folders = new List <LLSDFetchInventoryDescendents>();

            for (int i = 0; i < foldersrequested.Count; i++)
            {
                Hashtable inventoryhash = (Hashtable)foldersrequested[i];
                LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();

                try
                {
                    LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
                }
                catch (Exception e)
                {
                    m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e);
                    continue;
                }

                folders.Add(llsdRequest);
            }

            foldersrequested.Clear();

            if (folders.Count == 0)
            {
                return("<llsd><map><key>folders</key><array /></map></llsd>");
            }

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

            int total_folders = 0;
            int total_items   = 0;
            List <InventoryCollection> invcollSet = Fetch(folders, bad_folders, ref total_folders, ref total_items);
            //m_log.DebugFormat("[XXX]: Got {0} folders from a request of {1}", invcollSet.Count, folders.Count);

            int invcollSetCount = 0;

            if (invcollSet != null)
            {
                invcollSetCount = invcollSet.Count;
            }

            int mem = 8192 + ((256 * invcollSetCount +
                               384 * total_folders +
                               1024 * total_items +
                               128 * bad_folders.Count) & 0x7ffff000);

            StringBuilder lastresponse = new StringBuilder(mem);

            lastresponse.Append("<llsd>");

            if (invcollSetCount > 0)
            {
                lastresponse.Append("<map><key>folders</key><array>");
                int i = 0;
                InventoryCollection thiscoll;
                for (i = 0; i < invcollSetCount; i++)
                {
                    thiscoll      = invcollSet[i];
                    invcollSet[i] = null;

                    LLSDxmlEncode.AddMap(lastresponse);
                    LLSDxmlEncode.AddElem("agent_id", thiscoll.OwnerID, lastresponse);
                    LLSDxmlEncode.AddElem("descendents", thiscoll.Descendents, lastresponse);
                    LLSDxmlEncode.AddElem("folder_id", thiscoll.FolderID, lastresponse);

                    if (thiscoll.Folders == null || thiscoll.Folders.Count == 0)
                    {
                        LLSDxmlEncode.AddEmptyArray("categories", lastresponse);
                    }
                    else
                    {
                        LLSDxmlEncode.AddArray("categories", lastresponse);
                        foreach (InventoryFolderBase invFolder in thiscoll.Folders)
                        {
                            LLSDxmlEncode.AddMap(lastresponse);

                            LLSDxmlEncode.AddElem("folder_id", invFolder.ID, lastresponse);
                            LLSDxmlEncode.AddElem("parent_id", invFolder.ParentID, lastresponse);
                            LLSDxmlEncode.AddElem("name", invFolder.Name, lastresponse);
                            LLSDxmlEncode.AddElem("type", invFolder.Type, lastresponse);
                            LLSDxmlEncode.AddElem("preferred_type", (int)-1, lastresponse);
                            LLSDxmlEncode.AddElem("version", invFolder.Version, lastresponse);

                            LLSDxmlEncode.AddEndMap(lastresponse);
                        }
                        LLSDxmlEncode.AddEndArray(lastresponse);
                    }

                    if (thiscoll.Items == null || thiscoll.Items.Count == 0)
                    {
                        LLSDxmlEncode.AddEmptyArray("items", lastresponse);
                    }
                    else
                    {
                        LLSDxmlEncode.AddArray("items", lastresponse);
                        foreach (InventoryItemBase invItem in thiscoll.Items)
                        {
                            invItem.ToLLSDxml(lastresponse);
                        }

                        LLSDxmlEncode.AddEndArray(lastresponse);
                    }

                    LLSDxmlEncode.AddElem("owner_id", thiscoll.OwnerID, lastresponse);
                    LLSDxmlEncode.AddElem("version", thiscoll.Version, lastresponse);

                    LLSDxmlEncode.AddEndMap(lastresponse);
                    invcollSet[i] = null;
                }
                lastresponse.Append("</array></map>");
                thiscoll = null;
            }
            else
            {
                lastresponse.Append("<map><key>folders</key><array /></map>");
            }

            //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Bad folders {0}", string.Join(", ", bad_folders));
            if (bad_folders.Count > 0)
            {
                lastresponse.Append("<map><key>bad_folders</key><array>");
                foreach (UUID bad in bad_folders)
                {
                    lastresponse.Append("<map><key>folder_id</key><uuid>");
                    lastresponse.Append(bad.ToString());
                    lastresponse.Append("</uuid><key>error</key><string>Unknown</string></map>");
                }
                lastresponse.Append("</array></map>");
            }
            lastresponse.Append("</llsd>");

            return(lastresponse.ToString());
        }
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

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

            // We need to check the authorization header
            //httpRequest.Headers["authorization"] ...

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

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                method = request["METHOD"].ToString();

                switch (method)
                {
                case "createuser":
                    if (m_AllowCreateUser)
                    {
                        return(CreateUser(request));
                    }
                    else
                    {
                        break;
                    }

                case "getaccount":
                    return(GetAccount(request));

                case "getaccounts":
                    return(GetAccounts(request));

                case "setaccount":
                    if (m_AllowSetAccount)
                    {
                        return(StoreAccount(request));
                    }
                    else
                    {
                        break;
                    }
                }

                m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e);
            }

            return(FailureResult());
        }
        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            m_log.DebugFormat("[GET_DISPLAY_NAMES]: called {0}", httpRequest.Url.Query);

            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);

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


            if (m_UserManagement == null)
            {
                m_log.Error("[GET_DISPLAY_NAMES]: Cannot fetch display names without a user management component");
                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return(new byte[0]);
            }

            OSDMap   osdReply = new OSDMap();
            OSDArray agents   = new OSDArray();

            osdReply["agents"] = agents;
            foreach (string id in ids)
            {
                UUID uuid = UUID.Zero;
                if (UUID.TryParse(id, out uuid))
                {
                    string name = m_UserManagement.GetUserName(uuid);
                    if (!string.IsNullOrEmpty(name))
                    {
                        string[] parts   = name.Split(new char[] { ' ' });
                        OSDMap   osdname = new OSDMap();
                        osdname["display_name_next_update"] = OSD.FromDate(DateTime.MinValue);
                        osdname["display_name_expires"]     = OSD.FromDate(DateTime.Now.AddMonths(1));
                        osdname["display_name"]             = OSD.FromString(name);
                        osdname["legacy_first_name"]        = parts[0];
                        osdname["legacy_last_name"]         = parts[1];
                        osdname["username"] = OSD.FromString(name);
                        osdname["id"]       = OSD.FromUUID(uuid);
                        osdname["is_display_name_default"] = OSD.FromBoolean(true);

                        agents.Add(osdname);
                    }
                }
            }

            // Full content request
            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
            //httpResponse.ContentLength = ??;
            httpResponse.ContentType = "application/llsd+xml";

            string reply = OSDParser.SerializeLLSDXmlString(osdReply);

            return(System.Text.Encoding.UTF8.GetBytes(reply));
        }
Пример #46
0
 protected override byte[] ProcessRequest(string path, Stream request,
                                          IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
 {
     return(Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)));
 }