public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse 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);
                result = m_WebApp.Services.UserAccountGetRequest(env, userID);
            }

            return WifiUtils.StringToBytes(result);

        }
Example #2
0
 private byte[] OKResponse (OSHttpResponse httpResponse)
 {
     httpResponse.AddHeader ("X-Handlers-Provided", m_HandlersType);
     httpResponse.StatusCode = (int)HttpStatusCode.OK;
     httpResponse.StatusDescription = "OK";
     return new byte[0];
 }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            string result = string.Empty;
            try
            {
                Request request = WifiUtils.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 WifiUtils.StringToBytes(result);
        }
Example #4
0
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            byte[] result = new byte[0];

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

            Dictionary<string, object> request =
                        WebUtils.ParseQueryString(body);

            if (!request.ContainsKey("METHOD"))
                return result; //No method, no work

            string method = request["METHOD"].ToString();
            switch(method)
            {
                case "inform_neighbors_region_is_up":
                    return InformNeighborsRegionIsUp(request);
                case "inform_neighbors_region_is_down":
                    return InformNeighborsRegionIsDown(request);
                case "inform_neighbors_of_chat_message":
                    return InformNeighborsOfChatMessage(request);
                case "get_neighbors":
                    return GetNeighbors(request);
                default :
                    m_log.Warn("[NeighborHandlers]: Unknown method " + method);
                    break;
            }
            return result;
        }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            StreamReader sr = new StreamReader(requestData);
            string body = sr.ReadToEnd();
            sr.Close();
            body = body.Trim();

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

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

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

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

                switch (method)
                {
                    case "report":
                        return Report(request);
                }
                m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method);
            }
            catch (Exception e)
            {
                m_log.Debug("[PRESENCE HANDLER]: Exception {0}" + e);
            }

            return FailureResult();

        }
Example #6
0
        public override byte[] Handle(string path, Stream request,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            XmlSerializer xs = new XmlSerializer(typeof (AssetBase));
            AssetBase asset = (AssetBase) xs.Deserialize(request);

            IGridRegistrationService urlModule =
                            m_registry.RequestModuleInterface<IGridRegistrationService>();
            if (urlModule != null)
                if (!urlModule.CheckThreatLevel("", m_regionHandle, "Asset_Update", ThreatLevel.Full))
                    return new byte[0];
            string[] p = SplitParams(path);
            if (p.Length > 1)
            {
                bool result =
                        m_AssetService.UpdateContent(p[1], asset.Data);

                xs = new XmlSerializer(typeof(bool));
                return WebUtils.SerializeResult(xs, result);
            }

            string id = m_AssetService.Store(asset);

            xs = new XmlSerializer(typeof(string));
            return WebUtils.SerializeResult(xs, id);
        }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse 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 = WifiUtils.CreateRequest(string.Empty, httpRequest);
                Diva.Wifi.Environment env = new Diva.Wifi.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 WifiUtils.StringToBytes(result);

        }
 public override byte[] Handle(string path, Stream request,
         OSHttpRequest httpRequest, OSHttpResponse httpResponse)
 {
     // Not implemented yet
     httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
     return new byte[] { };
 }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            string resource = GetParam(path);
            //m_log.DebugFormat("[Wifi]: resource {0}", resource);
            resource = resource.Trim(WifiUtils.DirectorySeparatorChars);
            string resourcePath = System.IO.Path.Combine(m_LocalPath, resource);
            resourcePath = Uri.UnescapeDataString(resourcePath);

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

            if (type.StartsWith("application") || type.StartsWith("text"))
            {
                string res = WifiUtils.ReadTextResource(resourcePath, true);
                return WifiUtils.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 WifiUtils.StringToBytes(result);
        }
        public override byte[] Handle(string path, Stream request,
                OSHttpRequest httpRequest, OSHttpResponse 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];
        }
