Writes a IResponse object into a stream.
Important! ResponseWriter do not throw any exceptions. Instead it just logs them and let them die peacefully. This is since the response writer is used from catch blocks here and there.
/// <summary> /// Returns pure string content. /// </summary> /// <param name="context"></param> /// <param name="action"></param> /// <returns></returns> private ProcessingResult ProcessStringContent(RequestContext context, IActionResult action) { var content = (StringContent) action; context.Response.ContentLength.Value = context.Response.Encoding.GetByteCount(content.Body); if (content.ContentType != null) context.Response.ContentType.Value = content.ContentType; var writer = new ResponseWriter(); writer.SendHeaders(context.HttpContext, context.Response); writer.Send(context.HttpContext, content.Body, context.Response.Encoding); context.HttpContext.Stream.Flush(); return ProcessingResult.Abort; }
/// <summary> /// Process a request. /// </summary> /// <param name="context">Request information</param> /// <returns>What to do next.</returns> public ProcessingResult Process(RequestContext context) { // should add information about the file here. // Lets send the header. ResponseWriter generator = new ResponseWriter(); generator.SendHeaders(context.HttpContext, context.Response); // loop through file contents. BinaryWriter writer = new BinaryWriter(context.HttpContext.Stream); // Abort is needed since we've used the network // stream directly. Else the framework will try to use the // response object + network stream to send another response. return ProcessingResult.Abort; }
public ProcessingResult Process(RequestContext requestcontext) { IRequest request = requestcontext.Request; IResponse response = requestcontext.Response; IHttpContext context = requestcontext.HttpContext; if (SessionManager.Current.SessionId == null) { SessionManager.Create(); SessionManager.Current.SessionId = Guid.NewGuid().ToString().Replace("-", String.Empty); } if (request.Method == Method.Post && request.Parameters.Count == 3) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> AJAX request from {1} {2} {3} {4}", DateTime.Now.ToString("hh:mm"), context.RemoteEndPoint, request.HttpVersion, request.Method, request.Uri.AbsoluteUri); Console.WriteLine("({0}) <Web Interface> AJAX parameters width={1}&height={2}&rooturl={3}", DateTime.Now.ToString("hh:mm"), request.Parameters.Get("width").Value, request.Parameters.Get("height").Value, request.Parameters.Get("rooturl").Value); Console.WriteLine("({0}) <Web Interface> AJAX session id {1}", DateTime.Now.ToString("hh:mm"), SessionManager.Current.SessionId); response.ContentType = new ContentTypeHeader("application/json"); response.Status = HttpStatusCode.OK; var stream = new MemoryStream(ASCIIEncoding.Default.GetBytes("{\"session\":\"" + SessionManager.Current.SessionId + "\",\"data\":\"Connected to server-side. Welcome to WCell.Terminal\"}")); response.ContentLength.Value = stream.Length; var generator = new ResponseWriter(); generator.SendHeaders(context, response); generator.SendBody(context, stream); Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "{\"session\":\"" + SessionManager.Current.SessionId + "\",\"data\":\"Connected to server-side. Welcome to WCell.Terminal\"}"); return ProcessingResult.Abort; } else { if (context.IsSecure) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Secure HTTP request from {1} {2} {3} {4}", DateTime.Now.ToString("hh:mm"), context.RemoteEndPoint, request.HttpVersion, request.Method, request.Uri.AbsoluteUri); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> HTTP request from {1} {2} {3} {4}", DateTime.Now.ToString("hh:mm"), context.RemoteEndPoint, request.HttpVersion, request.Method, request.Uri.AbsoluteUri); } } return ProcessingResult.Continue; }
private ProcessingResult ProcessStream(RequestContext context, IActionResult action) { StreamResult result = (StreamResult) action; if (context.Response.ContentType.Value == "text/html") context.Response.ContentType.Value = "application/octet-stream"; context.Response.ContentLength.Value = result.Stream.Length; ResponseWriter writer = new ResponseWriter(); writer.SendHeaders(context.HttpContext, context.Response); byte[] buffer = new byte[8196]; int bytesRead = result.Stream.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { context.HttpContext.Stream.Write(buffer, 0, bytesRead); bytesRead = result.Stream.Read(buffer, 0, buffer.Length); } return ProcessingResult.Abort; }
private void listener_RequestReceived(object sender, RequestEventArgs e) { e.IsHandled = true; e.Response.Reason = string.Empty; string userAgent = string.Empty; IHeader uahead = e.Request.Headers.Where(h => string.Equals("User-Agent", h.Name, StringComparison.OrdinalIgnoreCase)). FirstOrDefault(); if (null != uahead) userAgent = uahead.HeaderValue; //Send to the correct handler if (userAgent.StartsWith("FAP")) { if (OnRequest(RequestType.FAP, e)) return; } if (OnRequest(RequestType.HTTP, e)) return; e.Response.Reason = "Handler error"; e.Response.Status = HttpStatusCode.InternalServerError; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); }
private bool HandleCompare(RequestEventArgs e, NetworkRequest req) { var verb = new CompareVerb(model); NetworkRequest result = verb.ProcessRequest(req); byte[] data = Encoding.UTF8.GetBytes(result.Data); var generator = new ResponseWriter(); e.Response.ContentLength.Value = data.Length; generator.SendHeaders(e.Context, e.Response); e.Context.Stream.Write(data, 0, data.Length); e.Context.Stream.Flush(); data = null; return true; }
private bool HandleInfo(RequestEventArgs e) { e.Response.Status = HttpStatusCode.OK; var verb = new InfoVerb(); verb.Node = model.LocalNode; NetworkRequest result = verb.CreateRequest(); byte[] data = Encoding.UTF8.GetBytes(result.Data); var generator = new ResponseWriter(); e.Response.ContentLength.Value = data.Length; generator.SendHeaders(e.Context, e.Response); e.Context.Stream.Write(data, 0, data.Length); e.Context.Stream.Flush(); return true; }
private void SendError(RequestEventArgs e) { e.Response.Status = HttpStatusCode.MethodNotAllowed; e.Response.ContentLength.Value = 0; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); }
private bool HandleSearch(RequestEventArgs e, NetworkRequest req) { //We dont do this on a server.. var verb = new SearchVerb(shareInfoService); NetworkRequest result = verb.ProcessRequest(req); byte[] data = Encoding.UTF8.GetBytes(result.Data); var generator = new ResponseWriter(); e.Response.ContentLength.Value = data.Length; generator.SendHeaders(e.Context, e.Response); e.Context.Stream.Write(data, 0, data.Length); e.Context.Stream.Flush(); data = null; return true; }
/// <exception cref="Exception">Throwing exception if in debug mode and not exception handler have been specified.</exception> private void OnRequest(object sender, RequestEventArgs e) { var context = (HttpContext) sender; HttpFactory.Current = Factory; HttpContext.Current = context; try { var args = new RequestEventArgs(context, e.Request, e.Response); RequestReceived(this, args); if (!args.IsHandled) { // need to respond to the context. var generator = new ResponseWriter(); generator.Send(context, args.Response); } // Disconnect when done. if (e.Response.HttpVersion == "HTTP/1.0" || e.Response.Connection.Type == ConnectionType.Close) context.Disconnect(); } catch (Exception err) { if (err is HttpException) { var exception = (HttpException) err; ErrorPage(e.Request, e.Response, exception); } else { _logger.Debug("Request failed.", err); #if DEBUG if (ExceptionThrown.GetInvocationList().Length == 1) throw; #endif ExceptionThrown(this, new ExceptionEventArgs(err)); SendInternalServerError(context, err); } } }
private void SendInternalServerError(HttpContext context, Exception exception) { var generator = new ResponseWriter(); var response = HttpFactory.Current.Get<IResponse>(); byte[] body = Encoding.ASCII.GetBytes("Internal server error " + exception); response.Body.Write(body, 0, body.Length); response.Status = HttpStatusCode.InternalServerError; response.Reason = exception.Message; generator.Send(context, response); }
private bool SendFile(RequestEventArgs e, string path, string url) { try { string fileExtension = Path.GetExtension(path); if (fileExtension != null && fileExtension.StartsWith(".")) fileExtension = fileExtension.Substring(1); ContentTypeHeader header; if (!contentTypes.TryGetValue(fileExtension, out header)) header = contentTypes["default"]; e.Response.ContentType = header; DateTime modified = File.GetLastWriteTime(path).ToUniversalTime(); // Only send file if it has not been modified. var browserCacheDate = e.Request.Headers["If-Modified-Since"] as DateHeader; if (browserCacheDate != null) { DateTime since = browserCacheDate.Value.ToUniversalTime(); // Allow for file systems with subsecond time stamps modified = new DateTime(modified.Year, modified.Month, modified.Day, modified.Hour, modified.Minute, modified.Second, modified.Kind); if (since >= modified) { e.Response.Status = HttpStatusCode.NotModified; var generator = new ResponseWriter(); e.Response.ContentLength.Value = 0; generator.SendHeaders(e.Context, e.Response); return true; } } using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { e.Response.Add(new DateHeader("Last-Modified", modified)); // Send response and tell server to do nothing more with the request. SendFile(e.Context, fs, url); return true; } } catch { return false; } }
public void DoUpload(IHttpContext context, Stream stream, string user, string url) { length = stream.Length; ResumePoint = 0; IHeader rangeHeader = context.Request.Headers.Where(n => n.Name.ToLowerInvariant() == "range").FirstOrDefault(); ServerUploadToken token = null; try { if (stream.Length > Model.FREE_FILE_LIMIT) { //File isnt free leech, acquire a token before we send the file token = uploadLimiter.RequestUploadToken(context.RemoteEndPoint.Address.ToString()); while (token.GlobalQueuePosition > 0) { context.LastAction = DateTime.Now; status = string.Format("HTTP ({0}) queued upload in slot {1}", user, token.GlobalQueuePosition); token.WaitTimeout(); } } status = string.Format("HTTP ({0}) Sending {1}", user, url); try { if (null != rangeHeader) { //Partial request //Try to parse header - if we fail just send a 200 ok from zero long start = 0; long end = 0; if (rangeHeader.HeaderValue.StartsWith("bytes=")) { string header = rangeHeader.HeaderValue.Substring(6).Trim(); string starttxt = string.Empty; string endtxt = string.Empty; if (header.Contains('-')) { starttxt = header.Substring(0, header.IndexOf("-")); endtxt = header.Substring(header.IndexOf("-") + 1, header.Length - (header.IndexOf("-") + 1)); } else { starttxt = header; } if (!string.IsNullOrEmpty(starttxt)) start = long.Parse(starttxt); if (!string.IsNullOrEmpty(endtxt)) end = long.Parse(endtxt); //Only allow a partial request start. May implement this at some point but its beyond the scope of this atm. if (start != 0 && end == 0) { if (start > stream.Length) start = stream.Length; stream.Seek(start, SeekOrigin.Begin); position = start; ResumePoint = start; } context.Response.Status = HttpStatusCode.PartialContent; } } } catch { } TransferStart = DateTime.Now; //Send headers context.Response.ContentLength.Value = stream.Length - stream.Position; var generator = new ResponseWriter(); generator.SendHeaders(context, context.Response); //Send data MemoryBuffer buffer = bufferService.GetBuffer(); try { int bytesRead = stream.Read(buffer.Data, 0, buffer.Data.Length); while (bytesRead > 0) { context.LastAction = DateTime.Now; context.Stream.Write(buffer.Data, 0, bytesRead); position += bytesRead; nsm.PutData(bytesRead); bytesRead = stream.Read(buffer.Data, 0, buffer.Data.Length); } } catch (Exception err) { LogManager.GetLogger("faplog").Trace("Failed to send body through context stream.", err); } finally { bufferService.FreeBuffer(buffer); } } finally { status = string.Format("HTTP ({0}) Upload complete", user); if (null != token) uploadLimiter.FreeToken(token); isComplete = true; position = length; } }
/// <exception cref="Exception">Throwing exception if in debug mode and not exception handler have been specified.</exception> private void OnRequest(object sender, RequestEventArgs e) { var context = (HttpContext) sender; HttpFactory.Current = Factory; HttpContext.Current = context; try { var args = new RequestEventArgs(context, e.Request, e.Response); RequestReceived(this, args); if (!args.IsHandled) { // need to respond to the context. var generator = new ResponseWriter(); generator.Send(context, args.Response); } // Disconnect when done. if (e.Response.HttpVersion == "HTTP/1.0" || e.Response.Connection.Type == ConnectionType.Close) context.Disconnect(); } catch (Exception err) { if (err is HttpException) { var exception = (HttpException) err; SendErrorPage(exception); } else { _logger.Debug("Request failed.", err); SendErrorPage(err); } e.IsHandled = true; } }
private void SendResponse(RequestEventArgs e, byte[] data) { e.Response.Status = HttpStatusCode.OK; if (null != data) e.Response.ContentLength.Value = data.Length; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); if (data != null && data.Length > 0) { e.Context.Stream.Write(data, 0, data.Length); e.Context.Stream.Flush(); } }
private void SendErrorPage(Exception exception) { var httpException = exception as HttpException; var response = HttpContext.Current.Response; response.Status = httpException != null ? httpException.Code : HttpStatusCode.InternalServerError; response.Reason = exception.Message; if (response.Body.CanWrite) response.Body.SetLength(0); var args = new ErrorPageEventArgs(HttpContext.Current) {Exception = exception}; ErrorPageRequested(this, args); try { var generator = new ResponseWriter(); if (args.IsHandled) generator.Send(HttpContext.Current, response); else generator.SendErrorPage(HttpContext.Current, response, exception); } catch (Exception err) { _logger.Error("Failed to display error page", err); } }
public ProcessingResult Process(RequestContext context) { IServableContent hit = null; content.TryGetValue(context.Request.Uri.AbsolutePath, out hit); var runner = hit as ActionRunner; if (runner != null) { var service = (JsonService)runner.Type.GetConstructor(Type.EmptyTypes).Invoke(null); string result = null; try { result = runner.Invoke(service, context.Request); } catch (Exception e) { Logger.ReportException("Failed to execute action in MBWeb: " + context.Request.Uri.AbsolutePath, e); throw; } var body = new MemoryStream(); var bytes = Encoding.UTF8.GetBytes(result); body.Write(bytes, 0, bytes.Length); context.Response.ContentLength.Value = body.Length; context.Response.Add(new ContentTypeHeader("application/json")); var generator = new ResponseWriter(); generator.SendHeaders(context.HttpContext, context.Response); generator.SendBody(context.HttpContext, body); return ProcessingResult.Abort; } EmbeddedContent embeddedContent = hit as EmbeddedContent; if (embeddedContent != null) { var actual = new MemoryStream(); using (var body = embeddedContent.Stream) { StreamReader reader = new StreamReader(body); var read = reader.ReadToEnd(); var bytes = Encoding.UTF8.GetBytes(read); actual.Write(bytes, 0, bytes.Length); context.Response.ContentLength.Value = bytes.Length; actual.Seek(0, SeekOrigin.Begin); } context.Response.Add(embeddedContent.ContentTypeHeader); var generator = new ResponseWriter(); generator.SendHeaders(context.HttpContext, context.Response); generator.SendBody(context.HttpContext, actual); return ProcessingResult.Abort; } // fake 404 for now var badRequest = new MemoryStream(Encoding.UTF8.GetBytes("Not Found : " + context.Request.Uri.AbsolutePath)); var rw = new ResponseWriter(); context.Response.ContentLength.Value = badRequest.Length; rw.SendHeaders(context.HttpContext, context.Response); rw.SendBody(context.HttpContext, badRequest); return ProcessingResult.Abort; }
public bool Handle(string req, RequestEventArgs e) { e.Response.Status = HttpStatusCode.OK; string path = Utility.DecodeURL(e.Request.Uri.AbsolutePath); byte[] data = null; if (path.StartsWith(WEB_ICON_PREFIX)) { //what icon been requested? string ext = path.Substring(path.LastIndexOf("/") + 1); lock (sync) { //Has the icon been requested already? if so just return that if (iconCache.ContainsKey(ext)) { data = iconCache[ext]; e.Response.ContentType = contentTypes["png"]; } else { //item wasnt cached if (ext == "folder") { data = GetResource("Images\\folder.png"); iconCache.Add("folder", data); e.Response.ContentType = contentTypes["png"]; } else { Icon icon = IconReader.GetFileIcon("file." + ext, IconReader.IconSize.Small, false); using (var mem = new MemoryStream()) { using (Bitmap bmp = icon.ToBitmap()) { bmp.MakeTransparent(); bmp.Save(mem, ImageFormat.Png); data = mem.ToArray(); iconCache.Add(ext, data); e.Response.ContentType = contentTypes["png"]; } } } } } } else if (path.StartsWith(WEB_PREFIX)) { //Has a static file been requested? data = GetResource(path.Substring(WEB_PREFIX.Length)); string ext = Path.GetExtension(path); if (ext != null && ext.StartsWith(".")) ext = ext.Substring(1); ContentTypeHeader header; if (!contentTypes.TryGetValue(ext, out header)) header = contentTypes["default"]; e.Response.ContentType = header; } else { bool validPath = false; string page = Encoding.UTF8.GetString(GetResource("template.html")); var pagedata = new Dictionary<string, object>(); pagedata.Add("model", model); pagedata.Add("appver", Model.AppVersion); pagedata.Add("freelimit", Utility.FormatBytes(Model.FREE_FILE_LIMIT)); pagedata.Add("uploadslots", model.MaxUploads); int freeslots = model.MaxUploads - uploadLimiter.GetActiveTokenCount(); pagedata.Add("currentuploadslots", freeslots); pagedata.Add("queueInfo", freeslots > 0 ? "" : " Queue length: " + uploadLimiter.GetQueueLength() + "."); pagedata.Add("slotcolour", freeslots > 0 ? "green" : "red"); pagedata.Add("util", new Utility()); if (!path.EndsWith("/")) pagedata.Add("path", (path + "/").Replace("#", "%23")); else pagedata.Add("path", (path).Replace("#", "%23")); //Add path info var paths = new List<Dictionary<string, object>>(); string[] split = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < split.Length; i++) { var sb = new StringBuilder("/"); for (int y = 0; y <= i; y++) { sb.Append(split[y]); sb.Append("/"); } var di = new Dictionary<string, object>(); di.Add("Name", split[i]); di.Add("Path", sb.ToString()); paths.Add(di); } pagedata.Add("pathSplit", paths); /* List<DisplayInfo> peers = new List<DisplayInfo>(); foreach (var peer in model.Network.Nodes.ToList().Where(n => n.NodeType != ClientType.Overlord && !string.IsNullOrEmpty(n.Nickname))) { if (!string.IsNullOrEmpty(peer.Location)) { DisplayInfo p = new DisplayInfo(); p.SetData("Name", string.IsNullOrEmpty(peer.Nickname) ? "Unknown" : peer.Nickname); p.SetData("Location", peer.Location); peers.Add(p); } } pagedata.Add("peers", peers);*/ var files = new List<Dictionary<string, object>>(); long totalSize = 0; //Try to resolve the path to a file first string[] possiblePaths; if (infoService.ToLocalPath(path, out possiblePaths)) //User has requested a file foreach (string possiblePath in possiblePaths) if (File.Exists(possiblePath)) return SendFile(e, possiblePath, path); //User didnt request a file so try to send directory info List<BrowsingFile> results; if (infoService.GetPath(path, false, true, out results)) { foreach (var browsingFile in results) { if (browsingFile.IsFolder) { var d = new Dictionary<string, object> { {"Name", browsingFile.Name}, {"Path", Utility.EncodeURL(browsingFile.Name)}, {"Icon", "folder"}, {"Sizetxt", Utility.FormatBytes(browsingFile.Size)}, {"Size", browsingFile.Size}, { "LastModifiedtxt", browsingFile.LastModified.ToShortDateString() }, {"LastModified", browsingFile.LastModified} }; files.Add(d); totalSize += browsingFile.Size; } else { var d = new Dictionary<string, object> {{"Name", browsingFile.Name}}; string ext = Path.GetExtension(browsingFile.Name); if (ext != null && ext.StartsWith(".")) ext = ext.Substring(1); string name = browsingFile.Name; if (!string.IsNullOrEmpty(name)) name = name.Replace("#", "%23"); d.Add("Path", name); d.Add("Icon", ext); d.Add("Size", browsingFile.Size); d.Add("Sizetxt", Utility.FormatBytes(browsingFile.Size)); d.Add("LastModifiedtxt", browsingFile.LastModified.ToShortDateString()); d.Add("LastModified", browsingFile.LastModified); files.Add(d); totalSize += browsingFile.Size; } } validPath = true; //Clear result list to help GC results.Clear(); } pagedata.Add("files", files); pagedata.Add("totalSize", Utility.FormatBytes(totalSize)); if (validPath) { //Generate the page page = TemplateEngineService.Generate(page, pagedata); data = Encoding.UTF8.GetBytes(page); e.Response.ContentType = contentTypes["html"]; } //Clear up foreach (var item in pagedata.Values) { if (item is Dictionary<string, object>) { var i = item as Dictionary<string, object>; i.Clear(); } } pagedata.Clear(); } if (null == data) { data = Encoding.UTF8.GetBytes("404 Not found"); } var generator = new ResponseWriter(); e.Response.ContentLength.Value = data.Length; generator.SendHeaders(e.Context, e.Response); e.Context.Stream.Write(data, 0, data.Length); e.Context.Stream.Flush(); data = null; return true; }
private void SendOk(RequestEventArgs e) { e.Response.Status = HttpStatusCode.OK; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); }
private void ErrorPage(IRequest request, IResponse response, HttpException exception) { response.Status = exception.Code; response.Reason = exception.Message; response.Body.SetLength(0); var args = new ErrorPageEventArgs(HttpContext.Current, request, response); args.Exception = exception; ErrorPageRequested(this, args); // Add default error body. if (!args.IsHandled) { string htmlTemplate = "<html><head><title>{1}</title></head><body>Error {0}: {1}</body></html>"; byte[] body = Encoding.UTF8.GetBytes(string.Format(htmlTemplate, (int) response.Status, response.Reason)); response.Body.Write(body, 0, body.Length); } try { var generator = new ResponseWriter(); generator.Send(HttpContext.Current, response); } catch (Exception err) { #if DEBUG if (ExceptionThrown.GetInvocationList().Length == 1) throw; #endif ExceptionThrown(this, new ExceptionEventArgs(err)); } }
private bool HandleGet(RequestEventArgs e, NetworkRequest req) { //No url? if (string.IsNullOrEmpty(req.Param)) return false; string[] possiblePaths; if (shareInfoService.ToLocalPath(req.Param, out possiblePaths)) { foreach (string possiblePath in possiblePaths) { if (File.Exists(possiblePath)) { var ffu = new FAPFileUploader(bufferService, serverUploadLimiterService); var session = new TransferSession(ffu); model.TransferSessions.Add(session); try { //Try to find the username of the request string userName = e.Context.RemoteEndPoint.Address.ToString(); Node search = model.Network.Nodes.ToList().Where(n => n.ID == req.SourceID).FirstOrDefault(); if (null != search && !string.IsNullOrEmpty(search.Nickname)) userName = search.Nickname; using ( FileStream fs = File.Open(possiblePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { ffu.DoUpload(e.Context, fs, userName, possiblePath); } //Add log of upload double seconds = (DateTime.Now - ffu.TransferStart).TotalSeconds; var txlog = new TransferLog(); txlog.Nickname = userName; txlog.Completed = DateTime.Now; txlog.Filename = Path.GetFileName(possiblePath); txlog.Path = Path.GetDirectoryName(req.Param); if (!string.IsNullOrEmpty(txlog.Path)) { txlog.Path = txlog.Path.Replace('\\', '/'); if (txlog.Path.StartsWith("/")) txlog.Path = txlog.Path.Substring(1); } txlog.Size = ffu.Length - ffu.ResumePoint; if (txlog.Size < 0) txlog.Size = 0; if (0 != seconds) txlog.Speed = (int) (txlog.Size/seconds); model.CompletedUploads.Add(txlog); } finally { model.TransferSessions.Remove(session); } return true; } } } e.Response.Status = HttpStatusCode.NotFound; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); return true; }
public ProcessingResult Process(RequestContext requestcontext) { IRequest request = requestcontext.Request; IResponse response = requestcontext.Response; IHttpContext context = requestcontext.HttpContext; if (request.Method == Method.Post) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> AJAX request from {1} {2} {3} {4}", DateTime.Now.ToString("hh:mm"), context.RemoteEndPoint, request.HttpVersion, request.Method, request.Uri.AbsoluteUri); if (HasParameter(request.Parameters, request.Parameters.Get("rooturl"))) { if (SessionManager.Current == null) { SessionManager.Create(); SessionManager.Current.FirstRun = true; SessionManager.Save(SessionManager.Current); Console.WriteLine("({0}) <Web Interface> Created new session with id {1}", DateTime.Now.ToString("hh:mm"), SessionManager.Current.SessionId); } Console.WriteLine("({0}) <Web Interface> AJAX parameters width={1}&height={2}&rooturl={3}", DateTime.Now.ToString("hh:mm"), request.Parameters.Get("width").Value, request.Parameters.Get("height").Value, request.Parameters.Get("rooturl").Value); response.ContentType = new ContentTypeHeader("application/json"); response.Status = HttpStatusCode.OK; var stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"session\":\"" + SessionManager.Current.SessionId + "\",\"data\":\"\"}")); response.ContentLength.Value = stream.Length; var generator = new ResponseWriter(); generator.SendHeaders(context, response); generator.SendBody(context, stream); Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "{\"session\":\"" + SessionManager.Current.SessionId + "\",\"data\":\"\"}"); } if (HasParameter(request.Parameters, request.Parameters.Get("session"))) { Console.WriteLine("({0}) <Web Interface> AJAX parameters width={1}&height={2}&session={3}", DateTime.Now.ToString("hh:mm"), request.Parameters.Get("width").Value, request.Parameters.Get("height").Value, request.Parameters.Get("session").Value); //Console.WriteLine("({0}) <Web Interface> Trying to load session with id {1}", DateTime.Now.ToString("hh:mm"), request.Parameters.Get("session").Value); session = SessionManager.Load(request.Parameters.Get("session").Value); if (session == null) { Console.WriteLine("({0}) <Web Interface> Failed to load session with id {1}", DateTime.Now.ToString("hh:mm"), request.Parameters.Get("session").Value); response.ContentType = new ContentTypeHeader("application/json"); response.Status = HttpStatusCode.OK; var stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"session\":\"" + request.Parameters.Get("session").Value + "\",\"data\":\"Failed to load session !\"}")); response.ContentLength.Value = stream.Length; var generator = new ResponseWriter(); generator.SendHeaders(context, response); generator.SendBody(context, stream); Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "{\"session\":\"" + request.Parameters.Get("session").Value + "\",\"data\":\"Failed to load session !\"}"); } else { //Console.WriteLine("({0}) <Web Interface> Loaded session with id {1}", DateTime.Now.ToString("hh:mm"), request.Parameters.Get("session").Value); if (request.Parameters.Get("session").Value == session.SessionId) { if (HasParameter(request.Parameters, request.Parameters.Get("keys"))) { lastkeys = request.Parameters.Get("keys").Value; while (lastkeys != null) { Thread.Sleep(50); if (lastkeys == null) { if (request.Parameters.Get("session").Value == lastsession) { response.ContentType = new ContentTypeHeader("text/html; charset=utf-8"); response.Status = HttpStatusCode.OK; var stream2 = new MemoryStream(Encoding.UTF8.GetBytes("OK")); response.ContentLength.Value = stream2.Length; var generator2 = new ResponseWriter(); generator2.SendHeaders(context, response); generator2.SendBody(context, stream2); Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "OK"); lastsession = null; break; } } } } else { if (session.FirstRun) { lastkeys = null; response.ContentType = new ContentTypeHeader("application/json"); response.Status = HttpStatusCode.OK; var stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"session\":\"" + session.SessionId + "\",\"data\":\"Connected to server-side.\\r\\nWelcome to WCell.Terminal !\\r\\n\"}")); response.ContentLength.Value = stream.Length; var generator = new ResponseWriter(); generator.SendHeaders(context, response); generator.SendBody(context, stream); Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "{\"session\":\"" + session.SessionId + "\",\"data\":\"Connected to server-side. Welcome to WCell.Terminal !\"}"); session.FirstRun = false; SessionManager.Save(session); } else { while (lastkeys == null) { Thread.Sleep(50); if (lastkeys != null) { string stringValue = ""; if (lastkeys.Length == 2) { int value = Convert.ToInt32(lastkeys, 16); if (value <= Int32.MaxValue) { stringValue = Char.ConvertFromUtf32(value); } else { /*Console.WriteLine("({0}) <Web Interface> Problem with lastkeys ({1}): {2}", DateTime.Now.ToString("hh:mm"), e, lastkeys); stringValue = "\\r\\nProblem with lastkeys: " + lastkeys + "\\r\\n";*/ if (lastkeys.Length > 2) { string[] strArray = SplitString(lastkeys, 2); if (strArray != null) { foreach (string str in strArray) { if (!String.IsNullOrWhiteSpace(str)) { value = Convert.ToInt32(str, 16); stringValue += Char.ConvertFromUtf32(value); } } } } } } else { /*Console.WriteLine("({0}) <Web Interface> Problem with lastkeys ({1}): {2}", DateTime.Now.ToString("hh:mm"), e, lastkeys); stringValue = "\\r\\nProblem with lastkeys: " + lastkeys + "\\r\\n";*/ if (lastkeys.Length > 2) { string[] strArray = SplitString(lastkeys, 2); if (strArray != null) { foreach (string str in strArray) { if (!String.IsNullOrWhiteSpace(str)) { int value = Convert.ToInt32(str, 16); stringValue += Char.ConvertFromUtf32(value); } } } } } if (stringValue == "\r") { stringValue = "\\r\\n"; } if (stringValue == "\x7f") { stringValue = "\\b \\b"; } if (stringValue == "\f") { stringValue = "\\f"; } if (stringValue == "\t") { stringValue = "\\t"; } if (lastsession == null) { lastsession = session.SessionId; } response.ContentType = new ContentTypeHeader("application/json"); response.Status = HttpStatusCode.OK; var stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"session\":\"" + lastsession + "\",\"data\":\"" + stringValue + "\"}")); response.ContentLength.Value = stream.Length; var generator = new ResponseWriter(); generator.SendHeaders(context, response); generator.SendBody(context, stream); Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "{\"session\":\"" + lastsession + "\",\"data\":\"" + stringValue + "\"}"); lastkeys = null; break; } } } } } else { Console.WriteLine("({0}) <Web Interface> AJAX response {1}", DateTime.Now.ToString("hh:mm"), "Invalid Session: " + request.Parameters.Get("session").Value); } } } return ProcessingResult.Abort; } else { if (context.IsSecure) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Secure HTTP request from {1} {2} {3} {4}", DateTime.Now.ToString("hh:mm"), context.RemoteEndPoint, request.HttpVersion, request.Method, request.Uri.AbsoluteUri); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> HTTP request from {1} {2} {3} {4}", DateTime.Now.ToString("hh:mm"), context.RemoteEndPoint, request.HttpVersion, request.Method, request.Uri.AbsoluteUri); } } return ProcessingResult.Continue; }