Exemple #1
0
        private static void GetContextCallBack(IAsyncResult ar)
        {
            try
            {
                httpListener = ar.AsyncState as HttpListener;
                HttpListenerContext context = httpListener?.EndGetContext(ar);
                httpListener?.BeginGetContext(GetContextCallBack, httpListener);
                HttpListenerResponse response = context?.Response;

                var computerInfo = new ComputerInfo
                {
                    //UserName = GetSystemInfo.GetUserName(),
                    MacAddress = GetSystemInfo.GetMacAddress(),
                    //ClientLocalIPv6Address = GetSystemInfo.GetClientLocalIPv6Address(),
                    //ClientLocalIPv4Address = GetSystemInfo.GetClientLocalIPv4Address(),
                    //DiskId = GetSystemInfo.GetDiskID(),
                    //CpuId = GetSystemInfo.GetCpuID(),
                    //SystemType = GetSystemInfo.GetSystemType(),
                    //SystemName = GetSystemInfo.GetSystemName(),
                    //TotalPhysicalMemory = GetSystemInfo.GetTotalPhysicalMemory(),
                    //MotherBoardId = GetSystemInfo.GetMotherBoardID()
                };

                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ComputerInfo));
                MemoryStream msObj            = new MemoryStream();
                //将序列化之后的Json格式数据写入流中
                js.WriteObject(msObj, computerInfo);
                msObj.Position = 0;
                //从0这个位置开始读取流中的数据
                StreamReader sr   = new StreamReader(msObj, Encoding.UTF8);
                string       json = sr.ReadToEnd();
                sr.Close();
                msObj.Close();

                string responseString = "success_jsonpCallback(" + json + ")";
                byte[] buffer         = Encoding.UTF8.GetBytes(responseString);

                if (response != null)
                {
                    response.ContentLength64 = buffer.Length;
                    response.ContentType     = "text/plain";
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);

                    output.Close();
                }
            }
            catch (Exception e)
            {
                //
            }
        }
Exemple #2
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                try
                {
                    Console.WriteLine(context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    ThisLogger.Info(context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    //
                    var stringarr = context.Request.Url.AbsolutePath.Split('/');
                    //var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3)
                    {
                        Console.WriteLine(@"Invalid request");
                        ThisLogger.Error(@"Invalid request");
                        //
                        ErrorResponse(context, @"Invalid request parameter");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    var filename = stringarr[3];
                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = EditSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        var    fileExt  = filename.Substring(filename.LastIndexOf('.') + 1);
                        string UserId   = context.Request.QueryString["userid"].ToString();
                        string UserName = context.Request.QueryString["username"].ToString();
                        //editSession = new FileSession(filename, m_docsPath + "/" + filename, @"_", @"_", @"*****@*****.**", false);
                        editSession = new FileSession(filename, m_docsPath + "/" + filename, UserId, UserName, "", false);

                        EditSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && stringarr[2].Equals(@"files") && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        //request of checkfileinfo, will be called first
                        var memoryStream = new MemoryStream();
                        var json         = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                        json.WriteObject(memoryStream, editSession.GetCheckFileInfo());
                        memoryStream.Flush();
                        memoryStream.Position = 0;
                        StreamReader streamReader = new StreamReader(memoryStream);
                        var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                        context.Response.ContentType     = @"application/json";
                        context.Response.ContentLength64 = jsonResponse.Length;
                        context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                        context.Response.Close();
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        // get and put file's content
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            if (String.IsNullOrEmpty(context.Request.QueryString["del"]))
                            {
                            }
                            else
                            {
                                string DelFileName = context.Request.QueryString["del"].ToString();
                                File.Delete(m_docsPath + "/" + DelFileName);
                                string[] DelFileNameArr = DelFileName.Split(new char[2] {
                                    '_', '.'
                                });
                                string CurrentFile = "";
                                //StringBuilder FileSB = new StringBuilder();
                                for (int i = 1; i < Convert.ToInt16(DelFileNameArr[1]); i++)
                                {
                                    CurrentFile = DelFileNameArr[0] + "_" + i.ToString() + "." + DelFileNameArr[2];
                                    if (File.Exists(m_docsPath + "/" + CurrentFile))
                                    {
                                        File.Delete(m_docsPath + "/" + CurrentFile);
                                    }
                                    //FileSB.Append(CurrentFile+"///");
                                }
                            }
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                            context.Response.StatusCode = (int)HttpStatusCode.OK;
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        //lock,
                        Console.WriteLine("request lock: " + context.Request.Headers["X-WOPI-Override"]);
                        ThisLogger.Info("request lock: " + context.Request.Headers["X-WOPI-Override"]);
                        //
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    //token
                    //else if...
                    //
                    else
                    {
                        Console.WriteLine(@"Invalid request parameters");
                        ThisLogger.Error(@"Invalid request parameters");
                        //
                        ErrorResponse(context, @"Invalid request cobalt parameter");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"process request exception:" + ex.Message);
                    ThisLogger.Fatal(@"process request exception:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"get request context:" + ex.Message);
                ThisLogger.Fatal(@"get request context:" + ex.Message);
                //
                return;
            }
        }
Exemple #3
0
        private void OnHttpRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                listener.BeginGetContext(OnHttpRequest, listener);

                RequestPackage package;
                if (!ActionDispatcher.TryDecodePackage(context, out package))
                {
                    return;
                }

                GameSession session;
                if (package.ProxySid != Guid.Empty)
                {
                    session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                    session.ProxySid = package.ProxySid;
                }
                else
                {
                    session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
                }
                package.Bind(session);

                ActionGetter httpGet = ActionDispatcher.GetActionGetter(package);
                if (package.IsUrlParam)
                {
                    httpGet["UserHostAddress"] = session.EndAddress;
                    httpGet["ssid"]            = session.KeyCode.ToString("N");
                    httpGet["http"]            = "1";
                }

                var httpresponse = new SocketGameResponse();
                httpresponse.WriteErrorCallback += new ScutActionDispatcher().ResponseError;

                var clientConnection = new HttpClientConnection
                {
                    Context      = context,
                    Session      = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, httpRequestTimeout, Timeout.Infinite);
                byte[] respData = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    if (CheckRemote(package.RouteName, httpGet))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, httpGet, response);
                        respData = response.PopBuffer();
                    }
                }
                else
                {
                    DoAction(httpGet, httpresponse);
                    respData = httpresponse.ReadByte();
                }
                OnHttpResponse(clientConnection, respData, 0, respData.Length);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnHttpRequest error:{0}", ex);
            }
        }