Example #11
0
        public bool ProcessInMsg(OSHttpRequest req, OSHttpResponse resp)
        {
            //                              0        1          2       3
            // http://simulator.com:9000/vwohttp/sessionid/methodname/param
            string[] urlparts = req.Url.AbsolutePath.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);

            UUID sessionID;
            // Check for session
            if (!UUID.TryParse(urlparts[1], out sessionID))
                return false;
            // Check we match session
            if (sessionID != SessionId)
                return false;

            string method = urlparts[2];

            string param = String.Empty;
            if (urlparts.Length > 3)
                param = urlparts[3];

            bool found;

            switch (method.ToLower())
            {
                case "textures":
                    found = ProcessTextureRequest(param, resp);
                    break;
                default:
                    found = false;
                    break;
            }

            return found;
        }
Example #12
0
        private string RESTGetUserProfile(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            UUID id;
            UserProfileData userProfile;

            try
            {
                id = new UUID(param);
            }
            catch (Exception)
            {
                httpResponse.StatusCode = 500;
                return "Malformed Param [" + param + "]";
            }

            userProfile = m_userDataBaseService.GetUserProfile(id);

            if (userProfile == null)
            {
                httpResponse.StatusCode = 404;
                return "Not Found.";
            }

            return ProfileToXmlRPCResponse(userProfile).ToString();
        }
Example #13
0
        private string RESTGetUserProfile(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            // Check IP Endpoint Access
            if (!TrustManager.Instance.IsTrustedPeer(httpRequest.RemoteIPEndPoint))
            {
                httpResponse.StatusCode = 403;
                return ("Access is denied for this IP Endpoint");
            }

            UUID id;
            UserProfileData userProfile;

            try
            {
                id = new UUID(param);
            }
            catch (Exception)
            {
                httpResponse.StatusCode = 500;
                return "Malformed Param [" + param + "]";
            }

            userProfile = m_userDataBaseService.GetUserProfile(id);

            if (userProfile == null)
            {
                httpResponse.StatusCode = 404;
                return "Not Found.";
            }

            return ProfileToXmlRPCResponse(userProfile).ToString();
        }
Example #14
0
        private bool ProcessTextureRequest(string param, OSHttpResponse resp)
        {
            UUID assetID;
            if (!UUID.TryParse(param, out assetID))
                return false;

            AssetBase asset = m_scene.AssetService.Get(assetID.ToString());

            if (asset == null)
                return false;

            ManagedImage tmp;
            Image imgData;
            byte[] jpegdata;

            OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData);

            using (MemoryStream ms = new MemoryStream())
            {
                imgData.Save(ms, ImageFormat.Jpeg);
                jpegdata = ms.GetBuffer();
            }

            resp.ContentType = "image/jpeg";
            resp.ContentLength = jpegdata.Length;
            resp.StatusCode = 200;
            resp.Body.Write(jpegdata, 0, jpegdata.Length);

            return true;
        }
Example #15
0
        public void Init()
        {
            TestHttpRequest threq0 = new TestHttpRequest("utf-8", "text/xml", "OpenSim Test Agent", "192.168.0.1", "4711", 
                                                       new string[] {"text/xml"}, 
                                                       ConnectionType.KeepAlive, 4711, 
                                                       new Uri("http://127.0.0.1/admin/inventory/Dr+Who/Tardis"));
            threq0.Method = "GET";
            threq0.HttpVersion = HttpHelper.HTTP10;

            TestHttpRequest threq1 = new TestHttpRequest("utf-8", "text/xml", "OpenSim Test Agent", "192.168.0.1", "4711", 
                                                       new string[] {"text/xml"}, 
                                                       ConnectionType.KeepAlive, 4711, 
                                                       new Uri("http://127.0.0.1/admin/inventory/Dr+Who/Tardis?a=0&b=1&c=2"));
            threq1.Method = "POST";
            threq1.HttpVersion = HttpHelper.HTTP11;
            threq1.Headers["x-wuff"] = "wuffwuff";
            threq1.Headers["www-authenticate"] = "go away";
            
            req0 = new OSHttpRequest(new TestHttpClientContext(false), threq0);
            req1 = new OSHttpRequest(new TestHttpClientContext(false), threq1);

            rsp0 = new OSHttpResponse(new TestHttpResponse());

            ipEP0 = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 4711);

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

            //m_log.DebugFormat("[XXX]: query String: {0}", body);
            string method = string.Empty;
            try
            {
                Dictionary<string, object> request = new Dictionary<string, object>();
                request = WebUtils.ParseQueryString(body);
                if (request.Count == 1)
                    request = WebUtils.ParseXmlResponse(body);
                object value = null;
                request.TryGetValue("<?xml version", out value);
                if (value != null)
                    request = WebUtils.ParseXmlResponse(body);

                return ProcessAddCAP(request);
            }
            catch (Exception)
            {
            }

            return null;

        }
