public void Handle(System.Net.HttpListenerContext context)
        {
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            Utils.CorsConfig(request, response);
            response.StatusCode = (int)HttpStatusCode.OK;
            String dir = request.QueryString.Get("dir");

            if (request.HttpMethod == "OPTIONS")
            {
                response.Close();
            }
            else
            {
                try
                {
                    List <DocFile> docfiles     = GetFiles(dir);
                    String         serialized   = Serialization.SerializeToJson <List <DocFile> >(docfiles);
                    byte[]         messageBytes = Encoding.Default.GetBytes(serialized);
                    response.OutputStream.Write(messageBytes, 0, messageBytes.Length);
                    // Send the HTTP response to the client
                    response.ContentType = "application/json";
                    response.Close();
                }
                catch (Exception ex)
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    byte[] messageBytes = Encoding.Default.GetBytes(ex.Message);
                    response.OutputStream.Write(messageBytes, 0, messageBytes.Length);
                    response.ContentType = "application/json";
                    response.Close();
                }
            }
        }
示例#2
0
        private void Listener_ProcessRequest(System.Net.HttpListenerContext context)
        {
            string       body = null;
            StreamReader sr   = new StreamReader(context.Request.InputStream);

            using (sr)
            {
                body = sr.ReadToEnd();
            }

            var method = context.Request.Url.AbsolutePath.Replace("/", "").ToLower();

            if (method.Equals("registerplayer"))
            {
                var data = JsonConvert.DeserializeObject <ConnectedPlayer>(body);

                context.Response.StatusCode  = (int)HttpStatusCode.OK;
                context.Response.ContentType = "text/plain";
                using (StreamWriter sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine(context.Request.RawUrl);
                }


                lock (_connectedPlayers)
                {
                    _connectedPlayers.Add(data);
                }
            }
        }
        } //End of WebRequestCallback

        private void ProcessRequest(System.Net.HttpListenerContext Context)
        {
            HttpListenerRequest  request  = Context.Request;
            HttpListenerResponse response = Context.Response;

            //front support returning xml to Http client
            response.ContentType = "text/xml";
            //Construct a response
            response.StatusCode = 200;
            StreamWriter writer = new StreamWriter(response.OutputStream, System.Text.UTF8Encoding.UTF8);

            try
            {
                short rv = process2(request, writer);
                if (rv == ReturnValue.ERROR)
                {
                    response.StatusCode = 500;
                }
            }
            catch (System.Xml.XPath.XPathException e)
            {
                //when XDocument.XPathSelectElements() throws XPathException but not when a client send path to query
                Error.createError(sharedData, Error.INTERNAL_ERROR, e.Message).Save(writer);
            }
            writer.Close();
        }
示例#4
0
    public WebResultSet(System.Net.HttpListenerContext ctx, System.IO.MemoryStream outStream)
    {
        Ctx       = ctx;
        OutStream = outStream;

        if (ctx.Request.HasEntityBody)
        {
            if (ctx.Request.ContentType == "application/x-www-form-urlencoded")
            {
                string input = null;
                using (System.IO.StreamReader reader = new System.IO.StreamReader(ctx.Request.InputStream))
                {
                    input = reader.ReadToEnd( );
                }
                Form = System.Web.HttpUtility.ParseQueryString(input);
            }
            else /* Assume multipart/form-data */
            {
                Files = ParseMultipart(ctx.Request);
            }
        }

        CookieNames = new G.List <string>();
        foreach (string k in ctx.Request.Cookies)
        {
            CookieNames.Add(k);
        }
    }
        public void Handle(System.Net.HttpListenerContext context)
        {
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            Utils.CorsConfig(request, response);

            response.StatusCode = (int)HttpStatusCode.OK;

            List <PrinterModel> printers = new List <PrinterModel>();
            PrinterSettings     ps       = new PrinterSettings();

            foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                printers.Add(new PrinterModel()
                {
                    Name    = printer,
                    Default = ps.PrinterName == printer
                });
            }

            String serialized = Serialization.SerializeToJson <List <PrinterModel> >(printers);

            byte[] messageBytes = Encoding.Default.GetBytes(serialized);
            response.OutputStream.Write(messageBytes, 0, messageBytes.Length);
            // Send the HTTP response to the client
            response.ContentType = "application/json";
            response.Close();
        }