Exemple #4
0
        private void ProcessRequest(IAsyncResult result)
        {
            if (_HTFanCtrl != null)
            {
                HttpListener         listener = (HttpListener)result.AsyncState;
                HttpListenerContext  context  = listener.EndGetContext(result);
                HttpListenerRequest  request  = context.Request;
                HttpListenerResponse response = context.Response;

                string htmlResponse = "";
                switch (request.RawUrl)
                {
                case "/":
                    htmlResponse = StatusPage(request, "status");
                    break;

                case "/statusdata":
                    htmlResponse = GetStatusData(request, "statusdata");
                    break;

                case "/currentmovie":
                    htmlResponse = GetCurrentMovie(request, "currentmovie");
                    break;

                case "/settings":
                    htmlResponse = SettingsPage(request, "settings");
                    break;

                case "/savesettings":
                    SaveSettings(request, "savesettings");
                    break;

                case "/raspiwifi":
                    htmlResponse = RasPiWiFiPage(request, "raspiwifi");
                    break;

                case "/savewifi":
                    SaveWiFi(request, "savewifi");
                    break;

                case "/downloadlist":
                    htmlResponse = DownloadListPage(request, "downloadlist");
                    break;

                case "/download":
                    htmlResponse = DownloadPage(request, "download");
                    break;

                case "/manage":
                    htmlResponse = ManagePage(request, "manage");
                    break;

                case "/edit":
                    htmlResponse = EditPage(request, "edit");
                    break;

                case "/add":
                    htmlResponse = GetHtml("add");
                    break;

                case "/uploadlocal":
                    _waitForFile = true;
                    UploadLocal(request, "uploadlocal");
                    break;

                case "/rename":
                    RenameFile(request, "rename");
                    break;

                case "/delete":
                    _waitForFile = true;
                    DeleteFile(request, "delete");
                    break;

                case "/save":
                    SaveFile(request, "save");
                    break;

                case "/selectplexplayer":
                    htmlResponse = GetHtml("selectplexplayer");
                    break;

                case "/getplexplayers":
                    htmlResponse = GetPlexPlayer(request, "getplexplayers");
                    break;

                case "/saveplexplayer":
                    _waitForFile = true;
                    SavePlexPlayer(request, "saveplexplayer");
                    break;

                case "/reload":
                    _HTFanCtrl.ReInitialize();
                    break;

                case "/togglefan":
                    _HTFanCtrl.ToggleFan();
                    break;

                case "/toggleoffset":
                    _HTFanCtrl._offsetEnabled = !_HTFanCtrl._offsetEnabled;
                    _HTFanCtrl.ReInitialize();
                    break;

                case "/fantester":
                    htmlResponse = GetHtml("fantester");
                    break;

                case "/loadedwindtrack":
                    htmlResponse = GetHtml("loadedwindtrack");
                    break;

                case "/loadedwindtrackdata":
                    htmlResponse = LoadedWindTrackData(request, "loadedwindtrackdata");
                    break;

                case "/fancmd":
                    FanCmd(request, "fancmd");
                    break;

                case "/clearerror":
                    _HTFanCtrl._errorStatus = null;
                    break;

                case "/checkupdate":
                    htmlResponse = CheckUpdatePage(request, "checkupdate");
                    break;

                case "/raspiupdate":
                    ($"nohup {Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "updater.sh")} &>/dev/null &").Bash();
                    Environment.Exit(0);
                    break;

                case "/shutdown":
                    Environment.Exit(0);
                    break;

                default:
                    break;
                }

                byte[] buffer = Encoding.ASCII.GetBytes(htmlResponse);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                try
                {
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }
                catch { }
            }
        }
        private void ProcessRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;
            HttpListenerRequest request = null;

            try
            {
                context = _listener.EndGetContext(result);
                request = context.Request;


                string postData;
                using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                {
                    postData = WebUtility.UrlDecode(reader.ReadToEnd());

                    var rawProps = postData.Split('&');
                    Dictionary <string, string> props = new Dictionary <string, string>(rawProps.Length);

                    foreach (var prop in rawProps)
                    {
                        var rawEntry = prop.Split('=');

                        if (rawEntry.Length == 2 && !props.ContainsKey(rawEntry[0].ToLower()))
                        {
                            props.Add(rawEntry[0].ToLower(), rawEntry[1]);
                        }
                    }

                    props.TryGetValue("url", out string url);

                    if (!string.IsNullOrWhiteSpace(url) && _blockedUrls.Any(str => url.Contains(str)))
                    {
                        var response = context.Response;
                        response.AddHeader("Access-Control-Allow-Origin", "*");
                        response.ContentType = "text/html";

                        var buffer = Encoding.UTF8.GetBytes("b");
                        response.ContentLength64 = buffer.Length;
                        var output = response.OutputStream;

                        output.Write(buffer, 0, buffer.Length);
                        output.Close();
                        response.Close();

                        Debug.WriteLine($"Blocked url: {url}");
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.AddHeader("Access-Control-Allow-Origin", "*");
                        context.Response.Close();
                    }
                }

                _listener.BeginGetContext(new AsyncCallback(ProcessRequest), null);
            }
            catch (ObjectDisposedException)
            {
            }
        }
        /// <summary>
        /// Process the web request
        /// </summary>
        /// <param name="result"></param>
        private void ProcessRequest(IAsyncResult result)
        {
            string responseString = "";
            string pageString     = "";
            string responseType   = "text/html";
            string filetype       = "";
            bool   binary         = false;

            byte[]       buffer;
            int          pos;
            StreamReader streamReader;

            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = listener.EndGetContext(result);
            HttpListenerRequest request  = context.Request;

            string path      = rootPath + request.RawUrl;
            string webMethod = request.HttpMethod;

            if (path == rootPath + "/")
            {
                path += defaultPage;
            }

            filetype = Path.GetExtension(path);
            // take off any parameters at the end of the url
            filetype = StripParameters(filetype);

            switch (filetype)
            {
            case (".png"):
            case (".jpg"):
            case (".jpeg"):
            case (".gif"):
            case (".tiff"):
                responseType = "image/" + filetype.Substring(1);        // leave off the decimal point
                binary       = true;
                break;

            case (".htm"):
            case (".html"):
            case (".htmls"):
                responseType = "text/html";
                binary       = false;
                break;

            case (".js"):
                responseType = "application/javascript";
                binary       = false;
                break;

            case (".ico"):
                responseType = "image/x-icon";
                binary       = true;
                break;

            case (".xml"):
            case (".txt"):
            case (".css"):
                responseType = "text/" + filetype.Substring(1);        // leave off the decimal point
                binary       = false;
                break;

            case (".json"):
                responseType = "application/json";
                binary       = false;
                break;

            case (".cachemanifest"):
                responseType = " text/cache-manifest";
                binary       = false;
                break;

            default:
                break;
            }

            HttpListenerResponse response = context.Response;

            if (File.Exists(path))
            {
                if (binary)
                {
                    //Open image as byte stream to send to requestor
                    FileInfo     fInfo        = new FileInfo(path);
                    long         numBytes     = fInfo.Length;
                    FileStream   fStream      = new FileStream(path, FileMode.Open, FileAccess.Read);
                    BinaryReader binaryReader = new BinaryReader(fStream);
                    buffer = binaryReader.ReadBytes((int)numBytes);
                    binaryReader.Close();
                }
                else
                {
                    // read text file
                    streamReader = new StreamReader(path);
                    pageString   = streamReader.ReadToEnd();

                    if (filetype == appFileType)
                    {
                        // treat as an application filetype, to be processed by the host application
                        // cf .php, .cf, .asmx, .lua etc
                        // should return a text for the response string

                        // Deal with the message
                        if (MessageHandler != null)
                        {
                            responseString = MessageHandler(webMethod, pageString);
                        }
                        else
                        {
                            responseString = appErrorResponse;
                        }
                    }
                    else
                    {
                        responseString = pageString;
                    }
                    buffer = Encoding.UTF8.GetBytes(responseString);
                    streamReader.Close();
                }
            }

            // file doesn't exist
            // check for json, xml requests
            else if (filetype == ".json" || filetype == ".xml" || filetype == ".txt")
            {
                // Deal with the message
                if (MessageHandler != null)
                {
                    responseString = MessageHandler(webMethod, request.RawUrl);
                }
                else
                {
                    responseString = appErrorResponse;
                }
                buffer = Encoding.UTF8.GetBytes(responseString);
            }

            // check for a command
            else if ((pos = path.IndexOf("cmd=", 0)) > 0)
            {
                string command = path.Substring(pos + 4);
                RaiseCommand(command);
                responseString = "<html>OK</html>";
                buffer         = Encoding.UTF8.GetBytes(responseString);
            }
            else
            {
                responseString = "<html>Unknown file: " + request.RawUrl + "</html>";
                RaiseCommand("Unknown");
                buffer = Encoding.UTF8.GetBytes(responseString);
            }

            response.ContentType     = responseType;
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();

            listener.BeginGetContext(ProcessRequest, listener);
        }
        private async void ListenerCallback(IAsyncResult result)
        {
            HttpListenerContext context = listener.EndGetContext(result);
            Uri uri = context.Request.Url;

            Console.WriteLine($"Revived request for {uri}");

            List <DataFormat> dataValues = new List <DataFormat>();
            //get data from body
            string cleaned_data;

            if (context.Request.HasEntityBody)
            {
                string data_text = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd();
                dataValues.AddRange(RequestData.GetValues(System.Web.HttpUtility.UrlDecode(data_text)));
            }
            else
            {
                cleaned_data = string.Empty;
            }

            //get data form url
            dataValues.AddRange(RequestData.GetValues(context.Request.QueryString));
            cleaned_data = Helpers.ToJson(dataValues);

            // Get a response stream and write the response to it.
            HttpListenerResponse response = context.Response;

            response.StatusCode        = 200;
            response.StatusDescription = "OK";
            response.AddHeader("Access-Control-Allow-Origin", "*");
            response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
            response.AddHeader("Access-Control-Max-Age", "1000");
            response.AddHeader("Access-Control-Allow-Header", "Content-Type");
            response.ContentType = "application/json; charset=utf-8";
            //append the data response
            byte[] buffer;
            Stream output = new MemoryStream();

            Console.WriteLine("setup completed...");
            try
            {
                switch (uri.LocalPath.ToLower())
                {
                case "/printerlist":
                case "printerlist":
                    //get the printer list to show
                    Console.WriteLine("Get printer List...");
                    buffer = Encoding.ASCII.GetBytes(Helpers.ToJson(WindowsManagement.PopulateInstalledPrinters()));
                    response.ContentLength64 = buffer.Length;
                    output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    break;

                default:
                    Console.WriteLine("Print document...");
                    WindowsPrint winPrint = new WindowsPrint(dataValues);
                    bool         print    = await winPrint.PrintUrl();

                    if (print)
                    {
                        Console.WriteLine("printed...");
                        buffer = Encoding.ASCII.GetBytes(Helpers.ToJson(print));
                    }
                    else
                    {
                        Console.WriteLine("error on print a document...");
                        buffer = Encoding.ASCII.GetBytes(Helpers.ToJson(print, "Error on print a document"));
                    }
                    winPrint.Dispose();
                    response.ContentLength64 = buffer.Length;
                    output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    // must close the output stream.
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("we can't print, no printer defined...", ex);
                buffer = Encoding.ASCII.GetBytes(Helpers.ToJson(false, ex.Message));
                response.ContentLength64 = buffer.Length;
                output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
            }
            finally
            {
                // must close the output stream.
                output.Close();
            }
            context.Response.Close();
        }
Exemple #8
0
        private void callback(IAsyncResult result)
        {
            if (m_Listener == null)
            {
                return;             //callback sometime happens when listener is null on shutdown
            }
            if (!m_Listener.IsListening)
            {
                return;
            }

            //This is called on its own pool thread by HttpListener
            bool gateAccessDenied = false;
            HttpListenerContext listenerContext;

            try
            {
                listenerContext = m_Listener.EndGetContext(result);

                if (m_InstrumentationEnabled)
                {
                    Interlocked.Increment(ref m_stat_ServerRequest);
                }


                if (m_Gate != null)
                {
                    try
                    {
                        var action = m_Gate.CheckTraffic(new HTTPIncomingTraffic(listenerContext.Request, GateCallerRealIpAddressHeader));
                        if (action != GateAction.Allow)
                        {
                            //access denied
                            gateAccessDenied = true;
                            listenerContext.Response.StatusCode        = Web.WebConsts.STATUS_403; //todo - need properties for this
                            listenerContext.Response.StatusDescription = Web.WebConsts.STATUS_403_DESCRIPTION;
                            listenerContext.Response.Close();

                            if (m_InstrumentationEnabled)
                            {
                                Interlocked.Increment(ref m_stat_ServerGateDenial);
                            }
                            return;
                        }
                    }
                    catch (Exception denyError)
                    {
                        Log(MessageType.Error, denyError.ToMessageWithType(), "callback(deny request)", denyError);
                    }
                }
            }
            catch (Exception error)
            {
                if (error is HttpListenerException)
                {
                    if ((error as HttpListenerException).ErrorCode == 995)
                    {
                        return;                                        //Aborted
                    }
                }
                Log(MessageType.Error, error.ToMessageWithType(), "callback(endGetContext())", error);
                return;
            }
            finally
            {
                if (Running)
                {
                    var acceptCount = m_AcceptSemaphore.Release();

                    if (m_InstrumentationEnabled)
                    {
                        Thread.VolatileWrite(ref m_stat_ServerAcceptSemaphoreCount, acceptCount);
                    }

                    if (gateAccessDenied)//if access was denied then no work will be done either
                    {
                        var workCount = m_WorkSemaphore.Release();
                        if (m_InstrumentationEnabled)
                        {
                            Thread.VolatileWrite(ref m_stat_ServerWorkSemaphoreCount, workCount);
                        }
                    }
                }
            }

            //no need to call process() asynchronously because this whole method is on its own thread already
            if (Running)
            {
                var workContext = MakeContext(listenerContext);
                m_Dispatcher.Dispatch(workContext);
            }
        }
Exemple #9
0
        //public static void CmdRun(string cmd,string param)
        //{
        //    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(cmd, param);
        //    psi.UseShellExecute = true;
        //    psi.WorkingDirectory = Environment.CurrentDirectory;
        //    psi.Verb = "runas";
        //    psi.CreateNoWindow = true;
        //    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //    psi.UseShellExecute = false;
        //    System.Diagnostics.Process.Start(psi).WaitForExit();
        //}
        void GetContext(IAsyncResult ar)
        {
            HttpListener        listener = ar.AsyncState as HttpListener;
            HttpListenerContext context;

            try
            {
                context = listener.EndGetContext(ar);  //接收到的请求context(一个环境封装体)
            }
            catch
            {//listener.Stop()时不继续
                return;
            }

            listener.BeginGetContext(new AsyncCallback(GetContext), listener); //开始 第二次 异步接收request请求

            HttpListenerRequest  request  = context.Request;                   //接收的request数据
            HttpListenerResponse response = context.Response;                  //用来向客户端发送回复

            //response.ContentType = "text/html; charset=UTF-8";
            response.ContentType     = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.StatusCode      = 200;//设置返回给客服端http状态代码
            response.AppendHeader("Access-Control-Allow-Origin", "*");
            string postData = string.Empty;

            using (StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
            {
                postData = reader.ReadToEnd();
            }

            string rString = "";

            //显示
            SManager.SetText(textBoxServerRequest, string.Format("URL: {0}\r\n{1}ContentType: \r\n\r\n{2}", request.Url, request.ContentType, postData), true);

            if (ServerForceResponse)
            {
                rString = DeFaultResponseString;//(强制内容时由人工修改)窗体内容改变事件中修改的DeFaultResponseString
            }
            else
            {
                //显示
                SManager.SetText(textBoxServerResponse, "", true);

                if (ServerOnHandleRequests != null)
                {
                    rString = ServerOnHandleRequests(request, postData);
                }
                else
                {
                    rString = NotSetResponseString;  //表示未绑定处理代码
                }

                //显示
                SManager.SetText(textBoxServerResponse, rString, true);
            }


            using (Stream output = response.OutputStream)  //发送回复
            {
                byte[] buffer = Encoding.UTF8.GetBytes(rString);
                try
                {
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }
                catch { }
            }
            response.Close();
        }
Exemple #10
0
        private void RequestHandler(IAsyncResult ar)
        {
            HttpListenerContext httpContext = null;
            HttpListener        listener    = (HttpListener)ar.AsyncState;

            // try to finish getting the current context
            try {
                httpContext = listener.EndGetContext(ar);
            } catch (ObjectDisposedException) {
                _log.Debug("dropping out of request handler, since listener was disposed");
                return;
            } catch (HttpListenerException) {
                _log.Debug("EndGetContext() failed, most likely because the I/O operation was aborted by either a thread exit or an application request");
            } catch (Exception e) {
                _log.WarnExceptionFormat(e, "unable to finish acquiring the request context, unable to handle request");
            }

            // start listening for next request
            if (!listener.IsListening)
            {
                _log.Debug("dropping out of request handler, since the listener is no longer listening");
                return;
            }
            try {
                listener.BeginGetContext(RequestHandler, listener);
            } catch (Exception e) {
                _log.WarnExceptionFormat(e, "unable to re-aquire context, dropping out of request handler");
                return;
            }

            // if we didn't succeed in ending the GetContext call, drop out
            if (httpContext == null)
            {
                return;
            }
            Action <string> activity = null;
            DreamMessage    request  = null;

            try {
                // finish listening for current context
                string[] prefixes = new string[listener.Prefixes.Count];
                listener.Prefixes.CopyTo(prefixes, 0);
                XUri requestUri = HttpUtil.FromHttpContext(httpContext);
                _log.DebugMethodCall("RequestHandler", httpContext.Request.HttpMethod, requestUri);

                // create request message
                request = new DreamMessage(DreamStatus.Ok, new DreamHeaders(httpContext.Request.Headers), MimeType.New(httpContext.Request.ContentType), httpContext.Request.ContentLength64, httpContext.Request.InputStream);
                Debug.Assert(httpContext.Request.RemoteEndPoint != null, "httpContext.Request.RemoteEndPoint != null");
                DreamUtil.PrepareIncomingMessage(request, httpContext.Request.ContentEncoding, prefixes[0], httpContext.Request.RemoteEndPoint.ToString(), httpContext.Request.UserAgent);
                requestUri = requestUri.AuthorizeDreamInParams(request, _dreamInParamAuthtoken);

                // check if the request was forwarded through Apache mod_proxy
                string hostname = requestUri.GetParam(DreamInParam.HOST, null) ?? request.Headers.ForwardedHost ?? request.Headers.Host ?? requestUri.HostPort;
                activity = new ActivityState(_env, httpContext.Request.HttpMethod, httpContext.Request.Url.ToString(), hostname).Message;
                activity("RequestHandler");

                // process message
                _env.UpdateInfoMessage(_sourceExternal, null);
                string verb = httpContext.Request.HttpMethod;
                _env.SubmitRequestAsync(verb, requestUri, httpContext.User, request, new Result <DreamMessage>(TimeSpan.MaxValue))
                .WhenDone(result => Coroutine.Invoke(ResponseHandler, verb, requestUri, request, result, httpContext, activity, new Result(TimeSpan.MaxValue)));
            } catch (Exception ex) {
                _log.ErrorExceptionMethodCall(ex, "RequestHandler");
                if (request != null)
                {
                    request.Close();
                }
                try {
                    DreamMessage response = DreamMessage.InternalError(ex);
                    httpContext.Response.StatusCode = (int)response.Status;
                    Stream stream = response.ToStream();
                    httpContext.Response.Headers.Clear();
                    foreach (KeyValuePair <string, string> pair in response.Headers)
                    {
                        HttpUtil.AddHeader(httpContext.Response, pair.Key, pair.Value);
                    }
                    httpContext.Response.KeepAlive = false;
                    long size = response.ContentLength;
                    if (((size == -1) || (size > 0)) && (stream != Stream.Null))
                    {
                        CopyStream(message => { }, stream, httpContext.Response.OutputStream, size, new Result <long>(DreamHostService.MAX_REQUEST_TIME)).Block();
                    }
                    httpContext.Response.OutputStream.Flush();
                } catch {
                    httpContext.Response.StatusCode = (int)DreamStatus.InternalError;
                }
                httpContext.Response.Close();
                if (activity != null)
                {
                    activity(null);
                }
            }
        }
        /// <summary>
        /// Callback when a HTTP request comes in on the port listener and is handed off
        /// to a thread for processing.  This method
        /// </summary>
        /// <param name="result">IAsyncResult containing the HTTPListener</param>
        public void ListenerCallback(IAsyncResult result)
        {
            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = null;

            if (listener == null)
            {
                return;
            }

            try {
                // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
                // blocks until there is a request to be processed or some type of data is available.
                context = listener.EndGetContext(result);
            } catch (Exception ex) {
                // You will get an exception when httpListener.Stop() is called
                // because there will be a thread stopped waiting on the .EndGetContext()
                // method, and again, that is just the way most Begin/End asynchronous
                // methods of the .NET Framework work.
                Console.WriteLine("HttpListener Error", ex);
                return;
            } finally {
                // Once we know we have a request (or exception), we signal the other thread
                // so that it calls the BeginGetContext() (or possibly exits if we're not
                // listening any more) method to start handling the next incoming request
                // while we continue to process this request on a different thread.
                listenForNextRequest.Set();
            }

            if (context == null)
            {
                return;
            }

            Console.WriteLine("Start: {0}", DateTime.Now.ToString());


            System.Net.HttpListenerRequest request = context.Request;
            Console.WriteLine("{0}: {1}", PORT, request.RawUrl);

            if (request.HasEntityBody)
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)) {
                    string requestData = sr.ReadToEnd();
                }
            }

            // Obtain a response object
            using (System.Net.HttpListenerResponse response = context.Response) {
                /*
                 * cmpa --+
                 *  cmpg 4  000000c8 == 0000000000000001
                 *  cmnm 10 648a861f == devicename
                 *  cmty 4  648a861f == ipod
                 */

                DACPResponse dacpResponse = new PairingClientResponse();
                byte[]       output       = dacpResponse.GetBytes();

                Console.WriteLine(new UTF8Encoding(false).GetString(output));
                response.StatusCode      = (int)HttpStatusCode.OK;
                response.ContentLength64 = output.LongLength;
                response.OutputStream.Write(output, 0, output.Length);
            }

            Console.WriteLine("End: {0}", DateTime.Now.ToString());
        }