Example #17
0
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            httpResponse.ContentType = "image/jpeg";

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

            try
            {
                lock (m_RequestLock)
                {
                    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];
        }
Example #18
0
        public override byte[] Handle(string path, Stream request,
                                      OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            string param = GetParam(path);
            byte[] result = new byte[] {};
            try
            {
                string[] p = param.Split(new char[] {'/', '?', '&'}, StringSplitOptions.RemoveEmptyEntries);

                if (p.Length > 0)
                {
                    UUID assetID = UUID.Zero;

                    if (!UUID.TryParse(p[0], out assetID))
                    {
                        m_log.InfoFormat(
                            "[REST]: GET:/presence ignoring request with malformed UUID {0}", p[0]);
                        return result;
                    }

                }
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
            }
            return result;
        }
 public override byte[] Handle(string path, Stream request,
         OSHttpRequest httpRequest, OSHttpResponse httpResponse)
 {
     //Return the config map
     UTF8Encoding encoding = new UTF8Encoding();
     return encoding.GetBytes(OSDParser.SerializeJsonString(m_configMap));
 }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            StreamReader sr = new StreamReader(requestData);
            string body = sr.ReadToEnd();
            sr.Close();
            body = body.Trim();

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

            try
            {
                OSDMap map = WebUtils.GetOSDMap(body);
                if (map != null)
                {
                    return NewMessage(map);
                }
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[GRID HANDLER]: Exception {0}", e);
            }

            return FailureResult();
        }
Example #21
0
        public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            byte[] data = ReadFully(request);
            string param = GetParam(path);
            string responseString = m_method(data, path, param);

            return Encoding.UTF8.GetBytes(responseString);
        }
 public override byte[] Handle(string path, Stream request,
         OSHttpRequest httpRequest, OSHttpResponse httpResponse)
 {
     // Not implemented yet
     Console.WriteLine("--- Get region --- " + path);
     httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
     return new byte[] { };
 }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse 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(WifiUtils.DirectorySeparatorChars);

            Request request = WifiUtils.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 WifiUtils.StringToBytes(m_WebApp.Services.DefaultRequest(env));
            }
            else
            {
                string resourcePath = System.IO.Path.Combine(WifiUtils.DocsPath, resource);
                string type = WifiUtils.GetContentType(resource);
                httpResponse.ContentType = type;
                //m_log.DebugFormat("[Wifi]: ContentType {0}", type);
                if (type.StartsWith("image"))
                    return WifiUtils.ReadBinaryResource(resourcePath);

                if (type.StartsWith("application"))
                {
                    string res = WifiUtils.ReadTextResource(resourcePath, true);
                    return WifiUtils.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(WifiUtils.ReadTextResource(resourcePath));
                    if (res == string.Empty)
                        res = m_WebApp.Services.DefaultRequest(env);
                    return WifiUtils.StringToBytes(res);
                }
            }

            httpResponse.ContentType = "text/plain";
            string result = "Boo!";
            return WifiUtils.StringToBytes(result);
        }
        public override byte[] Handle(string path, Stream requestData,
                OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            StreamReader sr = new StreamReader(requestData);
            string body = sr.ReadToEnd();
            sr.Close();
            body = body.Trim();

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

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

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

            return FailureResult();

        }
Example #25
0
        /// <summary>
        /// Send LLSD to an HTTP client in application/llsd+json form
        /// </summary>
        /// <param name="response">HTTP response to send the data in</param>
        /// <param name="body">LLSD to send to the client</param>
        public static void SendJSONResponse(OSHttpResponse response, OSDMap body)
        {
            byte[] responseData = Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(body));

            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength = responseData.Length;
            response.ContentType = "application/llsd+json";
            response.Body.Write(responseData, 0, responseData.Length);
        }