示例#6
0
        void _HttpListener_ResponseEvent(System.Net.HttpListenerContext ctx)
        {
            //GET 还是 POST 是根据访问方式得来的
            try
            {
                //响应消息 根据第一列,响应第三列
                Invoke((MethodInvoker)(() =>
                {
                    foreach (ListViewItem item in listView1.Items)
                    {
                        string url = ctx.Request.Url.ToString();
                        url = url.Contains('?') ? url.Substring(0, url.IndexOf('?')) : url;

                        if (item.SubItems[0].Text == url || item.SubItems[0].Text == url + "/")
                        {
                            ResponseWrite(item.SubItems[2].Text, ctx.Response);
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
            }

            //测试页面
            //if (!ctx.Request.Url.AbsolutePath.ToLower().Contains("login"))
            //{
            //    ResponseWrite("<html><head><title>ODOO</title></head><body><div><h1>这是一个测试页面</h1><p>如果能打开这个页面,那么HttpServer已经启动成功了。</body></html>", ctx.Response, "text/html");
            //}
            //else
            //{
            //    ResponseWrite("ok", ctx.Response);
            //}
        }
        protected override void ProcessRequest(System.Net.HttpListenerContext Context)
        {
            HttpListenerRequest  Request  = Context.Request;
            HttpListenerResponse Response = Context.Response;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Request.HttpMethod + " " + Request.RawUrl + " Http/" + Request.ProtocolVersion.ToString());

            if (Request.UrlReferrer != null)
            {
                sb.AppendLine("Referer: " + Request.UrlReferrer);
            }

            if (Request.UserAgent != null)
            {
                sb.AppendLine("User-Agent: " + Request.UserAgent);
            }

            for (int x = 0; x < Request.Headers.Count; x++)
            {
                sb.AppendLine(Request.Headers.Keys[x] + ":" + " " + Request.Headers[x]);
            }

            sb.AppendLine();

            string htm = "<html><body><h1>Hello world</h1>Time is: " + DateTime.Now.ToString() + "<pre>" + sb.ToString() + "</pre>";

            string path = Request.Url.LocalPath.ToLower();

            if (path == "" || path == "/")
            {
                path = "/index.html";
            }
            if (path == "/ok")
            {
                htm = "OK";
                Response.ContentType = "text/plain";
            }
            else
            {
                //htm = ResourceHelper.GetEmbeddedResource("Test" + path);
                //if (!string.IsNullOrEmpty(htm))
                //{
                //    htm = htm.Replace("{###}", MsgHost.Port.ToString());
                //}
                //else htm = "";
                Response.ContentType = "text/html";
            }

            byte[] buf = System.Text.Encoding.UTF8.GetBytes(htm);

            Response.ContentLength64 = buf.Length;

            Stream OutputStream = Response.OutputStream;

            OutputStream.Write(buf, 0, buf.Length);
            OutputStream.Close();
        }
 internal HttpListenerConnectionInfo(System.Net.HttpListenerContext ctx)
 {
     this.inner      = ctx;
     this.localIp    = this.inner.Request.LocalEndPoint.Address;
     this.localPort  = this.inner.Request.LocalEndPoint.Port;
     this.remoteIp   = this.inner.Request.RemoteEndPoint.Address;
     this.remotePort = this.inner.Request.RemoteEndPoint.Port;
 }
示例#9
0
 public RequestContext(System.Net.HttpListenerContext httpListenerContext) : this()
 {
     this.HttpListenerContext    = new HttpListenerContextAdapter(httpListenerContext);
     this.TimeReceived           = DateTime.UtcNow;
     this.startMillisecond       = NativeMethods.timeGetTime();
     this.CreatorManagedThreadId = Thread.CurrentThread.ManagedThreadId;
     this.InputEntryPointType    = EntryPointType.Invalid;
 }
示例#10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SystemHttpRequest"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public SystemHttpRequest(System.Net.HttpListenerContext context)
 {
     _request = context.Request;
     Enum.TryParse <HttpVerbs>(_request.HttpMethod.Trim(), true, out var verb);
     HttpVerb       = verb;
     Cookies        = new SystemCookieCollection(_request.Cookies);
     LocalEndPoint  = _request.LocalEndPoint;
     RemoteEndPoint = _request.RemoteEndPoint;
 }
示例#11
0
        void _HttpListener_ResponseEvent(System.Net.HttpListenerContext ctx)
        {
            //直接获取数据
            Dictionary <string, string> rets = _HttpListener.getData(ctx);

            ////获取get数据
            //Dictionary<string, string> retGets = _HttpListener.getData(ctx, THttpListener.DataType.Get);
            ////获取post数据
            //Dictionary<string, string> retPosts = _HttpListener.getData(ctx, THttpListener.DataType.Post);
            ResponseWrite(ctx.Request.AcceptTypes[0], JsonConvert.SerializeObject(rets), ctx.Response);
        }
示例#12
0
        public SystemHttpContext(System.Net.HttpListenerContext context)
        {
            _context = context;

            Request        = new SystemHttpRequest(_context);
            User           = _context.User;
            Response       = new SystemHttpResponse(_context);
            Id             = UniqueIdGenerator.GetNext();
            LocalEndPoint  = Request.LocalEndPoint;
            RemoteEndPoint = Request.RemoteEndPoint;
        }
示例#13
0
        void _HttpListener_ResponseEvent(System.Net.HttpListenerContext ctx)
        {
            //直接获取数据
            Dictionary <string, string> rets = _HttpListener.getData(ctx);
            //获取get数据
            Dictionary <string, string> retGets = _HttpListener.getData(ctx, THttpListener.DataType.Get);

            //获取post数据
            Dictionary <string, string> retPosts = _HttpListener.getData(ctx, THttpListener.DataType.Post);

            ResponseWrite(ctx.Request.AcceptTypes[0], "Ret", ctx.Response);
        }
示例#14
0
        private void ProcessRequest(System.Net.HttpListenerContext Context)
        {
            Stream request = Context.Request.InputStream;

            string input = null;

            using (StreamReader sr = new StreamReader(request))
            {
                input = sr.ReadToEnd();
            }
            Console.WriteLine(input);
        }
示例#15
0
        public SystemHttpContext(System.Net.HttpListenerContext context)
        {
            _context = context;

            Request        = new SystemHttpRequest(_context);
            User           = _context.User ?? Auth.NoUser;
            Response       = new SystemHttpResponse(_context);
            Id             = UniqueIdGenerator.GetNext();
            LocalEndPoint  = Request.LocalEndPoint;
            RemoteEndPoint = Request.RemoteEndPoint;
            Route          = RouteMatch.None;
            Session        = SessionProxy.None;
        }
示例#16
0
        public Dictionary <string, string> getData(System.Net.HttpListenerContext ctx)
        {
            var request = ctx.Request;

            if (request.HttpMethod == "GET")
            {
                return(getData(ctx, DataType.Get));
            }
            else
            {
                return(getData(ctx, DataType.Post));
            }
        }
示例#17
0
 public void Run()
 {
     while (serv.Running)
     {
         try
         {
             Net.HttpListenerContext context = listener.GetContext();
             ThreadPool.QueueUserWorkItem(HandleContext, context);
         }
         catch (Exception)
         {
         }
     }
 }
示例#18
0
 private void WriteBytesToContext(System.Net.HttpListenerContext context, byte[] buffer)
 {
     try
     {
         context.Response.ContentLength64 = buffer.Length;
         System.IO.Stream output = context.Response.OutputStream;
         output.Write(buffer, 0, buffer.Length);
         output.Close();
     }
     catch (Exception pe)
     {
         // TODO: add error logging
     }
 }
示例#19
0
        void _HttpListener_ResponseEvent(System.Net.HttpListenerContext ctx)
        {
            Dictionary <string, string> requestParameter = _httpListener.getData(ctx);

            //测试页面
            if (ctx.Request.Url.AbsolutePath.ToUpper().Contains("ODOO/TEST"))
            {
                ResponseWrite("<html><head><title>ODOO</title></head><body><div><h1>这是一个测试页面</h1><p>如果能打开这个页面,那么HttpServer已经启动成功了。</body></html>", ctx.Response, "text/html");
            }
            else
            {
                ResponseWrite("这是响应的消息", ctx.Response);
            }
        }
示例#20
0
        private bool WebSocketService_OnAuthentication(System.Net.HttpListenerContext listenerContext)
        {
            Console.WriteLine("身份验证");

            Console.WriteLine("请求头信息:");
            var headers = listenerContext.Request.Headers;

            foreach (string key in headers.AllKeys)
            {
                Console.WriteLine($"【{key}】:【{headers[key]}】");
            }

            return(true);
        }
示例#21
0
    private void requestWaitELFloader(IAsyncResult ar)
    {
        Console.WriteLine("[INFO] requestWaitELFloader Start");

        if (!http.IsListening)
        {
            return;
        }
        System.Net.HttpListenerContext c = http.EndGetContext(ar);
        http.BeginGetContext(requestWaitELFloader, null);

        String url = tuneUrl(c.Request.RawUrl);

        Console.WriteLine("[INFO] requestWaitELFloader c.Request.RawUrl: " + c.Request.RawUrl);

        String fullPath = string.IsNullOrEmpty(url) ? RootPath : Path.Combine(RootPath, url);

        Console.WriteLine("[INFO] requestWaitELFloader fullPath: " + fullPath);

        if (Directory.Exists(fullPath))
        {
            returnDirContents(c, fullPath);
        }
        else if (File.Exists(fullPath))
        {
            Console.WriteLine("[INFO] requestWaitELFloader - File.Exists(fullPath): " + fullPath);
            Console.WriteLine("[INFO] requestWaitELFloader - c.Request: " + c.Request);
            Console.WriteLine("[INFO] requestWaitELFloader - c.Response: " + c.Response);

            returnFileELFloader(c, fullPath);
        }
        else if (fullPath.Contains(".html?"))
        {
            string FilePathWithoutParams = String.Empty;

            int index = fullPath.IndexOf("?");
            if (index > 0)
            {
                FilePathWithoutParams = fullPath.Remove(index, (fullPath.Length - index));
                Console.WriteLine("[INFO] requestWaitELFloader FilePathWithoutParams: " + FilePathWithoutParams);
            }

            returnFile(c, FilePathWithoutParams);
        }
        else
        {
            return404(c);
        }
    }
示例#22
0
        public Dictionary <string, string> getData(System.Net.HttpListenerContext ctx, DataType type)
        {
            var rets    = new Dictionary <string, string>();
            var request = ctx.Request;

            switch (type)
            {
            case DataType.Post:
                if (request.HttpMethod == "POST")
                {
                    string rawData;
                    using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        rawData = reader.ReadToEnd();
                    }
                    //如果是参数字符的形式
                    if (request.ContentType == "text/plain")
                    {
                        string[] rawParams = rawData.Split('&');
                        foreach (string param in rawParams)
                        {
                            string[] kvPair = param.Split('=');
                            string   key    = kvPair[0];
                            string   value  = HttpUtility.UrlDecode(kvPair[1]);
                            rets[key] = value;
                        }
                    }
                    //如果参数是json
                    else if (request.ContentType == "application/json")
                    {
                        rets["0"] = rawData;
                    }
                }
                break;

            case DataType.Get:
                if (request.HttpMethod == "GET")
                {
                    string[] keys = request.QueryString.AllKeys;
                    foreach (string key in keys)
                    {
                        rets[key] = request.QueryString[key];
                    }
                }
                break;
            }
            return(rets);
        }
示例#23
0
        static void httpListenerCallback(IAsyncResult result)
        {
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            try
            {
                if (listener.IsListening)
                {
                    // continue to listen
                    listener.BeginGetContext(new AsyncCallback(httpListenerCallback), listener);

                    // handle the incoming request
                    System.Net.HttpListenerContext context = listener.EndGetContext(result);
                    System.Net.HttpListenerRequest request = context.Request;
                    string responseString;
                    if (string.Compare("/appletv/us/js/application.js", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\application.js");
                    }
                    else if (string.Compare("/appletv/us/nav.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\index.xml");
                    }
                    else if (string.Compare("/appletv/studios/marvel/ironman3/index-hd.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.index-hd.xml");
                    }
                    else if (string.Compare("/appletv/studios/marvel/ironman3/videos/trailer1-hd.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.videos.trailer1-hd.xml");
                    }
                    else
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml");
                    }
                    System.Net.HttpListenerResponse response = context.Response;
                    //string responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml");
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
示例#24
0
        public void Handle(System.Net.HttpListenerContext context)
        {
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            Utils.CorsConfig(request, response);


            response.StatusCode = (int)HttpStatusCode.OK;

            const String message = "true";

            byte[] messageBytes = Encoding.Default.GetBytes(message);
            response.OutputStream.Write(messageBytes, 0, messageBytes.Length);
            // Send the HTTP response to the client
            response.Close();
        }
        public override bool Handle(System.Net.HttpListenerContext context)
        {
            IPAddress clientIP = context.Request.RemoteEndPoint.Address;

            List <string> HostIP = new List <string>();

            foreach (string AuthorizedHost in m_securityConfig.Allowed_Hosts)
            {
                HostIP.Add(Dns.GetHostAddresses(AuthorizedHost)[0].ToString());
            }

            if (!(m_securityConfig.Allowed_IPs.Contains(clientIP) || HostIP.Contains(clientIP.ToString())))
            {
                throw new AccessDeniedException("Access to the resource was denied", context);
            }

            return(true);
        }
示例#26
0
        private void Listen()
        {
            _listener = new System.Net.HttpListener();
            _listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
            _listener.Start();

            while (true)
            {
                try
                {
                    System.Net.HttpListenerContext context = _listener.GetContext();
                    Process(context);
                }
                catch (Exception ex)
                {
                }
            }
        }
示例#27
0
        //这里进行转发
        private void ProcessRequest(System.Net.HttpListenerContext Context)
        {
            Stream request = Context.Request.InputStream;

            string input = null;

            using (StreamReader sr = new StreamReader(request))
            {
                input = sr.ReadToEnd();
            }
            string strData = input.Split('\n')[3];

            //浏览器重启,读取一次终端ip,更新client连接
            if (strData.StartsWith("http"))
            {
                DataSender.PushUrl(strData);
            }
        }
示例#28
0
        public void HTTPSessionThread()
        {
            while (true)
            {
                try
                {
                    // 以HttpListener類別的GetContext方法等待傳入之用戶端請求
                    httpContext = httpListener.GetContext();

                    // Set Thread for each HTTP client Connection
                    Thread clientThread = new Thread(new ThreadStart(this.processRequest));
                    clientThread.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }
示例#29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static IWebSessionState GetWebSessionStateByContext(System.Net.HttpListenerContext context)
        {
            IWebSessionState session = null;
            var sessionId            = context.Request.Cookies[SessionIdKey]?.Value;

            if (string.IsNullOrEmpty(sessionId))
            {
                sessionId = context.Response.Cookies[SessionIdKey]?.Value;
                if (string.IsNullOrEmpty(sessionId))
                {
                    sessionId = Guid.NewGuid().ToSimpleString();
                    session   = GetWebSessionById(sessionId);
                    CacheCookies(sessionId, context.Response.Cookies);
                    return(session);
                }
            }
            session = GetWebSessionById(sessionId);
            return(session);
        }
示例#30
0
 public static void executeUploader(System.Net.HttpListenerContext ctx, RykonProcess cp, ServerConfig Servconf)
 {
     if (cp.Method == "POST")
     {
         HttpNameValueCollection o = new HttpNameValueCollection(ref ctx);
         //WebServer.SaveFile(ctx.Request.ContentEncoding, WebServer.GetBoundary(ctx.Request.ContentType), ctx.Request.InputStream);
     }
     else
     {
         if (cp.LocalPath.EndsWith("/Upload/thumb.png"))
         {
             cp.OutPutData             = AppHelper.ReadFileBts(Servconf.RootDirectory + "\\" + cp.LocalPath);
             cp.Requesting_Binary_data = true;
             return;
         }
         cp.Output_document = WebDesigner.getUpload_PostPage(cp.MainUrl(), Servconf.UploadPassword, Servconf.CSRF);
         cp.OutPutData      = Encoding.UTF8.GetBytes(cp.Output_document);
     }
 }
示例#31
-1
        public void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;
            using (StreamReader rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());
            using (var db = new Database())
            {
                var acc = db.GetAccount(int.Parse(query["accountId"]));
                var chr = db.LoadCharacter(acc, int.Parse(query["charId"]));

                var cmd = db.CreateQuery();
                cmd.CommandText = @"SELECT time, killer, firstBorn FROM death WHERE accId=@accId AND chrId=@charId;";
                cmd.Parameters.AddWithValue("@accId", query["accountId"]);
                cmd.Parameters.AddWithValue("@charId", query["charId"]);
                int time;
                string killer;
                bool firstBorn;
                using (var rdr = cmd.ExecuteReader())
                {
                    rdr.Read();
                    time = Database.DateTimeToUnixTimestamp(rdr.GetDateTime("time"));
                    killer = rdr.GetString("killer");
                    firstBorn = rdr.GetBoolean("firstBorn");
                }

                using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
                    wtr.Write(chr.FameStats.Serialize(acc, chr, time, killer, firstBorn));
            }
        }
示例#32
-1
        public static Body ReadBodyFromRequest(HttpListenerContext ctx)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");

            try
            {
                if (!ctx.Request.HasEntityBody) return null;

                byte[] data = new byte[ctx.Request.ContentLength64];
                int offset = 0;
                int count = data.Length;
                // Read may return anything from 0 to ContentLength64.
                while (0 < count)
                {
                    int readed = ctx.Request.InputStream.Read(data, offset, count);
                    if (readed == 0) break;
                    offset += readed;
                    count -= readed;
                }
                NetStatistics.ReadBytes(count);
                return ElementSerializer.DeSerializeElement<Body>(Encoding.UTF8.GetString(data));
            }
            catch (Exception e)
            {
                if (e is HttpListenerException || e is ObjectDisposedException)
                {
                    // ignore
                }
                else
                {
                    log.ErrorFormat("Error read body from request: {0}", e);
                }
            }
            return null;
        }
 private static void AccountUserTypeHandler(HttpListenerContext context)
 {
     switch (context.Request.RawUrl)
     {
         case "/api/v1/accounts/usertypes":
             if (context.Request.HttpMethod == "GET")
             {
                 context.Response.StatusCode = (int)HttpStatusCode.OK;
                 context.Response.OutputStream.Write(expectedUserTypesResponse);
             }
             else if (context.Request.HttpMethod == "PUT")
             {
                 requestContent = context.Request.GetRequestAsString();
                 if (context.Request.Headers.AllKeys.Any(c => c == ApiUrls.AuthorizeTokenHeaderName))
                     context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                 else
                     context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
             }
             break;
         case "/api/authorize":
             context.Response.Headers.Add(ApiUrls.AuthorizeTokenHeaderName, "OK");
             break;
         default:
             context.Response.StatusCode = (int)HttpStatusCode.NotFound;
             break;
     }
 }
示例#34
-1
        static void ProcessRequest(HttpListenerContext context)
        {
            Console.WriteLine("{0} {1} {2}", DateTime.UtcNow.ToString("o"), context.Request.HttpMethod, context.Request.Url.PathAndQuery);

            var service = GetService(context.Request.Url.PathAndQuery);
            context.Response.Headers["Content-Type"] = String.Format("application/x-git-{0}-advertisement", service);
            context.Response.Headers["Expires"] = "Fri, 01 Jan 1980 00:00:00 GMT";
            context.Response.Headers["Pragma"] = "no-cache";
            context.Response.Headers["Cache-Control"] = "no-cache, max-age=0, must-revalidate";

            if (context.Request.HttpMethod == "GET" && context.Request.Url.AbsolutePath == "/info/refs")
            {
                var input = String.Format("# service=git-{0}\n", service);
                var toWrite = (input.Length + 4).ToString("x").PadLeft(4, '0') + input;
                context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(toWrite), 0, Encoding.UTF8.GetByteCount(toWrite));

                toWrite = "0000";
                context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(toWrite), 0, Encoding.UTF8.GetByteCount(toWrite));

                var exe = new Executable();
                var args = String.Format("{0} --stateless-rpc --advertise-refs \"{1}\"", service, Program.RepositoryPath);
                exe.ExecuteAsync(args, context.Response.OutputStream).Wait();
                context.Response.Close();
            }
            else
            {
                var exe = new Executable();
                var args = String.Format("{0} --stateless-rpc \"{1}\"", service, Program.RepositoryPath);
                exe.ExecuteAsync(args, context.Response.OutputStream, GetInputStream(context.Request)).Wait();
                context.Response.Close();
            }
        }
示例#35
-1
        static void ProcessRequest(HttpListenerContext context)
        {
            try
            {
                IRequestHandler handler;

                if (!RequestHandlers.Handlers.TryGetValue(context.Request.Url.LocalPath, out handler))
                {
                    context.Response.StatusCode = 400;
                    context.Response.StatusDescription = "Bad request";
                    using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
                        wtr.Write("<h1>Bad request</h1>");
                }
                else
                    handler.HandleRequest(context);
            }
            catch (Exception e)
            {
                using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
                    wtr.Write("<Error>Internal Server Error</Error>");
                Console.Error.WriteLine(e);
            }

            context.Response.Close();
        }
        private void GetSigningPage(HttpListenerContext context)
        {
            var signingKey = context.Request.Url.Query.TrimStart('?').Split('&')
                .Select(t => t.Split('=')).ToDictionary(t => t[0], t => t[1]);
            var html = string.Empty;
            if (KeepSecretInServer)
            {
                html = System.IO.File.ReadAllText("EmbeddedSigningSample.secured.html")
                    .Replace("[AuthGenerator]", SampleParameters.GetAuthHeadersUrl)
                    .Replace("[ClientAccessTokenGenerator]", SampleParameters.GetClientAccessTokenUrl);
            }
            else
            {
                html = System.IO.File.ReadAllText("EmbeddedSigningSample.html")
                    .Replace("[APISecret]", SDKClient.APISecret);
            };

            html = html.Replace("[APIKEY]", SDKClient.APIKey)
            .Replace("[APIServiceUrl]", SDKClient.ServiceBaseUrl)
            .Replace("[APIVersion]", SDKClient.APIVersion)
            .Replace("[SigningKey]", signingKey["key"]);

            WriteResponse(context.Response, html);
            System.Threading.Thread.Sleep(2000);
        }
        protected override Task ProcessRequestAsync(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
                return ((object)null).AsTaskResult();

            var operationName = context.Request.GetOperationName().UrlDecode();

            var httpReq = context.ToRequest(operationName);
            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;
            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return task;
            }

            return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
                .AsTaskException();
        }
        public async Task Response(HttpListenerContext context)
        {
            var localPath = context.Request.MapFilePath(directory);

            var type = context.Request.QueryString["type"] ?? "file";
            switch (type)
            {
                case "file":
                case "files":
                    var onlyFilesText = GetFilesJson(localPath);
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteTextAsync(onlyFilesText);
                    break;

                case "folder":
                case "folders":
                case "directory":
                case "directories":
                    var onlyDirectoriesText = GetDirectoriesJson(localPath);
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteTextAsync(onlyDirectoriesText);
                    break;

                case "all":
                case "both":
                default:
                    var filesText = GetFilesJson(localPath);
                    var directoriesText = GetDirectoriesJson(localPath);
                    var jsonText = "{ files: " + filesText + ", directories: " + directoriesText + " }";
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteTextAsync(jsonText);
                    break;
            }
        }
示例#39
-1
 public void GetAnswer(HttpListenerContext context)
 {
     context.Response.StatusCode = (int) HttpStatusCode.OK;
     var bytes = Encoding.UTF8.GetBytes(_lastAnswer);
     context.Response.OutputStream.Write(bytes, 0, bytes.Length);
     Send(context);
 }
示例#40
-1
 public static String sendCommand(HttpListenerContext context, String text)
 {
     context.Response.AddHeader("Access-Control-Allow-Origin", "*");
     String cookie = context.Request.Cookies["session"].Value;
     CleverbotConversation activeConversation;
     bool flag = false;
     if (Sessions.active.ContainsKey(cookie))
     {
         activeConversation = Sessions.active[cookie];
     }
     else
     {
         activeConversation = Cleverbot.Cleverbot.buildSession(text);
         flag = true;
         Sessions.active.Add(cookie, activeConversation);
     }
     if (flag)
     {
         needToDo.Enqueue(activeConversation.latestReply.content);
         return activeConversation.latestReply.content;
     }
     else
     {
         needToDo.Enqueue(activeConversation.speak(text).content);
         return activeConversation.speak(text).content;
     }
 }
示例#41
-1
 private void Put(HttpListenerContext context, string docId)
 {
     var json = context.ReadJson();
     context.SetStatusToCreated("/docs/" + docId);
     var putResult = Database.Put(docId, context.GetEtag(), json, context.Request.Headers.FilterHeaders(), GetRequestTransaction(context));
     context.WriteJson(putResult);
 }
示例#42
-1
        public void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;
            using (StreamReader rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());

            //warning: maybe has hidden url injection
            string id = query["id"];
            foreach (var i in id)
            {
                if (char.IsLetter(i) || i == '_' || i == '-') continue;

                byte[] status = Encoding.UTF8.GetBytes("<Error>Invalid ID.</Error>");
                context.Response.OutputStream.Write(status, 0, status.Length);
                return;
            }

            string path = Path.GetFullPath("texture/_" + id + ".png");
            if (!File.Exists(path))
            {
                byte[] status = Encoding.UTF8.GetBytes("<Error>Invalid ID.</Error>");
                context.Response.OutputStream.Write(status, 0, status.Length);
                return;
            }

            context.Response.ContentType = "image/png";
            using (var i = File.OpenRead(path))
            {
                int c;
                while ((c = i.Read(buff, 0, buff.Length)) > 0)
                    context.Response.OutputStream.Write(buff, 0, c);
            }
        }
示例#43
-1
        public void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;
            using (var rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());

            using (var db = new Database())
            {
                Account acc = db.Verify(query["guid"], query["password"]);
                byte[] status;
                if (acc == null)
                    status = Encoding.UTF8.GetBytes("<Error>Bad login</Error>");
                else
                {
                    try
                    {
                        status =
                            Encoding.UTF8.GetBytes(db.HttpGetGuildMembers(Convert.ToInt32(query["num"]),
                                Convert.ToInt32(query["offset"]), acc));
                    }
                    catch
                    {
                        status = Encoding.UTF8.GetBytes("<Error>Guild member error</Error>");
                    }
                }
                context.Response.OutputStream.Write(status, 0, status.Length);
                context.Response.Close();
            }
        }
 public HttpListenerContextAdapter(HttpListenerContext inner)
 {
     _inner = inner;
     Request = new HttpListenerRequestAdapter(inner.Request);
     Response = new HttpListenerResponseAdapter(inner.Response);
     Items = new HybridDictionary(true);
 }
示例#45
-1
        public void Handle(HttpListenerContext ctx)
        {
            try
            {
                var callInfo = GetCallInfo(ctx);

                if (callInfo.Type == CallType.Submit && ctx.Request.ContentLength64 > 4 * 1024 * 1024)
                {
                    CloseResponseAndWarn(ctx, "Cannot accept messages larger than 4MB.", 413);
                    return;
                }

                string hash = ctx.Request.Headers[HttpHeaders.ContentMd5Key];
                if (hash == null)
                {
                    CloseResponseAndWarn(ctx, "Required header '" + HttpHeaders.ContentMd5Key + "' missing.", 400);
                    return;
                }

                switch(callInfo.Type)
                {
                    case CallType.Submit: HandleSubmit(ctx, callInfo); break;
                    case CallType.DatabusProperty: HandleDatabusProperty(ctx, callInfo); break;
                    case CallType.Ack: HandleAck(ctx, callInfo); break;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Unexpected error", ex);
                CloseResponseAndWarn(ctx, "Unexpected server error", 502);
            }

            Logger.Info("Http request processing complete.");
        }
示例#46
-1
        public void Handle(HttpListenerContext ctx)
        {
            try
            {
                if(!IsGatewayRequest(ctx.Request))
                {
                    //there will always be a responder
                    Configure.Instance.Builder.Build<IHttpResponder>().Handle(ctx);
                    return;
                }

                DataReceived(this, new DataReceivedOnChannelArgs
                                       {
                                           Headers = GetHeaders(ctx),
                                           Data = GetMessageStream(ctx)
                                       });
                ReportSuccess(ctx);

                Logger.Debug("Http request processing complete.");
            }
            catch (HttpChannelException ex)
            {
                CloseResponseAndWarn(ctx, ex.Message, ex.StatusCode);
            }
            catch (Exception ex)
            {
                Logger.Error("Unexpected error", ex);
                CloseResponseAndWarn(ctx, "Unexpected server error", 502);
            }
        }
        protected override void ProcessRequest(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl)) return;

            var operationName = context.Request.GetOperationName();

            var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
            var httpRes = new HttpListenerResponseWrapper(context.Response);
            var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHttpHandler;
            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
                }
                serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
                httpRes.Close();
                return;
            }

            throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
        }