Exemple #12
0
        private void AcceptCallback(IAsyncResult result)
        {
            int     val       = (int)ErrorCodes.UnknownError;
            string  stringOut = string.Empty;
            JObject jObj;

            HttpListener listener = (HttpListener)result.AsyncState;

            Sem.Release();
            HttpListenerContext context = listener.EndGetContext(result);

            HttpListenerRequest req = context.Request;

            Console.WriteLine($"incoming connection from: {req.RemoteEndPoint.Address.ToString()}");
            if (req.ContentType.Contains(ConstVar.JsonMIME) && req.HttpMethod == "POST")
            {
                //string inData;
                StringBuilder inDataB   = new StringBuilder();
                byte[]        inputByte = new byte[10];

                using (Stream inStr = req.InputStream)
                //using (StreamReader reader = new StreamReader(inStr))
                {
                    int readEl = 0;
                    do
                    {
                        readEl = inStr.Read(inputByte, 0, 10);
                        inDataB.Append(Encoding.UTF8.GetChars(inputByte), 0, readEl);
                    }while (readEl > 0);
                    //inData = reader.ReadToEnd();
                }
                Console.WriteLine($"requested Url: {req.RawUrl}");
                jObj = JObject.Parse(inDataB.ToString());

                string reqUrl = req.RawUrl;

                double idVal = double.Parse(jObj["OrderId"].ToString());
                if (reqUrl == ConstVar.Prefixes[0])// "/PayIn/":
                {
                    double  cardNum    = double.Parse(jObj["CardNumber"].ToString());
                    decimal expDate    = decimal.Parse(jObj["ExpireDate"].ToString());
                    short   cvv        = short.Parse(jObj["CVV"].ToString());
                    string  firstName  = jObj["FirstName"].ToString();
                    string  SecondName = jObj["SecondName"].ToString();
                    long    amount     = long.Parse(jObj["Amount"].ToString());

                    val = DBClass.PayIn(idVal, cardNum, expDate, cvv, string.Join(" ", SecondName, firstName), amount);
                }
                else if (reqUrl == ConstVar.Prefixes[1])// "/Refund/":
                {
                    val = DBClass.RefundPayment(idVal);
                }
                else if (reqUrl == ConstVar.Prefixes[2])// "/GetStatus/":
                {
                    val = DBClass.GetPaymentStatus(idVal);
                }
                if (val == (int)ErrorCodes.OperationSuccess)
                {
                    stringOut = $"{{\"Status\":\"Ok\", \"Value\":{val}}}";
                }
                else
                {
                    stringOut = $"{{\"Status\":\"Error\", \"Value\":{val}}}";
                }

                HttpListenerResponse resp = context.Response;
                resp.ContentType = ConstVar.JsonMIME;
                using (Stream str = resp.OutputStream)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(stringOut);
                    str.Write(bytes, 0, bytes.Count());
                }
                //str.Close();
            }
        }
        private void GetContextCallback(IAsyncResult asyncResult)
        {
            HttpListenerContext ctx = null;

            try
            {
                try
                {
                    ctx = httpListener.EndGetContext(asyncResult);
                }
                finally
                {
                    BeginGetContext();
                }

                if (maxPacket < ctx.Request.ContentLength64)
                {
                    BoshXmppHelper.TerminateBoshSession(ctx, "request-too-large");
                    return;
                }

                if (ctx.Request.Url.AbsolutePath == bindUri.AbsolutePath)
                {
                    var body = BoshXmppHelper.ReadBodyFromRequest(ctx);
                    if (body == null)
                    {
                        BoshXmppHelper.TerminateBoshSession(ctx, "bad-request");
                        return;
                    }

                    var connection = GetXmppConnection(body.Sid) as BoshXmppConnection;

                    if (!string.IsNullOrEmpty(body.Sid) && connection == null)
                    {
                        BoshXmppHelper.TerminateBoshSession(ctx, "item-not-found");
                        return;
                    }

                    if (connection == null)
                    {
                        connection = new BoshXmppConnection(body);
                        log.DebugFormat("Create new Bosh connection Id = {0}", connection.Id);

                        AddNewXmppConnection(connection);
                    }
                    connection.ProcessBody(body, ctx);
                }
                else
                {
                    BoshXmppHelper.TerminateBoshSession(ctx, "bad-request");
                    log.DebugFormat("{0}: Unknown uri request {1}", Name, ctx.Request.Url);
                }
            }
            catch (Exception e)
            {
                BoshXmppHelper.TerminateBoshSession(ctx, "internal-server-error");
                if (Started && !(e is ObjectDisposedException))
                {
                    log.ErrorFormat("{0}: Error GetContextCallback: {1}", Name, e);
                }
            }
        }
