private async void btnSwitch_Click(object sender, EventArgs e) { Servconf.RegenerateAuthCode(); btnSwitch.Enabled = false; btnSwitch.Enabled = false; if (ServerMode == _Mode_.on)//stop { this._Listening_ = false; this._isTakingScreenshots = false; ServerMode = _Mode_.off; stopserver(); } else if (ServerMode == _Mode_.off)//pressed start { try { ViewLog("initiating , Please Wait..."); _MainServer_.IgnoreWriteExceptions = true; _isTakingScreenshots = true; _Listening_ = true; await AddFirewallRule((int)NumPort.Value); if (_StreamerEnabled) Task.Factory.StartNew(() => CaptureScreenEvery(this.ScreenTicks)).Wait(); await StartServer(); } catch (ArgumentException ae) { ServerMode = _Mode_.off; string p = ("Starting Server exception " + ae.Message); ViewLog(p); } catch (HttpListenerException ae) { ServerMode = _Mode_.off; string msg = ""; if (ae.Message.Contains("The process cannot access the file because it is being used by another process")) { msg = "Port in use "; SetStatue("Can not listen on Port (" + NumPort.Value.ToString() + ") because it is in use "); if (MessageBox.Show("port is in use , Do you want to try another one?", "Error used port", MessageBoxButtons.YesNo) == DialogResult.Yes) { Random r = new Random(23232); NumPort.Value = (decimal)r.Next(1000, 64000); btnSwitch_Click(null, null); return; } else msg = ae.Message; string p = ("Starting Server exception " + msg); ViewLog(p); } } catch (ObjectDisposedException disObj) { _MainServer_ = new HttpListener(); _MainServer_.IgnoreWriteExceptions = true; } catch (Exception ae) { ServerMode = _Mode_.off; string p = ("Starting Server Error" + ae.Message); // SetError(p); ViewLog(p); } } ChangeControlerS(); }
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")) { if (cp.LocalPath.EndsWith("/Control/thumb.png")) { cp.Requesting_Binary_data = true; cp.OutPutData = AppHelper.ReadFileBts(cp.RequestPage); }else 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/")) { var page = _RootDirectory + cp.LocalPath; bool fileExist; lock (_mrlocker_) fileExist = File.Exists(page); if (fileExist) { _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 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); 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; } 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) { 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.Output_document=(WebServer.masterPagePre_(Program._AppverName,cp.lastdirName)+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 (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(); }