示例#48
-1
        /// <summary>
        /// Handles incoming http request asynchronously
        /// </summary>
		private void ListenerCallback(HttpListenerContext context)
        {
            try
            {
				if (Platform.IsLogLevelEnabled(LogLevel.Debug))
				{
					Platform.Log(LogLevel.Debug, "Handling http request");
					Platform.Log(LogLevel.Debug, "{0}", context.Request.Url.AbsoluteUri);
				}

                HandleRequest(context);
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Error, e, "Error while handling http request:");

                if (context!=null)
                {
                    try
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.StatusDescription = e.InnerException != null ? HttpUtility.HtmlEncode(e.InnerException.Message) : HttpUtility.HtmlEncode(e.Message);
                    }
                    catch(Exception ex)
                    {
                        Platform.Log(LogLevel.Error, ex, "Unable to set response status description");
                    }
                }
            }
        }
示例#49
-1
        public override void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;
            using (var rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());

            using (var db = new Database(Program.Settings.GetValue("conn")))
            {
                Account acc = db.Verify(query["guid"], query["password"]);
                byte[] status;
                if (acc == null)
                    status = Encoding.UTF8.GetBytes("<Error>Account credentials not valid</Error>");
                else
                {
                    MySqlCommand cmd = db.CreateQuery();
                    cmd.CommandText = @"DELETE FROM characters WHERE accId = @accId AND charId = @charId;";
                    cmd.Parameters.AddWithValue("@accId", acc.AccountId);
                    cmd.Parameters.AddWithValue("@charId", query["charId"]);
                    if (cmd.ExecuteNonQuery() > 0)
                        status = Encoding.UTF8.GetBytes("<Success />");
                    else
                        status = Encoding.UTF8.GetBytes("<Error>Internal Error</Error>");
                }
                context.Response.OutputStream.Write(status, 0, status.Length);
            }
        }
        public static void ValidatePostMethodParameters(HttpListenerContext context)
        {
            var request = context.Request;

            CapturedHasEntityBody = request.HasEntityBody;
            CapturedEntityBody = StreamToString(request.InputStream);
        }