Example #26
0
        /// <summary>
        /// Send LLSD to an HTTP client in application/llsd+xml form
        /// </summary>
        /// <param name="response">HTTP response to send the data in</param>
        /// <param name="body">LLSD to send to the client</param>
        public static void SendXMLResponse(OSHttpResponse response, OSDMap body)
        {
            byte[] responseData = OSDParser.SerializeLLSDXmlBytes(body);

            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength = responseData.Length;
            response.ContentType = "application/llsd+xml";
            response.Body.Write(responseData, 0, responseData.Length);
        }
        public static void BaseFetchExistingAssetDataTest(AssetBase asset, BaseGetAssetStreamHandler handler, OSHttpResponse response)
        {
            Assert.AreEqual(asset.Data, handler.Handle("/assets/" + asset.ID + "/data", null, null, response), "Failed on fetching data without trailing slash.");
            Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode, "Wrong http response code on first fetch.");
            Assert.AreEqual(EXPECTED_CONTENT_TYPE, response.ContentType, "Wrong http content type on first fetch.");

            Assert.AreEqual(asset.Data, handler.Handle("/assets/" + asset.ID + "/data/", null, null, response), "Failed on fetching data with trailing slash.");
            Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode, "Wrong http response code on second fetch.");
            Assert.AreEqual(EXPECTED_CONTENT_TYPE, response.ContentType, "Wrong http content type on second fetch.");
        }
Example #28
0
 byte[] GetHandler(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
 {
     string username;
     if (server.AuthenticateRequest(httpRequest, httpResponse, out username))
     {
         System.Net.HttpStatusCode status = server.GET(httpResponse, httpRequest.Url.AbsolutePath, username);
         httpResponse.StatusCode = (int)status;
     }
     return OpenMetaverse.Utils.EmptyBytes;
 }
Example #29
0
        public static byte[] MakeResponse(OSHttpResponse httpResponse, OSDMap map)
        {
            byte[] responseData = Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(map));

            httpResponse.ContentType = "application/json";
            httpResponse.ContentLength = responseData.Length;
            httpResponse.ContentEncoding = Encoding.UTF8;

            return responseData;
        }
        public override byte[] Handle(string path, Stream requestData,
                                      OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            StreamReader sr = new StreamReader(requestData);
            string body = sr.ReadToEnd();
            sr.Close();
            body = body.Trim();

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

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

                if (!request.ContainsKey("METHOD"))
                    return FailureResult();
                IGridRegistrationService urlModule =
                    m_registry.RequestModuleInterface<IGridRegistrationService>();

                string method = request["METHOD"].ToString();
                            
                switch (method)
                {
                    case "AddAbuseReport":
                        if (urlModule != null)
                            if (!urlModule.CheckThreatLevel(m_SessionID, method, ThreatLevel.Low))
                                return FailureResult();
                        return AddAbuseReport(request);
                    case "GetAbuseReport":
                        if (urlModule != null)
                            if (!urlModule.CheckThreatLevel(m_SessionID, method, ThreatLevel.High))
                                return FailureResult();
                        return GetAbuseReport(request);
                    case "UpdateAbuseReport":
                        if (urlModule != null)
                            if (!urlModule.CheckThreatLevel(m_SessionID, method, ThreatLevel.High))
                                return FailureResult();
                        return UpdateAbuseReport(request);
                    case "UpdateAbuseReports":
                        if (urlModule != null)
                            if (!urlModule.CheckThreatLevel(m_SessionID, method, ThreatLevel.High))
                                return FailureResult();
                        return GetAbuseReports(request);
                }
                MainConsole.Instance.DebugFormat("[ABUSEREPORT HANDLER]: unknown method {0} request {1}", method.Length, method);
            }
            catch (Exception e)
            {
                MainConsole.Instance.DebugFormat("[ABUSEREPORT HANDLER]: Exception {0}", e);
            }

            return FailureResult();
        }