Exemple #14
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                var context = listener.EndGetContext(result);

                var request  = context.Request;
                var response = context.Response;

                var wrd = string.Empty;

                using (var sr = new StreamReader(request.InputStream))
                    wrd = sr.ReadToEnd();


                var gcm = JsonConvert.DeserializeObject <GcmRequest>(wrd);

                var transportResponse = new GcmMessageTransportResponse();

                foreach (var id in gcm.RegistrationIds)
                {
                    GcmMessageResult singleResult  = null;
                    bool             matchedFilter = false;

                    foreach (var filter in this.MessageResponseFilters)
                    {
                        if (filter.IsMatch(gcm, id))
                        {
                            singleResult           = filter.Status;
                            singleResult.MessageId = "1:" + msgId++;
                            transportResponse.Results.Add(singleResult);
                            matchedFilter = true;
                            break;
                        }
                    }

                    if (!matchedFilter)
                    {
                        singleResult = new GcmMessageResult();
                        singleResult.ResponseStatus = GcmMessageTransportResponseStatus.Ok;
                        singleResult.MessageId      = "1:" + msgId++;
                        transportResponse.Results.Add(singleResult);
                    }

                    if (singleResult.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                    {
                        transportResponse.NumberOfSuccesses++;
                    }
                    else
                    {
                        transportResponse.NumberOfFailures++;
                    }

                    transportResponse.NumberOfCanonicalIds++;
                }

                transportResponse.ResponseCode = GcmMessageTransportResponseCode.Ok;


                foreach (var filter in TransportResponseFilters)
                {
                    if (filter.IsMatch(gcm))
                    {
                        transportResponse.ResponseCode = filter.Code;
                        break;
                    }
                }


                switch (transportResponse.ResponseCode)
                {
                case GcmMessageTransportResponseCode.Ok:
                    response.StatusCode = (int)HttpStatusCode.OK;
                    break;

                case GcmMessageTransportResponseCode.InvalidAuthToken:
                    response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    break;

                case GcmMessageTransportResponseCode.ServiceUnavailable:
                    response.Headers.Add("Retry-After", "120");
                    response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
                    break;

                case GcmMessageTransportResponseCode.InternalServiceError:
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;

                case GcmMessageTransportResponseCode.BadRequest:
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
                    break;

                default:
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
                }

                var responseString = JsonConvert.SerializeObject(transportResponse);

                //Console.WriteLine(responseString);

                var buffer = Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();

                notificationReceived(transportResponse);
            }
            catch (Exception)
            {
            }

            if (listener.IsListening && !cancelServer.IsCancellationRequested)
            {
                listener.BeginGetContext(ProcessRequest, listener);
            }
        }
