public static void executeController(ref ServerConfig Servconf, ref RykonProcess cp, ref bool valid_CSRF_tok, ref bool isValidsession, IntPtr handle , FormMain frm ) { if (cp.LocalPath.EndsWith("/Control/thumb.png")) { cp.Requesting_Binary_data = true; cp.OutPutData = AppHelper.ReadFileBts(cp.RequestPage); return; } else if (!Servconf.EnableControler) // disabled { cp.Output_document = WebDesigner.BuiltInDisabled("controller"); cp.LoadMaster = true; } else // working { cp.LoadMaster = true; valid_CSRF_tok = cp.UrlOriginalString.Contains(Servconf.CSRF) || cp.POSTParEqual("CSRF", Servconf.CSRF); isValidsession = cp.Reqcuest_cookie_equal(WebServer.Control_auth_token_name, Servconf.controlsession); /* ||cp.UrlOriginalString.Contains(Servconf.ControlPassword) */ if (Servconf.SecureControl) cp.AllowedTocontrol = isValidsession; else cp.AllowedTocontrol = true; string[] pcs = new string[] { }; if (cp.LocalPath.EndsWith("Control/logout")) { cp.SetResponseCooke(WebServer.Control_auth_token_name , WebServer.CookieDeletedvalue); cp.Output_document = "Logged out"; return; } else if (!cp.LocalPath.StartsWith("/Control/exec")) { cp.RedirectTo("http://" + cp.Url.Authority + "/Control/exec.rk"); return; } else if (!cp.AllowedTocontrol) // login page { bool validformcsrf = cp.POSTParEqual("CSRF", Servconf.CSRF); bool validformpassword = cp.POSTParEqual("pass", Servconf.ControlPassword); if (validformcsrf && validformpassword) { cp.RedirectTo(cp.Url.ToString()); } else { //ControlLoginPage; cp.Output_document = (!valid_CSRF_tok && isValidsession && cp.UrlOriginalString.Contains("CSRF")) ? WebDesigner.invalidAuthTok(cp.Requesting_Host, Servconf) : WebDesigner.ControlNotAllowedIndex(Servconf.CSRF); cp.OutPutData = Encoding.UTF8.GetBytes(cp.Output_document); cp.Output_code = 405; cp.Processing_Type = ProcessingResult.unAuthorized; return; } } else if (cp.UrlOriginalString.Contains("exec") && cp.UrlOriginalString.Contains("com=") && valid_CSRF_tok)//&& !cp.UrlOriginalString.EndsWith(this.AuthToke)) { // sending commands //"http://192.168.1.100:9090/Control/exec?jex&com=msgbx&title=hello+It" if (cp.UrlOriginalString.Contains("?")) pcs = cp.UrlOriginalString.Split('?'); else if (cp.UrlOriginalString.Contains("/")) pcs = cp.UrlOriginalString.Split('/'); } if (pcs.Length > 0) // receive comands { // "http://192.168.1.100:9090/Control/exec jex&com=msgbx&title=hello+It" string main = pcs[pcs.Length - 1]; if (main.StartsWith(Servconf.CSRF)) main = main.Substring(Servconf.CSRF.Length); RemoteCommandExecuter r = new RemoteCommandExecuter(main); r.HandlePointer = handle; r.proceeed(); if (r.RequireUnpreved) { if (frm != null) { if (r.hideOrShowclient()) { frm.Visible = r.formvisible; frm.notifyIcon1.Visible = r.ComType == RemoteCommandType.ShowClient; r.Result = "Form = " + (frm.Visible ? "visible" : "hidden"); r.Result += WebServer.NewLineReplacor; r.Result += "icon = " + (frm.notifyIcon1.Visible ? "visible" : "hidden"); } } } if (r.HasBinaryResult) { cp.OutPutData = r.bytes; cp.Processing_Type = ProcessingResult.Binary; cp.Requesting_Binary_data = true; cp.Request_extn = r.extn; } else cp.Output_document = (r.Result); } else if (cp.AllowedTocontrol)// List Command index { cp.Output_document = AppHelper.ReadFileText(Servconf.RootDirectory + "/Control/index.html"); cp.OutPutData = Encoding.UTF8.GetBytes(cp.Output_document); } if (Servconf.SecureControl) cp.SetResponseHeader("Set-Cookie", WebServer.Control_auth_token_name + "=" + Servconf.controlsession); } }
private async Task StartServer() { ServerMode = _Mode_.on; ViewLog("Staring server ..."); SetStatue("Staring server ..."); string TrimmedPrefex = this._Prefixs_[(cb_Prefixs.SelectedIndex)].Item2; string SelectedPrefix = txbx_serverUrl.Text = "http://" + TrimmedPrefex + ":" + NumPort.Value.ToString() + "/"; string mp = Servconf.GetMainApp(); this.textBoxUrlMainAPP.Text = SelectedPrefix+mp+"/"; gpxmainapp.Text = mp; labelmainapp.Text = mp + " url"; generatedefaultindex(); GenerateListenPlayer(); GenerateMediaPlayer(); GenerateControlIndex(); ChangeControlerS(); _MainServer_ = new HttpListener(); _MainServer_.Prefixes.Add(SelectedPrefix); _MainServer_.Prefixes.Add("http://*:" + NumPort.Value.ToString() + "/"); _MainServer_.Start(); Servconf.currentHost = TrimmedPrefex; string xt = "Running on " + this._Port; Ballooon(xt); ViewLog(xt); if (this._StreamerEnabled) ViewLog("Stream on " + textBoxUrlMainAPP.Text); if (this.Servconf.EnableControler) ViewLog("Control from " + SelectedPrefix + "Control/"); if (this.Servconf.EnableVideo) ViewLog("Video from " + SelectedPrefix + "Video/"); if (this.Servconf.EnableListen) ViewLog("Listen from " + SelectedPrefix + "Listen/"); if (this.Servconf.EnableUpload) ViewLog("Upload on " + SelectedPrefix + "Upload/"); SetStatue(xt); notifyIcon1.Text = "Rykon Online "; while (_Listening_) { try { if (_MainServer_.IsListening == false) break; var ctx = await _MainServer_.GetContextAsync(); string ad = ((!this._RootDirectory.EndsWith("\\") ? "\\" : "")); RykonProcess cp = new RykonProcess(ctx.Request.Url); cp.SaveRequestHeaders(ctx.Request.Headers); cp.UrlOriginalString = ctx.Request.Url.OriginalString; cp.SETLocalPath ( ctx.Request.Url.LocalPath); cp.RequestBuiltInTool = cp.IsREquestingTool(cp.LocalPath); cp.RequestPage = (this._RootDirectory + /*ad+*/ cp.LocalPath.Replace("/", "\\")).Replace("\\\\", "\\"); cp.Request_extn = AppHelper.LastPeice(cp.RequestPage, "."); cp.Request_extn = AppHelper.removeSlashes(cp.Request_extn); cp.Requestor_Host = AppHelper.FirstPieceof(ctx.Request.RemoteEndPoint.Address.ToString(), ':'); cp.Requesting_Host = ctx.Request.Url.Host; cp.CanConnect = (this.Servconf.IsPublicServer); cp.RequestorAddress = ctx.Request.UserHostAddress; cp.Url = ctx.Request.Url; if (cp.RequestPage.EndsWith("\\/")) cp.RequestPage = cp.RequestPage.Substring(0, cp.RequestPage.Length - 1); cp.RequestPage = WebServer.DecodeUrlChars(cp.RequestPage); bool validauthtok = false; bool IsValidSession = false; cp.LoadMaster = cp.RequestBuiltInTool; cp.Method=ctx.Request.HttpMethod ; // receiving data // cp.SaveRequestHeaders(ctx.Request.Headers); if (ctx.Request.HttpMethod == "POST") { if (ctx.Request.HasEntityBody) { using (System.IO.Stream body = ctx.Request.InputStream) // here we have data { using (System.IO.StreamReader reader = new System.IO.StreamReader(body, ctx.Request.ContentEncoding)) { cp.ParsePostData( reader.ReadToEnd()); } } } } //foreach(var p in ctx.Request.Headers) try { cp.CanConnect = true; if (!this.Servconf.IsPublicServer) cp. CanConnect = WebServer.CheckBasicAuth(ctx.Request.Headers["Authorization"], Servconf.ServerAuthId, Servconf.ServerAutPass); if (!cp.CanConnect) // ask credit { cp.Output_document = WebDesigner.IndexofNeedAuthentication; cp.Output_code = 401; cp.OutPutData = ASCIIEncoding.UTF8.GetBytes(cp.Output_document); ctx.Response.AddHeader("WWW-Authenticate", "Basic realm=Rykon Server : "); cp.Processing_Type = ProcessingResult.AuthRequired; } else if (cp.LocalPath.StartsWith("/Control")) { BuiltInApps. executeController(ref Servconf,ref cp, ref validauthtok, ref IsValidSession, this.Handle, this); } //else if (cp.LocalPath.StartsWith("/Upload/")) //{ // BuiltInApps.executeUploader(ctx,cp,Servconf); //} else if (cp.LocalPath.StartsWith("/Stream/index.html") || cp.LocalPath.StartsWith("/Stream/LiveStream.jpg")) { if (!Servconf.EnableStream ) { cp.Output_document = WebDesigner.BuiltInDisabled("Stream"); cp.LoadMaster = true; } else { bool allowtostream = true; if (Servconf.SecureStream) { allowtostream = cp.Reqcuest_cookie_equal(WebServer.stream_Auth_Tokenname, Servconf.streamSession); } if (cp.Method == "POST") { cp.validCSRF = cp.UrlOriginalString.Contains(Servconf.CSRF) || cp.POSTParEqual("CSRF", Servconf.CSRF); bool validformpassword = cp.POSTParEqual("pass", Servconf.StreamPassword); if (validformpassword) { cp.SetResponseCooke(WebServer.stream_Auth_Tokenname, Servconf.streamSession); cp.RedirectTo("index.html"); } else { cp.Output_document = WebDesigner.StreamLoginPage(Servconf.CSRF); cp.LoadMaster = true; } } else if (!allowtostream && (cp.LocalPath.EndsWith("Stream/") || cp.LocalPath.EndsWith("LiveStream.jpg") || cp.LocalPath.EndsWith("index.html"))) { cp.Output_document = WebDesigner.StreamLoginPage(Servconf.CSRF); } else { var page = _RootDirectory + cp.LocalPath; bool fileExist; lock (_mrlocker_) fileExist = File.Exists(page); if (fileExist) { if (!page.EndsWith("jpg")) { cp.Output_document = AppHelper.ReadFileText(page);; } else { cp.LoadMaster = false; _rwlck_.AcquireReaderLock(Timeout.Infinite); cp.OutPutData = File.ReadAllBytes(page); // cp.OutPutData = _imgstr_.ToArray(); _rwlck_.ReleaseReaderLock(); ctx.Response.ContentType = "text/jpg"; // Important For Chrome Otherwise will display the HTML as plain text. cp.Requesting_Binary_data = true; cp.Processing_Type = ProcessingResult.Binary; } } } } } else if (AppHelper.IsFileExist(cp.RequestPage)) //dynamic static page or bin { cp.RequestPage = AppHelper.Correctpath(cp.RequestPage); if (_MainCompiler_.IsCompilable(cp.RequestPage)) //dynamic page { { cp.Output_document = _MainCompiler_.CompileThis(cp.RequestPage, cp.Url.Query.ToString(), cp.RequestPostData); cp.SetData_ReadTextFile(cp.Output_document); } else { long filesize = AppHelper.FileSize(cp.RequestPage); if (this.Servconf.MaxFileSize < filesize) cp.Die(200, "File is too big"); else if (WebServer.IsBinFile(cp.RequestPage)) // binary { cp.Output_document = (cp.RequestPage); cp.Requesting_Binary_data = true; cp.SetData_ReadBinFile(cp.RequestPage); cp.ContentType = "content/" + cp.Request_extn; cp.Processing_Type = ProcessingResult.Binary; } else // static page { cp.Output_document = WebDesigner.ReadFile(cp.RequestPage); cp.SetData_ReadTextFile(cp.Output_document); cp.ContentType = "text/" + cp.Request_extn; } } } else if (ctx.Request.Url.LocalPath.EndsWith("/") || AppHelper.ExistedDir(cp.RequestPage)) //default index or browse Dir { string outed = ""; if (_MainCompiler_.IsFoundDefaultIndex(cp.RequestPage, out outed)) cp.Output_document = _MainCompiler_.CompileThis((outed == "") ? cp.RequestPage : outed, cp.Url.Query.ToString(), cp.RequestPostData); else if (WebServer.IsDirectoryFound(cp.RequestPage)) { cp.Output_document = WebDesigner.ListDirectory(cp.RequestPage, WebServer.ListDir(cp.RequestPage, this._RootDirectory, cp.Requesting_Host, this._Port.ToString()), Servconf); cp.LoadMaster = true; } else { cp.Output_document = WebDesigner.FileNotFoundTitle_Traditional(cp.Requesting_Host, this._Port.ToString()); cp.Output_code = 404; cp.Processing_Type = ProcessingResult.NotFound; } } else // not found { cp.Output_document = WebDesigner.FileNotFoundTitle_Traditional(cp.Requesting_Host, this._Port.ToString()); cp.Output_code = 404; cp.Processing_Type = ProcessingResult.NotFound; cp.LoadMaster = true; cp.NextTitle = ""; } ctx.Response.StatusCode = cp.Output_code; ctx.Response.ContentType = cp.ContentType; ctx.Response.Headers["server"] = cp.ResponseServerHeader; ctx.Response.Headers["X-Frame-Options"] = "SAMEORIGIN"; ctx.Response.Headers["X-Powered-By"] = "C#-4Neso-Ryon"; foreach (var p in cp.Response_Headers) ctx.Response.Headers.Add(p.id, p.value); if(cp.ContentType.Contains("html")) cp.Output_document = cp.Output_document.Replace(WebServer.NewLineReplacor, "<br />"); if (cp.Requesting_Binary_data && !cp.Dead) { ctx.Response.Headers.Add("Accept-Ranges", "bytes"); ctx.Response.Headers.Add("Last-Modified", ""); ctx.Response.Headers.Add("Server", "Rykon"); ctx.Response.Headers.Add("Date", System.DateTime.Now.ToShortDateString()); ctx.Response.Headers.Add("Content-Type", "image/" + cp.Request_extn); await ctx.Response.OutputStream.WriteAsync(cp.OutPutData, 0, cp.OutPutData.Length); } else { if (cp.LoadMaster) { cp.NextTitle=WebServer.EncodeHtmlChars(cp.NextTitle); cp.Output_document = (WebServer.masterPagePre_(Program._AppverName, cp.NextTitle) + cp.Output_document + WebServer.masterPageAfter); } await ctx.Response.OutputStream.WriteAsync(ASCIIEncoding.UTF8.GetBytes(cp.Output_document), 0, cp.Output_document.Length); } ctx.Response.Close(); if (cp.Processing_Type == ProcessingResult.AuthRequired) continue; } //catch //{ // cp.Output_document = WebDesigner._501InternalServerError(cp.Requesting_Host, this._Port.ToString(), this.ServerConfiguration); // cp.Output_code = 501; //} catch (OutOfMemoryException h) { cp.ErrorMessage = h.Message; cp.exception = ExceptionType.OutOfMemory_; } catch (HttpListenerException h) { cp.ErrorMessage = h.Message; cp.exception = ExceptionType.HttpListner_; if (h.Message.Contains("The specified network name is no longer ava")) cp.ErrorMessage = "Dropped Request"; } if (cp.exception != ExceptionType.none_) { cp.ServerErroroccured = true; cp.Output_code = 501; ctx.Response.StatusCode = cp.Output_code; switch (cp.exception) { case ExceptionType.OutOfMemory_: { cp.Output_document = WebServer.GetInternalErrorException(cp.exception); break; } case ExceptionType.HttpListner_: { if (cp.ErrorMessage == "The I/O operation has been aborted because of either a thread exit or an application request" || cp.ErrorMessage== "The specified network name is no longer available") { this._CanceledReqs++; cp.exception = ExceptionType.CanceledByRequestor; cp.Output_document = "Request Canceled by client"; cp.Canceled = true; } break; } } try // Informing client with server error { await ctx.Response.OutputStream.WriteAsync(ASCIIEncoding.UTF8.GetBytes(cp.Output_document), 0, cp.Output_document.Length); } catch (Exception h) { cp.ErrorMessage = h.Message; cp.exception = ExceptionType.FailedToHandle;} } // ctx.Response.OutputStream.Close(); ctx.Response.Close(); if (!cp.Canceled) _handled++; ViewLog(" ["+cp.Requesting_Host+"] ["+cp.Url.LocalPath+WebServer.DecodeUrlChars(cp.Url.Query)+ "] [" + WebDesigner.StatueCode(cp.Output_code)+((cp.ServerErroroccured)?("("+cp.ErrorMessage+")"):"")+"] ["+cp.getLenght()+"]"); ShowCounters(); } catch (Exception sas) { ViewLog(sas.Message); } } if (!_Listening_) stopserver(); }