Example #31
0
        public void Engine()
        {
            OSHttpRequest req = null;

            while (true)
            {
                try
                {
                    // dequeue an OSHttpRequest from OSHttpServer's
                    // request queue
                    req = _queue.Dequeue();

                    // get a copy of the list of registered handlers
                    List <OSHttpHandler> handlers = _server.OSHttpHandlers;

                    // prune list and have it sorted from most
                    // specific to least specific
                    handlers = MatchHandlers(req, handlers);

                    // process req: we try each handler in turn until
                    // we are either out of handlers or get back a
                    // Pass or Done
                    OSHttpHandlerResult rc = OSHttpHandlerResult.Unprocessed;
                    foreach (OSHttpHandler h in handlers)
                    {
                        rc = h.Process(req);

                        // Pass: handler did not process the request,
                        // try next handler
                        if (OSHttpHandlerResult.Pass == rc)
                        {
                            continue;
                        }

                        // Handled: handler has processed the request
                        if (OSHttpHandlerResult.Done == rc)
                        {
                            break;
                        }

                        // hmm, something went wrong
                        throw new Exception(String.Format("[{0}] got unexpected OSHttpHandlerResult {1}", EngineID, rc));
                    }

                    if (OSHttpHandlerResult.Unprocessed == rc)
                    {
                        _log.InfoFormat("[{0}] OSHttpHandler: no handler registered for {1}", EngineID, req);

                        // set up response header
                        OSHttpResponse resp = new OSHttpResponse(req);
                        resp.StatusCode        = (int)OSHttpStatusCode.ClientErrorNotFound;
                        resp.StatusDescription = String.Format("no handler on call for {0}", req);
                        resp.ContentType       = "text/html";

                        // add explanatory message
                        StreamWriter body = new StreamWriter(resp.Body);
                        body.WriteLine("<html>");
                        body.WriteLine("<header><title>Ooops...</title><header>");
                        body.WriteLine(String.Format("<body><p>{0}</p></body>", resp.StatusDescription));
                        body.WriteLine("</html>");
                        body.Flush();

                        // and ship it back
                        resp.Send();
                    }
                }
                catch (Exception e)
                {
                    _log.DebugFormat("[{0}] OSHttpHandler problem: {1}", EngineID, e.ToString());
                    _log.ErrorFormat("[{0}] OSHttpHandler problem: {1}", EngineID, e.Message);
                }
            }
        }
Example #32
0
        public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            XmlRpcRequest  xmlRpcRequest  = null;
            XmlRpcResponse xmlRpcResponse = null;
            string         requestBody    = null;

            byte[] response;

            Encoding     encoding     = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(request, encoding);

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

            try
            {
                xmlRpcRequest = (XmlRpcRequest)(new XmlRpcRequestDeserializer()).Deserialize(requestBody);
            }
            catch (XmlException e)
            {
                m_log.ErrorFormat("[XMLRPC STREAM HANDLER]: XmlRpc request failed to deserialize: {0} -> {1}", e, requestBody);
                xmlRpcRequest = null;
            }

            if (xmlRpcRequest != null)
            {
                string methodName = xmlRpcRequest.MethodName;

                if (methodName != null)
                {
                    xmlRpcRequest.Params.Add(httpRequest.RemoteIPEndPoint); // Param[1]
                    xmlRpcRequest.Params.Add(httpRequest.Url);              // Param[2]
                    xmlRpcRequest.Params.Add(getForwardedFor(httpRequest)); // Param[3]

                    try
                    {
                        xmlRpcResponse = m_xmlrpcMethod(xmlRpcRequest, httpRequest.RemoteIPEndPoint);
                    }
                    catch (Exception e)
                    {
                        string errorMessage =
                            String.Format(
                                "Requested method [{0}] from {1} threw exception: {2} {3}",
                                methodName, httpRequest.RemoteIPEndPoint.Address, e.Message, e.StackTrace);

                        m_log.ErrorFormat("[XMLRPC STREAM HANDLER]: {0}", errorMessage);

                        // if the registered XmlRpc method threw an exception, we pass a fault-code along
                        xmlRpcResponse = new XmlRpcResponse();

                        // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
                        xmlRpcResponse.SetFault(-32603, errorMessage);
                    }
                }
                else
                {
                    xmlRpcResponse = new XmlRpcResponse();

                    // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
                    xmlRpcResponse.SetFault(
                        XmlRpcErrorCodes.SERVER_ERROR_METHOD,
                        String.Format("Requested method [{0}] not found", methodName));
                }

                response = Encoding.UTF8.GetBytes(XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse));
                httpResponse.ContentType = "text/xml";
            }
            else
            {
                response = Encoding.UTF8.GetBytes("Not found");

                httpResponse.ContentType       = "text/plain";
                httpResponse.StatusCode        = 404;
                httpResponse.StatusDescription = "Not Found";
                httpResponse.ProtocolVersion   = new System.Version("1.0");

                m_log.ErrorFormat(
                    "[XMLRPC STREAM HANDLER]: Handler not found for http request {0} {1}",
                    httpRequest.HttpMethod, httpRequest.Url.PathAndQuery);
            }

            httpResponse.ContentLength64 = response.LongLength;
            httpResponse.ContentEncoding = Encoding.UTF8;
            httpResponse.SendChunked     = false;

            return(response);
        }