Exemple #15
0
        private void EndGetContext(IAsyncResult ar)
        {
            try
            {
                var ctx = _server.EndGetContext(ar);
                _server.BeginGetContext(EndGetContext, null);

                lock (workerLock)
                {
                    if (ctx.Request.HttpMethod == "GET" && ctx.Request.RawUrl == "/connectivity/")
                    {
                        ctx.Response.StatusCode = _pHost.Database.IsOpen ? 200 : 401;
                        ctx.Response.OutputStream.Close();
                        return;
                    }

                    if (ctx.Request.HttpMethod != "POST")
                    {
                        ctx.Response.StatusCode = 405;
                        ctx.Response.OutputStream.Close();
                        return;
                    }

                    if (ctx.Request.RawUrl != "/")
                    {
                        ctx.Response.StatusCode = 400;
                        ctx.Response.OutputStream.Close();
                        return;
                    }

                    EncryptedMessage encReqData = null;
                    RequestData      reqData    = null;
                    try
                    {
                        var rawData = new StreamReader(ctx.Request.InputStream).ReadToEnd();
                        Debug.WriteLine($"Received: {rawData}");
                        encReqData = JsonConvert.DeserializeObject <EncryptedMessage>(rawData);
                    }
                    catch (Exception)
                    {
                        ctx.Response.StatusCode = 400;
                        ctx.Response.OutputStream.Close();
                        return;
                    }

                    if (encReqData == null || string.IsNullOrEmpty(encReqData.IV) || string.IsNullOrEmpty(encReqData.Message))
                    {
                        ctx.Response.StatusCode = 400;
                        ctx.Response.OutputStream.Close();
                        return;
                    }

                    reqData = CryptoHelper.DecryptMessage(encReqData, _plugin.CryptoKey);

                    if (reqData == null || string.IsNullOrEmpty(reqData.Url))
                    {
                        ctx.Response.StatusCode = 400;
                        ctx.Response.OutputStream.Close();
                        return;
                    }

                    var responseData = FindCredentials(reqData.Url);

                    var encResponseData = CryptoHelper.EncryptMessage(responseData, _plugin.CryptoKey);

                    var response = JsonConvert.SerializeObject(encResponseData);
                    var writer   = new StreamWriter(ctx.Response.OutputStream);
                    writer.Write(response);
                    Debug.WriteLine($"Returned: {response}");

                    ctx.Response.StatusCode = 200;
                    writer.Close();
                    writer.Dispose();
                }
            }
            catch (HttpListenerException)
            {
                //system is terminating, so... that's right as it is ;)
            }
        }
        private void ListenerCallBack(IAsyncResult result)
        {
            if (_listener == null)
            {
                return;
            }

            try
            {
                var listenerContext = _listener.EndGetContext(result);

                var request  = listenerContext.Request;
                var response = listenerContext.Response;

                var query       = HttpUtility.ParseQueryString(request.Url.Query);
                var sessionId   = query?["sid"];
                var contextName = query?["ctx"] ?? "session";

                if (string.IsNullOrEmpty(sessionId) ||
                    string.IsNullOrEmpty(contextName) ||
                    listenerContext.Request.Url.AbsolutePath != "/diag" ||
                    request.HttpMethod != "POST")
                {
                    var droppedResponse = Encoding.UTF8.GetBytes("DROPPED");
                    listenerContext.Response.StatusCode      = 200;
                    listenerContext.Response.KeepAlive       = false;
                    listenerContext.Response.ContentLength64 = droppedResponse.Length;
                    listenerContext.Response.OutputStream.Write(droppedResponse, 0, droppedResponse.Length);
                    listenerContext.Response.Close();
                    return;
                }

                var now = DateTime.Now;

                if (!_sessionList.TryGetValue(sessionId, out var session))
                {
                    var folder = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "incoming-sessions", now.ToString("yyyy-MM-dd - HH-mm-ss", CultureInfo.InvariantCulture) + " - " + sessionId);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    File.WriteAllLines(Path.Combine(folder, "session-info.txt"), new[]
                    {
                        "id\t" + sessionId,
                        "started-on\t" + now.ToString("yyyy.MM.dd HH:mm:ss.fff", CultureInfo.InvariantCulture),
                    });

                    session = new DiagSession(sessionId, folder, now);
                    lock (_sessionList)
                    {
                        _sessionList.Add(sessionId, session);
                        _newSessions.Add(session);
                    }
                }

                if (!session.ContextListByName.TryGetValue(contextName, out var context))
                {
                    var folder = Path.Combine(session.DataFolder, contextName.Replace("/", "-", StringComparison.InvariantCultureIgnoreCase));
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    File.WriteAllLines(Path.Combine(folder, "context-info.txt"), new[]
                    {
                        "name\t" + contextName,
                        "started-on\t" + now.ToString("yyyy.MM.dd HH:mm:ss.fff", CultureInfo.InvariantCulture),
                    });

                    context = new DiagContext(session, contextName, now, folder);

                    lock (_sessionList)
                    {
                        session.ContextList.Add(context);
                        session.ContextListByName.Add(contextName, context);

                        _newDiagContexts.Add(context);
                    }
                }

                using (var tempMemoryStream = new MemoryStream())
                {
                    listenerContext.Request.InputStream.CopyTo(tempMemoryStream);
                    tempMemoryStream.Position = 0;

                    context.Stage(tempMemoryStream);
                }

                var acceptedResponse = Encoding.UTF8.GetBytes("ACK");
                listenerContext.Response.StatusCode      = 200;
                listenerContext.Response.KeepAlive       = false;
                listenerContext.Response.ContentLength64 = acceptedResponse.Length;

                listenerContext.Response.OutputStream.Write(acceptedResponse, 0, acceptedResponse.Length);
                listenerContext.Response.Close();
            }
            catch (Exception)
            {
            }
            finally
            {
                _listener.BeginGetContext(ListenerCallBack, null);
            }
        }