示例#51
-1
        static void ProcessRequest(HttpListenerContext context)
        {
            try
            {
                log.InfoFormat("Dispatching request '{0}'@{1}",
                    context.Request.Url.LocalPath, context.Request.RemoteEndPoint);
                IRequestHandler handler;

                if (!RequestHandlers.Handlers.TryGetValue(context.Request.Url.LocalPath, out handler))
                {
                    context.Response.StatusCode = 400;
                    context.Response.StatusDescription = "Bad request";
                    using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
                        wtr.Write("<h1>Bad request</h1>");
                }
                else
                    handler.HandleRequest(context);
            }
            catch (Exception e)
            {
                using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
                    wtr.Write("<Error>Internal Server Error</Error>");
                log.Error("Error when dispatching request", e);
            }

            context.Response.Close();
        }
示例#52
-1
        public override void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;
            using (var rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());

            using (var db = new Database(Program.Settings.GetValue("conn")))
            {
                Account acc = db.Verify(query["guid"], query["password"]);
                byte[] status;
                if (acc == null)
                    status = Encoding.UTF8.GetBytes("<Error>Account credentials not valid</Error>");
                else
                {
                    try
                    {
                        status = Encoding.UTF8.GetBytes(db.GetGuildBoard(acc));
                    }
                    catch (Exception e)
                    {
                        status = Encoding.UTF8.GetBytes("<Error>" + e.Message + "</Error>");
                    }
                }
                context.Response.OutputStream.Write(status, 0, status.Length);
            }
        }