Example #33
0
        public void Handle(string path, Stream request, Stream responseStream, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            TRequest deserial;

            using (XmlTextReader xmlReader = new XmlTextReader(request))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(TRequest));
                deserial = (TRequest)deserializer.Deserialize(xmlReader);
            }

            TResponse response = m_method(deserial);

            using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
                serializer.Serialize(xmlWriter, response);
            }
        }
Example #34
0
        internal void DoHTTPGruntWork(Hashtable responsedata)
        {
            if (Request.Body.CanRead)
            {
                Request.Body.Dispose();
            }

            if (responsedata.Contains("h"))
            {
                OSHttpResponse r = (OSHttpResponse)responsedata["h"];
                try
                {
                    r.Send();
                }
                catch { }
                PollServiceArgs.RequestsHandled++;
                return;
            }

            OSHttpResponse response = new OSHttpResponse(new HttpResponse(Request));

            if (responsedata == null)
            {
                SendNoContentError(response);
                return;
            }

            int    responsecode   = 200;
            string responseString = String.Empty;
            string contentType;

            byte[] buffer     = null;
            int    rangeStart = 0;
            int    rangeLen   = -1;

            try
            {
                //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response");
                if (responsedata["int_response_code"] != null)
                {
                    responsecode = (int)responsedata["int_response_code"];
                }

                if (responsedata["bin_response_data"] != null)
                {
                    buffer = (byte[])responsedata["bin_response_data"];
                    responsedata["bin_response_data"] = null;

                    if (responsedata["bin_start"] != null)
                    {
                        rangeStart = (int)responsedata["bin_start"];
                    }

                    if (responsedata["int_bytes"] != null)
                    {
                        rangeLen = (int)responsedata["int_bytes"];
                    }
                }
                else
                {
                    responseString = (string)responsedata["str_response_string"];
                }

                contentType = (string)responsedata["content_type"];
                if (responseString == null)
                {
                    responseString = String.Empty;
                }
            }
            catch
            {
                SendNoContentError(response);
                return;
            }

            response.StatusCode = responsecode;
            if (responsecode == (int)HttpStatusCode.Moved)
            {
                response.AddHeader("Location", (string)responsedata["str_redirect_location"]);
                response.KeepAlive = false;
                PollServiceArgs.RequestsHandled++;
                response.Send();
                return;
            }

            if (responsedata.ContainsKey("http_protocol_version"))
            {
                response.ProtocolVersion = (string)responsedata["http_protocol_version"];
            }

            if (responsedata.ContainsKey("keepalive"))
            {
                response.KeepAlive = (bool)responsedata["keepalive"];
            }

            if (responsedata.ContainsKey("keepaliveTimeout"))
            {
                response.KeepAliveTimeout = (int)responsedata["keepaliveTimeout"];
            }

            if (responsedata.ContainsKey("error_status_text"))
            {
                response.StatusDescription = (string)responsedata["error_status_text"];
            }

            // Cross-Origin Resource Sharing with simple requests
            if (responsedata.ContainsKey("access_control_allow_origin"))
            {
                response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]);
            }

            if (string.IsNullOrEmpty(contentType))
            {
                response.AddHeader("Content-Type", "text/html");
            }
            else
            {
                response.AddHeader("Content-Type", contentType);
            }

            if (responsedata.ContainsKey("headers"))
            {
                Hashtable headerdata = (Hashtable)responsedata["headers"];

                foreach (string header in headerdata.Keys)
                {
                    response.AddHeader(header, headerdata[header].ToString());
                }
            }

            if (buffer == null)
            {
                if (contentType != null && (!(contentType.Contains("image") ||
                                              contentType.Contains("x-shockwave-flash") ||
                                              contentType.Contains("application/x-oar") ||
                                              contentType.Contains("application/vnd.ll.mesh"))))
                {
                    // Text
                    buffer = Encoding.UTF8.GetBytes(responseString);
                }
                else
                {
                    // Binary!
                    buffer = Convert.FromBase64String(responseString);
                }
                response.ContentEncoding = Encoding.UTF8;
            }

            if (rangeStart < 0 || rangeStart > buffer.Length)
            {
                rangeStart = 0;
            }

            if (rangeLen < 0)
            {
                rangeLen = buffer.Length;
            }
            else if (rangeLen + rangeStart > buffer.Length)
            {
                rangeLen = buffer.Length - rangeStart;
            }

            response.ContentLength64 = rangeLen;

            try
            {
                if (rangeLen > 0)
                {
                    response.RawBufferStart = rangeStart;
                    response.RawBufferLen   = rangeLen;
                    response.RawBuffer      = buffer;
                    //response.OutputStream.Write(buffer, rangeStart, rangeLen);
                }

                buffer = null;

                response.Send();
            }
            catch (Exception ex)
            {
                if (ex is System.Net.Sockets.SocketException)
                {
                    // only mute connection reset by peer so we are not totally blind for now
                    if (((System.Net.Sockets.SocketException)ex).SocketErrorCode != System.Net.Sockets.SocketError.ConnectionReset)
                    {
                        m_log.Warn("[POLL SERVICE WORKER THREAD]: Error ", ex);
                    }
                }
                else
                {
                    m_log.Warn("[POLL SERVICE WORKER THREAD]: Error ", ex);
                }
            }

            PollServiceArgs.RequestsHandled++;
        }
        public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse 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));
        }