Exemple #17
0
        private void ListenerCallback(IAsyncResult result)
        {
            HttpListenerContext context = proc.EndGetContext(result);
            string RequestFile          = context.Request.Url.AbsolutePath;
            string RequestParam         = "";

            if (context.Request.Url.Query.Length > 0)
            {
                RequestParam = context.Request.Url.Query.Substring(1);
            }

            if (nonWindows)
            {
                if (!File.Exists("Caches/" + RequestFile) || (RequestFile.Contains("start.php")) || (RequestFile.Contains("sync.php")) || RequestFile.Contains("info.php") || RequestFile.Contains("briefing.php"))
                {
                    try
                    {
                        GatherFile(RequestFile, RequestParam, context.Request);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                }
            }
            else
            {
                if (!File.Exists("Caches\\" + RequestFile) || (RequestFile.Contains("start.php")) || (RequestFile.Contains("sync.php")) || RequestFile.Contains("info.php") || RequestFile.Contains("briefing.php"))
                {
                    try
                    {
                        GatherFile(RequestFile, RequestParam, context.Request);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                }
            }

            byte[] Response = File.ReadAllBytes(CacheFolder + RequestFile);

            Console.WriteLine("Sending:" + RequestFile);
            try
            {
                context.Response.OutputStream.Flush();
                context.Response.OutputStream.Write(Response, 0, Response.Length);
            }
            catch
            {
                Console.WriteLine("Connection to client dropped when sending.");
                context.Response.Close();
                return;
            }
            context.Response.Close();

            //Console.WriteLine(RequestFile + " " + RequestParam);
            return;
        }
        void ListenerCallback(IAsyncResult result)
        {
            XmlDocument         doc     = new XmlDocument();
            HttpListenerContext context = null;

            try
            {
                //Get listener instance from async result
                HttpListener listener = (HttpListener)result.AsyncState;
                if (!listener.IsListening)
                {
                    return;
                }

                context = listener.EndGetContext(result);
                log.Info("Response received");

                string responseString;
                using (StreamReader reader = new StreamReader(context.Request.InputStream))
                {
                    responseString = reader.ReadToEnd();
                }

                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    doc.LoadXml(responseString);
                    ProcessResponse(doc, doc.DocumentElement.Name);
                    context.Response.StatusCode = 200;
                }
                catch (WebException ex)
                {
                    var response = ex.Response as HttpWebResponse;

                    if (response.StatusCode == HttpStatusCode.GatewayTimeout || response.StatusCode == HttpStatusCode.BadGateway || response.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        context.Response.StatusCode = (int)response.StatusCode;
                    }
                    else //any other case, it is ok
                    {
                        context.Response.StatusCode = 200;
                    }

                    log.Error("Error processing response", ex);
                }

                catch (Exception ex)
                {
                    log.Error("Error processing response", ex);
                }

                using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
                {
                    writer.WriteLine("Response received succesfully");
                }
                context.Response.Close();
            }
            catch (Exception ex)
            {
                log.Error("Writing of response to xml failed", ex);
            }
            finally
            {
                if (_httpListener != null && _httpListener.IsListening)
                {
                    _httpListener.BeginGetContext(ListenerCallback, _httpListener);
                }
            }
            log.Info("Response processing ended");
        }
Exemple #19
0
        private void ListenerCallback(IAsyncResult result)
        {
            HttpListener listener = result.AsyncState as HttpListener;

            if (listener.IsListening)
            {
                HttpListenerContext context = null;
                try
                {
                    context = listener.EndGetContext(result);
                }
                catch (HttpListenerException hle)
                {
                    Console.WriteLine(hle.Message);
                    return;
                }



                HttpListenerRequest request = context.Request;

                string responseString = "";
                device dev            = devices[request.Url.Port];

                var body = new StreamReader(request.InputStream).ReadToEnd();

                Console.WriteLine("BODY\r\n{0}", body);
                Console.WriteLine("RAW URL:  {0}", request.RawUrl);
                switch (request.RawUrl)
                {
                case "/":


                    Console.WriteLine(request.RawUrl);
                    Console.WriteLine("unknown request on port:  " + request.Url.Port.ToString());

                    break;

                case "/upnp/control/basicevent1":
                    Debug.WriteLine("***ECHO COMMAND on port:  " + request.Url.Port.ToString());

                    Console.WriteLine("BODY {0}", body);
                    if (body.Contains("SetBinaryState"))
                    {
                        if (body.Contains("<BinaryState>1</BinaryState>"))
                        {
                            intLastStateRequest = 1;
                            Debug.Write(dev.name + ":  ON...");
                            if (boolBalloonNotification)
                            {
                                notifyIcon1.ShowBalloonTip(3000, dev.name, "Turning " + dev.name + " ON", ToolTipIcon.Info);
                            }

                            logData(DateTime.Now.ToString(), dev.name, "ON");

                            Task.Run(() => {
                                PerformAction(dev.action_on);
                            });
                        }
                        else if (body.Contains("<BinaryState>0</BinaryState>"))
                        {
                            intLastStateRequest = 0;
                            Debug.Write(dev.name + ":  OFF...");
                            if (boolBalloonNotification)
                            {
                                notifyIcon1.ShowBalloonTip(3000, dev.name, "Turning " + dev.name + " OFF", ToolTipIcon.Info);
                            }

                            logData(DateTime.Now.ToString(), dev.name, "OFF");

                            Task.Run(() =>
                            {
                                PerformAction(dev.action_off);
                            });
                        }
                    }

                    if (body.Contains("GetBinaryState"))
                    {
                        Console.WriteLine("Request for binary state of device:  " + dev.name);

                        string deviceState = "";

                        int intDeviceState = intLastStateRequest;      //for devices that toggle, just send whatever the last requested state

                        // get the URL from the table... query for state.... reply
                        if (!string.IsNullOrEmpty(dev.state_url))
                        {
                            deviceState    = PerformAction(dev.state_url);  //main thread?
                            intDeviceState = ((deviceState.ToLower().Contains("on") || deviceState.ToLower().Contains("open")) ? 1 : 0);
                        }
                        responseString = $@"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" s:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><s:Body>
<u:GetBinaryStateResponse xmlns:u=""urn:Belkin:service:basicevent:1"">
<BinaryState>{intDeviceState.ToString()}</BinaryState>
</u:GetBinaryStateResponse>
</s:Body> </s:Envelope>
";
                    }

                    break;

                default:
                    break;
                }


                HttpListenerResponse response = context.Response;
                Console.WriteLine("headers:  {0}", request.Headers.ToString());
                if (responseString.Contains("BinaryState"))
                {
                    Console.WriteLine("Sending as text/xml");
                    response.ContentType     = "text/xml";
                    response.ContentEncoding = Encoding.UTF8;
                    //response.Headers.Remove("Date");

                    //response.Headers.Add("Server", "");
                    //response.Headers.Add("Date", "");
                    //response.KeepAlive = false;
                    // SOAPACTION: "urn:Belkin:service:basicevent:1#GetBinaryState"
                }
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                //System.IO.Stream output = response.OutputStream;


                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.Close(buffer, true);

                //response.OutputStream.Write(buffer, 0, buffer.Length);
                //response.OutputStream.Flush();
                //response.OutputStream.Close();


                Console.WriteLine("Sending response:\r\n{0}", responseString);
                Console.WriteLine(new string('*', 30));

                if (!done)
                {
                    receive(ref listener);
                }
            }
            else
            {
                Console.WriteLine("listener isn't listening??");
            }
        }
Exemple #20
0
        private void GotContext(IAsyncResult result)
        {
            try
            {
                HttpListenerContext c = listener.EndGetContext(result);
                Console.WriteLine("Got Context");
                requestedUrl.Add(c.Request.Url.OriginalString);
                Match  match = null;
                string range = c.Request.Headers["range"];

                if (!(range != null && (match = rangeMatcher.Match(range)).Success))
                {
                    Assert.Fail("No valid range specified");
                }

                int start = int.Parse(match.Groups[1].Captures[0].Value);
                int end   = int.Parse(match.Groups[2].Captures[0].Value);


                long   globalStart = 0;
                bool   exists      = false;
                string p;
                if (rig.Manager.Torrent.Files.Length > 1)
                {
                    p = c.Request.RawUrl.Substring(10 + rig.Torrent.Name.Length + 1);
                }
                else
                {
                    p = c.Request.RawUrl.Substring(10);
                }
                foreach (TorrentFile file in rig.Manager.Torrent.Files)
                {
                    if (file.Path.Replace('\\', '/') != p)
                    {
                        globalStart += file.Length;
                        continue;
                    }
                    globalStart += start;
                    exists       = start < file.Length && end < file.Length;
                    break;
                }

                TorrentFile[] files = rig.Manager.Torrent.Files;
                if (files.Length == 1 && rig.Torrent.GetRightHttpSeeds[0] == c.Request.Url.OriginalString)
                {
                    globalStart = 0;
                    exists      = start < files[0].Length && end < files[0].Length;
                }

                if (!exists)
                {
                    c.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
                    c.Response.Close();
                }
                else
                {
                    byte[] data = partialData ? new byte[(end - start) / 2] : new byte[end - start + 1];
                    for (int i = 0; i < data.Length; i++)
                    {
                        data[i] = (byte)(globalStart + i);
                    }

                    c.Response.Close(data, false);
                }

                listener.BeginGetContext(GotContext, null);
            }
            catch
            {
            }
        }
Exemple #21
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                try
                {
                    Console.WriteLine(context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3)
                    {
                        Console.WriteLine(@"Invalid request");
                        ErrorResponse(context, @"Invalid request parameter");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    var filename = HttpUtility.UrlDecode(stringarr[3]);//获取文件名称
                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = EditSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        editSession = new FileSession(filename, m_filePath + "/" + filename, @"地信云科", @"地信云科", @"*****@*****.**", false);

                        EditSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))//如 /wopi/files/1.dicx
                    {
                        //request of checkfileinfo, will be called first
                        var memoryStream = new MemoryStream();
                        var json         = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                        json.WriteObject(memoryStream, editSession.GetCheckFileInfo());
                        memoryStream.Flush();
                        memoryStream.Position = 0;
                        StreamReader streamReader = new StreamReader(memoryStream);
                        var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                        context.Response.ContentType     = @"application/json";
                        context.Response.ContentLength64 = jsonResponse.Length;
                        context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                        context.Response.Close();
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))//如 /wopi/files/1.dicx/contents
                    {
                        // get and put file's content
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                            context.Response.StatusCode = (int)HttpStatusCode.OK;
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        //lock,
                        Console.WriteLine("request lock: " + context.Request.Headers["X-WOPI-Override"]);
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine(@"Invalid request parameters");
                        ErrorResponse(context, @"Invalid request cobalt parameter");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"process request exception:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"get request context:" + ex.Message);
                return;
            }
        }
        private async Task <bool> CanConnectUsingOpenId(Connection connection)
        {
            try
            {
                using (var source = new CancellationTokenSource())
                {
                    var discoveryUrl = new Uri(new Uri(connection.Uri), "/" + OpenIdProviderMetadataNames.Discovery);
                    var config       = await OpenIdConnectConfigurationRetriever.GetAsync(discoveryUrl.ToString(), source.Token);

                    var result = false;
                    var closed = false;

                    var authEndpoint = config.AuthorizationEndpoint +
                                       "?scope=email%20profile" +
                                       "&response_type=code" +
                                       "&redirect_uri=http://localhost:" + connection.RedirectPort +
                                       "&client_id=" + WebUtility.UrlEncode(connection.ClientId);

                    await Runtime.InvokeAsync(() =>
                    {
                        var window = new NavigationWindow()
                        {
                            WindowStartupLocation = WindowStartupLocation.CenterOwner,
                            Owner             = Application.Current?.MainWindow,
                            Title             = "Authenticate",
                            ShowsNavigationUI = false,
                            Source            = new Uri(authEndpoint),
                            Width             = 500,
                            Height            = 400
                        };

                        var listener = new HttpListener();
                        listener.Prefixes.Add($"http://*:{ connection.RedirectPort }/");
                        listener.Start();

                        listener.BeginGetContext(x =>
                        {
                            if (!listener.IsListening || closed)
                            {
                                return;
                            }

                            var context = listener.EndGetContext(x);
                            var code    = context.Request.QueryString["code"];

                            Runtime.Invoke(() =>
                            {
                                result = !string.IsNullOrWhiteSpace(code);
                                window.Close();
                            });
                        }, null);

                        window.Closed += (s, e) =>
                        {
                            closed = true;
                            listener.Stop();
                        };

                        window.ShowDialog();
                    });

                    _log.DebugFormat("OpenID connection test {0}", result ? "passed" : "failed");
                    return(await Task.FromResult(result));
                }
            }
            catch (Exception ex)
            {
                _log.Error("OpenID connection test failed", ex);
                return(await Task.FromResult(false));
            }
        }
Exemple #23
0
        /// <summary>
        /// 网页服务器相应处理
        /// </summary>
        /// <param name="ar"></param>
        private void onWebResponse(IAsyncResult ar)
        {
            try
            {
                byte[] responseByte = null;    //响应数据

                HttpListener        httpListener = ar.AsyncState as HttpListener;
                HttpListenerContext context      = httpListener.EndGetContext(ar);            //接收到的请求context(一个环境封装体)

                httpListener.BeginGetContext(new AsyncCallback(onWebResponse), httpListener); //开始 第二次 异步接收request请求

                HttpListenerRequest  request  = context.Request;                              //接收的request数据
                HttpListenerResponse response = context.Response;                             //用来向客户端发送回复

                var path = request.Url.AbsolutePath;

                var file = "";

                if (path == "" || path == "/")
                {
                    file = Path.Combine(WebRoot, "index.html");
                }
                else
                {
                    if (path.StartsWith("/"))
                    {
                        path = path.Substring(1);
                    }

                    var paths = path.Split('/');

                    path = Path.Combine(paths);

                    if (paths.Last().IndexOf('.') == -1)
                    {
                        file = Path.Combine(WebRoot, path, "index.html");
                    }
                    else
                    {
                        file = Path.Combine(WebRoot, path);
                    }
                }

                //处理请求文件名的后缀
                string fileExt = Path.GetExtension(file);

                if (!File.Exists(file))
                {
                    responseByte        = Encoding.UTF8.GetBytes("404 Not Found!");
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                }
                else
                {
                    responseByte        = File.ReadAllBytes(file);
                    response.StatusCode = (int)HttpStatusCode.OK;
                }

                if (mimeType.ContainsKey(fileExt))
                {
                    response.ContentType = mimeType[fileExt];
                }
                else
                {
                    response.ContentType = mimeType["*"];
                }

                response.Cookies = request.Cookies; //处理Cookies

                response.ContentEncoding = Encoding.UTF8;

                using (Stream output = response.OutputStream)  //发送回复
                {
                    output.Write(responseByte, 0, responseByte.Length);
                }
            }
            catch { }
        }
        private void ListenerCallback(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;

            if (listener == null || !listener.IsListening)
            {
                return;
            }


            // Call EndGetContext to complete the asynchronous operation.
            HttpListenerContext context;

            try
            {
                context = listener.EndGetContext(result);
            }
            catch (Exception)
            {
                return;
            }

            HttpListenerRequest request = context.Request;

            bool authenticated;

            if (AuthEnabled)
            {
                try
                {
                    HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
                    authenticated = (identity.Name == UserName) & (ComputeSHA256(identity.Password) == Password);
                }
                catch
                {
                    authenticated = false;
                }
            }
            else
            {
                authenticated = true;
            }

            if (authenticated)
            {
                switch (request.HttpMethod)
                {
                case "POST":
                {
                    string postResult = HandlePostRequest(request);

                    Stream output   = context.Response.OutputStream;
                    byte[] utfBytes = Encoding.UTF8.GetBytes(postResult);

                    context.Response.AddHeader("Cache-Control", "no-cache");
                    context.Response.ContentLength64 = utfBytes.Length;
                    context.Response.ContentType     = "application/json";

                    output.Write(utfBytes, 0, utfBytes.Length);
                    output.Close();

                    break;
                }

                case "GET":
                {
                    string requestedFile = request.RawUrl.Substring(1);

                    if (requestedFile == "data.json")
                    {
                        SendJson(context.Response, request);
                        return;
                    }

                    if (requestedFile.Contains("images_icon"))
                    {
                        ServeResourceImage(context.Response,
                                           requestedFile.Replace("images_icon/", string.Empty));

                        return;
                    }

                    // default file to be served
                    if (string.IsNullOrEmpty(requestedFile))
                    {
                        requestedFile = "index.html";
                    }

                    string[] splits = requestedFile.Split('.');
                    string   ext    = splits[splits.Length - 1];
                    ServeResourceFile(context.Response, "Web." + requestedFile.Replace('/', '.'), ext);

                    break;
                }

                default:
                {
                    context.Response.StatusCode = 404;
                    break;
                }
                }
            }
            else
            {
                context.Response.StatusCode = 401;
            }

            if (context.Response.StatusCode == 401)
            {
                const string responseString = @"<HTML><HEAD><TITLE>401 Unauthorized</TITLE></HEAD>
  <BODY><H4>401 Unauthorized</H4>
  Authorization required.</BODY></HTML> ";

                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                context.Response.ContentLength64 = buffer.Length;
                context.Response.StatusCode      = 401;
                Stream output = context.Response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }

            try
            {
                context.Response.Close();
            }
            catch
            {
                // client closed connection before the content was sent
            }
        }
