// /** // * File: Connection.cs // * Author: haraldwolff // * // * This file and it's content is copyrighted by the Author and / or copyright holder. // * Any use wihtout proper permission is illegal and may lead to legal actions. // * // * // **/ using System; using ln.type; using System.IO; using ln.logging; using ln.http.listener; namespace ln.http.connections { public abstract class Connection : IDisposable { public Listener Listener { get; private set; } public abstract IPv6 RemoteHost { get; } public abstract int RemotePort { get; } public abstract Stream GetStream(); public Connection(Listener listener) { Listener = listener; } public virtual HttpRequest ReadRequest(HTTPServer httpServer) { try { return new HttpRequest(httpServer, GetStream(), Listener.LocalEndpoint, new Endpoint(RemoteHost, RemotePort)); } catch (IOException) { return null; } catch (Exception e) { Logging.Log(e); return null; } } public abstract void Close(); public virtual void Dispose() { Close(); Listener = null; } public virtual void SendResponse(HttpResponse response) => SendResponse(GetStream(), response); public static void SendResponse(Stream stream, HttpResponse response) { response.HttpRequest.FinishRequest(); response.SetHeader("Content-Length", response.ContentStream.Length.ToString()); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.NewLine = "\r\n"; streamWriter.WriteLine("{0} {1} {2}", response.HttpRequest.Protocol, response.StatusCode, response.StatusMessage); foreach (String headerName in response.GetHeaderNames()) { streamWriter.WriteLine("{0}: {1}", headerName, response.GetHeader(headerName)); } foreach (HttpCookie httpCookie in response.Cookies) { streamWriter.WriteLine("Set-Cookie: {0}", httpCookie.ToString()); } streamWriter.WriteLine(); streamWriter.Flush(); response.ContentStream.Position = 0; response.ContentStream.CopyTo(stream); response.ContentStream.Close(); response.ContentStream.Dispose(); stream.Flush(); } } }