示例#53
-1
 private void GenerateResponse(IModule module, HttpListenerContext context)
 {
     // Process the request then close the stream. All logic is delegated
     // to the supplied IModule implementer.
     module.Process(context.Response.OutputStream, context);
     context.Response.Close();
 }
示例#54
-1
        static async void SolveAsync(HttpListenerContext context)
        {
            Console.WriteLine("New great task!");

            try
            {
                var arr = Converter.ToList(context.Request.InputStream);

//                arr.ForEach(x => Console.Write("{0} ", x));
//                Console.WriteLine();

                arr.Sort();
//                arr.ForEach(x => Console.Write("{0} ", x));
//                Console.WriteLine();

                var bytes = Converter.ToBytes(arr); 
                await context.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
                context.Response.Close();

                Console.WriteLine("Sended");
            }
            catch(Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
示例#55
-1
        private static void UsernamePasswordEchoHandler(HttpListenerContext context)
        {
            var header = context.Request.Headers["Authorization"];
            var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':');

            context.Response.OutputStream.WriteStringUtf8(string.Join("|", parts));
        }
示例#56
-1
 public HttpServiceRequest(string text, HttpListenerContext context)
 {
     Text = text;
     Data = JsonConvert.DeserializeObject<dynamic>(Text);
     Context = context;
     Response = Context.Response;
 }
示例#57
-1
        public async Task<Context> HandleHttp(HttpListenerContext httpContext, Uri baseUri, CancellationToken cancellationToken)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            var request = ConvertRequest(baseUri, httpContext.Request);

            var context = new Context()
            {
                Request = request,
            };

            var staticContentResponse = _staticContentProvider.GetContent(context);
            if (staticContentResponse != null)
            {
                context.Response = staticContentResponse;
            }
            else
            {
                context.Response = await _requestDispatcher.Dispatch(context, cancellationToken).ConfigureAwait(false);
            }

            ConvertResponse(context.Response, httpContext.Response);

            return context;
        }