Exemple #25
0
        //private void IncomingHttpRequest(HttpListenerContext context)
        private void ListenerCallback(IAsyncResult result)
        {
            try
            {
                //HttpListenerResponse response = context.Response;
                HttpListener listener = (HttpListener)result.AsyncState;
                if (!m_HttpListener.IsListening)
                {
                    Console.WriteLine("HttpListener is closed. Stop process request.");
                    return;
                }

                // Call EndGetContext to complete the asynchronous operation.
                HttpListenerContext context = listener.EndGetContext(result);
                HttpListenerRequest request = context.Request;
                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                var receive_data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd();

                //Upload log(csv file)
                if (context.Request.Url.AbsolutePath.Contains(Url_File_UploadLog_Token))
                {
                    string        szFileName = string.Empty;
                    List <string> szList     = new List <string>(context.Request.Url.AbsolutePath.Split('/'));
                    //foreach (string subValue in szList)
                    //{
                    //if (subValue.Contains(".csv"))
                    if ((szList.Count >= 6 && szList[5].Contains(".csv")) ||
                        (szList.Count >= 7 && szList[6].Contains(".csv")))         //Add for WISE-4210 with additional MAC address in URL
                    {
                        string szModuleId = szList[2];
                        szFileName = context.Request.Url.AbsolutePath.Replace(Slash_Str_Token, BackSlash_Str_Token);
                        szFileName = szFileName.Substring(BackSlash_Str_Token.Length, (szFileName.Length - BackSlash_Str_Token.Length));
                        Object lockObj = getLockObject(szModuleId);
                        //lock is based on module id
                        lock (lockObj)
                        {
                            szFileName = getUniqueFileName(szFileName);
                            FileInfo file = new FileInfo(szFileName);
                            file.Directory.Create();
                            System.IO.File.WriteAllText(file.FullName, receive_data);
                        }
                        //break;
                    }
                    //}
                }

                /*
                 * //Un-comment this block to write Push log(json file)
                 * var dateString = DateTime.Now.Year.ToString("D4") + DateTime.Now.Month.ToString("D2") + DateTime.Now.Day.ToString("D2");
                 * var dateTimeString = dateString + DateTime.Now.Hour.ToString("D2") + DateTime.Now.Minute.ToString("D2") + DateTime.Now.Second.ToString("D2");
                 * if (context.Request.Url.AbsolutePath.Contains(Url_Json_IoLog_Token))
                 * {
                 *  string szFileName = string.Empty;
                 *  szFileName = Url_Json_IoLog_Token + "\\" + dateString + "\\" + dateTimeString + ".log";
                 *  lock (lockObject)
                 *  {
                 *      FileInfo file = new FileInfo(szFileName);
                 *      file.Directory.Create();
                 *      System.IO.File.WriteAllText(file.FullName, receive_data);
                 *  }
                 * }
                 * else if (context.Request.Url.AbsolutePath.Contains(Url_Json_SysLog_Token))
                 * {
                 *  string szFileName = string.Empty;
                 *  szFileName = Url_Json_SysLog_Token + "\\" + dateString + "\\" + dateTimeString + ".log";
                 *  lock (lockObject)
                 *  {
                 *      FileInfo file = new FileInfo(szFileName);
                 *      file.Directory.Create();
                 *      System.IO.File.WriteAllText(file.FullName, receive_data);
                 *  }
                 * }
                 */
                DataGridViewRow  dgvRow;
                DataGridViewCell dgvCell;
                dgvRow = new DataGridViewRow();

                dgvCell = new DataGridViewTextBoxCell(); //Column Time
                var dataTimeInfo = DateTime.Now.Year.ToString("D4") + "/" +
                                   DateTime.Now.Month.ToString("D2") + "/" +
                                   DateTime.Now.Day.ToString("D2") + " " +
                                   DateTime.Now.Hour.ToString("D2") + ":" +
                                   DateTime.Now.Minute.ToString("D2") + ":" +
                                   DateTime.Now.Second.ToString("D2");
                dgvCell.Value = dataTimeInfo;
                dgvRow.Cells.Add(dgvCell);

                dgvCell       = new DataGridViewTextBoxCell(); //RemoteEndPoint
                dgvCell.Value = context.Request.RemoteEndPoint.ToString();
                dgvRow.Cells.Add(dgvCell);

                dgvCell       = new DataGridViewTextBoxCell(); //Url Scheme
                dgvCell.Value = context.Request.Url.Scheme.ToString();
                dgvRow.Cells.Add(dgvCell);

                dgvCell       = new DataGridViewTextBoxCell(); //HTTP Method
                dgvCell.Value = context.Request.HttpMethod;
                dgvRow.Cells.Add(dgvCell);

                dgvCell = new DataGridViewTextBoxCell(); //Data Format
                if (context.Request.Url.AbsolutePath.Contains(Url_File_UploadLog_Token))
                {
                    dgvCell.Value = DataType_Csv_File;
                }
                else
                {
                    dgvCell.Value = DataType_Json_Str;
                }
                dgvRow.Cells.Add(dgvCell);

                dgvCell       = new DataGridViewTextBoxCell(); //Request URL
                dgvCell.Value = context.Request.Url.ToString();
                dgvRow.Cells.Add(dgvCell);

                dgvRow.Tag = receive_data;

                m_DataGridViewCtrlAddDataRow(dgvRow);

                response.StatusCode        = 200;
                response.StatusDescription = "OK";
                response.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.ToString());
            }
        }
Exemple #26
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                Console.WriteLine("开始监听中...");
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                try
                {
                    //Console.WriteLine("1111...");
                    Console.WriteLine(context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        Console.WriteLine(@"无效的请求");
                        ErrorResponse(context, @"无效的请求参数");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    //todo:

                    documentUtil = new DocumentUtil();
                    //string fileId = stringarr[3];
                    var docInfo  = documentUtil.GetInfo(stringarr[3]);
                    var filename = docInfo.fileName;
                    //Stream gridfsStream = GetFileById(fileId);
                    //StreamToFile(gridfsStream, filename);


                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = CobaltSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        //Console.WriteLine("2222...");
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Contains("xlsx"))
                        {
                            editSession = new FileSession(filename, docInfo.filePath, docInfo.author, docInfo.author, docInfo.mail, false);
                        }
                        else
                        {
                            editSession = new CobaltSession(filename, docInfo.filePath, docInfo.author, docInfo.author, docInfo.mail, false);
                        }
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        //Console.WriteLine("4444...");
                        //request of checkfileinfo, will be called first
                        var memoryStream = new MemoryStream();
                        var json         = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                        json.WriteObject(memoryStream, editSession.GetCheckFileInfo());
                        memoryStream.Flush();
                        memoryStream.Position = 0;
                        StreamReader streamReader = new StreamReader(memoryStream);
                        var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                        context.Response.ContentType     = @"application/json";
                        context.Response.ContentLength64 = jsonResponse.Length;
                        context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        //Console.WriteLine("5555...");
                        // get and put file's content, only for xlsx and pptx
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        //Console.WriteLine("6666...");
                        //cobalt, for docx and pptx
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                        RequestBatch      requestBatch = new RequestBatch();

                        Object          ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) &&
                                request.PartitionId == FilePartitionId.Content)
                            {
                                editSession.Save();
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType     = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        //Console.WriteLine("7777...");
                        //lock, for xlsx and pptx
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine(@"无效的请求参数.");
                        ErrorResponse(context, @"无效的Word请求参数.");
                    }

                    Console.WriteLine("请求成功.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"异常请求处理:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"获取请求上下文异常:" + ex.Message);
                return;
            }
        }
        static void GetContextCallback(IAsyncResult ar)
        {
            /*
             * if(shouldInitPorts && !initPortsDone){
             *  initPorts();
             *  print("Com Ports init..");
             *  printLocalHostAndPortData();
             *  initPortsDone = true;
             * }*/


            try
            {
                /*if (!shouldInitPorts){
                 *  shouldInitPorts = true;
                 *  return;
                 * }*/
                int req = ++RequestNumber;

                // Get the context
                var context = Listener.EndGetContext(ar);

                // listen for the next request
                Listener.BeginGetContext(GetContextCallback, null);

                // get the request
                var NowTime = DateTime.UtcNow;

                var responseString = string.Format(ctrl_data[X_DAT] + "," +
                                                   ctrl_data[Y_DAT] + "," +
                                                   ctrl_data[Z_DAT] + "," +
                                                   ctrl_data[U_DAT] + "," +
                                                   ctrl_data[V_DAT] + "," +
                                                   ctrl_data[W_DAT] + "," +
                                                   ctrl_data[LP_DAT] + "," +
                                                   ctrl_data[RP_DAT] + "," +
                                                   ctrl_data[POS_CTRL_SENSITIVITY] + "," +
                                                   ctrl_data[PRES_CTRL_SENSITIVITY]
                                                   );

                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                // and send it
                var response = context.Response;
                response.ContentType     = "text/html";
                response.ContentLength64 = buffer.Length;
                response.StatusCode      = 200;
                response.Headers.Remove("Access-Control-Allow-Origin");
                response.AddHeader("Access-Control-Allow-Origin", "*" /*, Listener.GetContext().Request.UrlReferrer.GetLeftPart(UriPartial.Authority)*/);

                //response.Headers.Remove("Access-Control-Allow-Credentials");
                //response.AddHeader("Access-Control-Allow-Credentials", "true");

                //response.Headers.Remove("Access-Control-Allow-Methods");
                //response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                response.OutputStream.Write(buffer, 0, buffer.Length);
                response.OutputStream.Close();
            }
            catch (Exception ex)
            {
                print(ex.Message);
            }
        }