Example #36
0
        /// <summary>
        /// Invoked by OSHttpRequestPump.
        /// </summary>
        public override OSHttpHandlerResult Process(OSHttpRequest request)
        {
            // call handler method
            Hashtable responseData = _handler(request.Query);

            int    responseCode   = (int)responseData["int_response_code"];
            string responseString = (string)responseData["str_response_string"];
            string contentType    = (string)responseData["content_type"];

            //Even though only one other part of the entire code uses HTTPHandlers, we shouldn't expect this
            //and should check for NullReferenceExceptions

            if (string.IsNullOrEmpty(contentType))
            {
                contentType = "text/html";
            }

            OSHttpResponse response = new OSHttpResponse(request);

            // We're forgoing the usual error status codes here because the client
            // ignores anything but 200 and 301

            response.StatusCode = (int)OSHttpStatusCode.SuccessOk;

            if (responseCode == (int)OSHttpStatusCode.RedirectMovedPermanently)
            {
                response.RedirectLocation = (string)responseData["str_redirect_location"];
                response.StatusCode       = responseCode;
            }

            response.AddHeader("Content-type", contentType);

            byte[] buffer;

            if (!contentType.Contains("image"))
            {
                buffer = Encoding.UTF8.GetBytes(responseString);
            }
            else
            {
                buffer = Convert.FromBase64String(responseString);
            }

            response.SendChunked     = false;
            response.ContentLength64 = buffer.Length;
            response.ContentEncoding = Encoding.UTF8;

            try
            {
                response.Body.Write(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("[OSHttpHttpHandler]: Error:  {0}", ex.Message);
            }
            finally
            {
                response.Send();
            }

            return(OSHttpHandlerResult.Done);
        }