示例#58
-1
        public void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;
            using (var rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());

            using (var db = new Database())
            {
                List<ServerItem> filteredServers = null;
                Account a = db.Verify(query["guid"], query["password"]);
                if (a != null)
                {
                    if (a.Banned)
                    {
                        filteredServers = YoureBanned();
                    }
                    else
                    {
                        filteredServers = GetServersForRank(a.Rank);
                    }
                }
                else
                {
                    filteredServers = GetServersForRank(0);
                }

                var chrs = new Chars
                {
                    Characters = new List<Char>(),
                    NextCharId = 2,
                    MaxNumChars = 1,
                    Account = db.Verify(query["guid"], query["password"]),
                    Servers = filteredServers
                };
                Account dvh = null;
                if (chrs.Account != null)
                {
                    db.GetCharData(chrs.Account, chrs);
                    db.LoadCharacters(chrs.Account, chrs);
                    chrs.News = db.GetNews(chrs.Account);
                    dvh = chrs.Account;
                }
                else
                {
                    chrs.Account = Database.CreateGuestAccount(query["guid"]);
                    chrs.News = db.GetNews(null);
                }

                var ms = new MemoryStream();
                var serializer = new XmlSerializer(chrs.GetType(),
                    new XmlRootAttribute(chrs.GetType().Name) {Namespace = ""});

                var xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Encoding = Encoding.UTF8;
                XmlWriter xtw = XmlWriter.Create(context.Response.OutputStream, xws);
                serializer.Serialize(xtw, chrs, chrs.Namespaces);
                db.Dispose();
            }
        }
示例#59
-1
        private JObject Alert_1(HttpListenerContext context, long chartId)
        {
            MQLCommandManager mqlCommandManager = DLLObjectWrapper.getInstance().getMQLCommandManager(chartId);
            JObject payload = this.GetJsonPayload(context.Request);
            JObject result = new JObject();
            if (payload == null)
            {
                result["result"] = PARSE_ERROR;
                return result;
            }
            List<Object> parameters = new List<Object>();
            parameters.Add(payload["argument"]);
            int id = mqlCommandManager.ExecCommand(MQLCommand.Alert_1, parameters); // MQLCommand ENUM = 1
            while (mqlCommandManager.IsCommandRunning(id)) ; // block while command is running
            try
            {
                mqlCommandManager.throwExceptionIfErrorResponse(id);
                result["result"] = "";
            }
            catch (Exception e)
            {
                result["error"] = MQLExceptions.convertRESTException(e.ToString());
            }

            return result;
        }
		internal HttpListenerRequest (HttpListenerContext context)
		{
			this.context = context;
			headers = new WebHeaderCollection ();
			input_stream = Stream.Null;
			version = HttpVersion.Version10;
		}