Exemple #28
0
        private void GetContextCallback(IAsyncResult asyncResult)
        {
            HttpListenerContext ctx = null;

            try
            {
                try
                {
                    ctx = httpListener.EndGetContext(asyncResult);
                }
                finally
                {
                    BeginGetContext();
                }

                var url = ctx.Request.Url;
                log.DebugFormat("{0}: Begin process http request {1}", Name, url);

                if (url.AbsolutePath == bindUri.AbsolutePath)
                {
                    var body = BoshXmppHelper.ReadBodyFromRequest(ctx);
                    if (body == null)
                    {
                        BoshXmppHelper.TerminateBoshSession(ctx, "bad-request");
                        return;
                    }

                    var connection = GetXmppConnection(body.Sid) as BoshXmppConnection;

                    if (!string.IsNullOrEmpty(body.Sid) && connection == null)
                    {
                        BoshXmppHelper.TerminateBoshSession(ctx, "item-not-found");
                        return;
                    }

                    if (connection == null)
                    {
                        connection = new BoshXmppConnection();
                        AddNewXmppConnection(connection);
                    }

                    connection.ProcessBody(body, ctx);
                }
                else if (url.AbsolutePath == domainUri.AbsolutePath && ctx.Request.HttpMethod == "GET")
                {
                    SendPolicy(ctx);
                }
                else
                {
                    BoshXmppHelper.TerminateBoshSession(ctx, "bad-request");
                }
            }
            catch (ObjectDisposedException) { }
            catch (Exception e)
            {
                if (ctx != null)
                {
                    BoshXmppHelper.TerminateBoshSession(ctx, "internal-server-error");
                }
                if (Started)
                {
                    log.ErrorFormat("{0}: Error GetContextCallback: {1}", Name, e);
                }
            }
        }
Exemple #29
0
        private void Handle(IAsyncResult result)
        {
            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = listener.EndGetContext(result);


            HttpListenerRequest request = context.Request;
            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            // Construct a response.
            string responseString = "<HTML><BODY><PRE>";

            /*
             * responseString += "Active Connections: ";
             * int connectedUsers = 0;
             * foreach(var client in ResourcesManager.GetConnectedClients())
             * {
             *  var socket = client.Socket;
             *  if(socket != null)
             *  {
             *      try
             *      {
             *          bool part1 = socket.Poll(1000, SelectMode.SelectRead);
             *          bool part2 = (socket.Available == 0);
             *          if (!(part1 && part2))
             *              connectedUsers++;
             *      }
             *      catch(Exception){}
             *  }
             * }
             * responseString += connectedUsers + "\n";
             */
            responseString += "Established Connections: " + ResourcesManager.GetConnectedClients().Count + "\n";

            responseString += "<details><summary>";
            responseString += "In Memory Levels: " + ResourcesManager.GetInMemoryLevels().Count + "</summary>";
            foreach (var account in ResourcesManager.GetInMemoryLevels())
            {
                responseString += "    " + account.GetPlayerAvatar().GetId() + ", " + account.GetPlayerAvatar().GetAvatarName() + " \n";
            }
            responseString += "</details>";

            responseString += "<details><summary>";
            responseString += "Online Players: " + ResourcesManager.GetOnlinePlayers().Count + "</summary>";
            foreach (var account in ResourcesManager.GetOnlinePlayers())
            {
                responseString += "    " + account.GetPlayerAvatar().GetId() + ", " + account.GetPlayerAvatar().GetAvatarName() + " \n";
            }
            responseString += "</details>";

            responseString += "<details><summary>";
            responseString += "In Memory Alliances: " + ObjectManager.GetInMemoryAlliances().Count + "</summary>";
            foreach (var alliance in ObjectManager.GetInMemoryAlliances())
            {
                responseString += "    " + alliance.GetAllianceId() + ", " + alliance.GetAllianceName() + " \n";
            }
            responseString += "</details>";

            string hostName = Dns.GetHostName();
            string LIP      = Dns.GetHostByName(hostName).AddressList[0].ToString();

            responseString += "<center><p>Current local ip: " + LIP + "</p></center>";
            responseString += "<center><img src='https://d14.usercdn.com/i/02212/ea18nj5uxcll.png' style='width: 25%; height: 50%'></img></center></PRE></BODY></HTML>";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
        }
Exemple #30
0
        static void Main(string[] args)
        {
            db = new SQLiteConnection(ServerSettings.Default.ConnectionString);
            db.Open();

            CreateTables();

            bool running = true;
            Console.CancelKeyPress += (s, e) =>
            {
                running = false;
                e.Cancel = true;
            };

            Console.WriteLine("Press Ctrl+C to quit.");

            using (var http = new HttpListener())
            {
                http.Prefixes.Add(ServerSettings.Default.Prefix);
                http.Start();

                while (running)
                {
                    HttpListenerContext context = null;
                    try
                    {
                        var result = http.BeginGetContext(null, null);
                        while (!result.IsCompleted)
                        {
                            if (running == false)
                                goto quit;
                            Thread.Sleep(0);
                        }
                        context = http.EndGetContext(result);
                        switch (context.Request.HttpMethod)
                        {
                            case "POST":
                                DispatchPost(context);
                                break;
                            default:
                                DispatchGet(context);
                                break;
                        }

                    }
                    catch (Exception ex)
                    {
                        using (var sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
                        {
                            sw.Write(ex.ToString());
                        }
                        context.Response.StatusCode = 500;
                    }
                    finally
                    {
                        if (context != null)
                            context.Response.Close();
                    }
                }
            quit:
                db.Close();
            }
        }
        private void OnContext(IAsyncResult ar)
        {
            var context = _httpListener.EndGetContext(ar);

            _httpListener.BeginGetContext(OnContext, null);
            var request = context.Request;

            var list = context.Request.Url.LocalPath.Split("/").Where(s => !string.IsNullOrEmpty(s))
                       .Take(2)
                       .ToList();

            var readingResource = request.HttpMethod == "GET";

            if (list.Count == 2)
            {
                if (!readingResource)
                {
                    var resource = list[0] + "/" + list[1];
                    RemoveCacheByPattern("*" + resource + "*");
                    Console.WriteLine("Invalidating cache for " + resource + " because of method : " + request.HttpMethod);
                }
            }

            var redisKey = context.Request.Url.PathAndQuery;

            if (readingResource &&
                _connectionMultiplexer.GetDatabase(0).KeyExists(redisKey))
            {
                Console.WriteLine("Returning cached request.");
                var content        = _connectionMultiplexer.GetDatabase(0).StringGet(redisKey);
                var cachedResponse = JsonConvert.DeserializeObject <CachedResponse>(content);

                CopyHelper.CopyHeaders(CopyHelper.ToNameValueCollection(cachedResponse.Headers), context.Response.Headers);
                CopyHelper.CopyResponse(context.Response, cachedResponse.Body, cachedResponse.Body.Length);
            }
            else
            {
                var uri = GetRedirectUri(request);

                Console.WriteLine($"Received a request. Redirecting to {uri}");
                var webRequest = WebRequest.Create(uri);
                CopyHelper.CopyRequestDetails(webRequest, request);
                CopyHelper.CopyHeaders(request.Headers, webRequest.Headers);
                CopyHelper.CopyInputStream(webRequest, request);

                var webResponse = webRequest.GetResponse();


                byte[] buffer = new byte[CopyHelper.BufferSize];
                var    read   = webResponse.GetResponseStream().Read(buffer, 0, buffer.Length);

                CopyHelper.CopyHeaders(webResponse.Headers, context.Response.Headers);
                CopyHelper.CopyResponse(context.Response, buffer, read);

                if (readingResource)
                {
                    var serializeObject = JsonConvert.SerializeObject(new CachedResponse
                    {
                        Body    = buffer.Take(read).ToArray(),
                        Headers = CopyHelper.ToDictionary(webResponse.Headers)
                    });
                    _connectionMultiplexer.GetDatabase(0).StringSet(redisKey, serializeObject);
                }
            }
        }