Giter Site home page Giter Site logo

ceenhttpd's People

Contributors

dependabot[bot] avatar hc4 avatar kenkendk avatar peckmore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ceenhttpd's Issues

Feature Suggestion

I hope this is the right place for feature suggestions.

It looks like I may end up using this for a project very soon. I've already got a feature I'd like to see added, and in fact, I'd probably be able to add it myself (assuming my project moves forward and I get to use this library). If I get to use it, I'd like to be able to help contribute by adding the feature if the maintainer approves.

What I'd like to see is a decorated approach to routing. Basically, an exact approach like Embed.IO uses.

Example code pulled directly from Embed.IO:
`public class PeopleController : WebApiController
{
// You need to add a default constructor where the first argument
// is an IHttpContext
public PeopleController(IHttpContext context)
: base(context)
{
}

// You need to include the WebApiHandler attribute to each method
// where you want to export an endpoint. The method should return
// bool or Task<bool>.
[WebApiHandler(HttpVerbs.Get, "/api/people/{id}")]
public async Task<bool> GetPersonById(int id)
{
    try
    {
        // This is fake call to a Repository
        var person = await PeopleRepository.GetById(id);
        return await Ok(person);
    }
    catch (Exception ex)
    {
        return await InternalServerError(ex);
    }
}

// You can override the default headers and add custom headers to each API Response.
public override void SetDefaultHeaders() => HttpContext.NoCache();

}
`

I just feel this approach is a lot more maintainable since the routes are directly labeled at the entry point of their functions.

Of course, there are multiple ways that a decorated function approach could be added. It doesn't necessarily have to use the subclassed controller approach as Embed.IO.

If you feel that this architecture is too opinionated to be part of the Ceen base package, it shouldn't be too difficult to put support for this architecture in an optional module.

What do you think?

support .net standard v2.0

would be great if this worked with .net standard v2.0 as then we could use it in .net framework 4.8 solutions

Spawned child process hangs

After a few days with light load on a setup using .net core and an isolated processes the spawned child hangs in various ways. Sometimes it is simply not responding, other times it appears to close the connection immediately. Simply issuing a touch config.txt will spawn a new child and the new child works immediately. Strangely, the IPC library does have a ping-pong method that would cause a frozen child process to be terminated, but since this does not happen it seems that the IPC part keeps working, but the HTTP handling part somehow fails.

I have not been able to reproduce this in stress testing locally, and listing open sockets while the child hangs does not suggest leaking socket descriptors. The spawned processes makes it slightly complicated to debug. Disabling isolated processes makes the problem go away.

Add XSRF module

This could easily use the module prefix to decide which paths are protected by the XSRF module.

Possible configuration options

  • Name of XSRF cookie
  • Name of XSRF header
  • Expiration of the cookie (and session)
  • Status code on reject
  • Status message on reject

URL not correctly decoded.

Hello,

I have some problem with URL not correctly decoded.
Many Web browsers escape spaces inside of URIs into plus ("+") characters (Chrome on Windows โ€ฆ)
According the Microsoft Doc the use of Uri.UnescapeDataString method does not convert plus characters into spaces.

So solution :
text = text.Replace("+", " ");
text = System.Uri.UnescapeDataString(text);

Or
use System.Web.HttpUtility.UrlDecode instead

Best continuation
Daniel

Add authentication module

Could be multiple related items

  • Use HTTP basic auth
  • Custom auth with redirect to login page
  • OAuth based auth
  • NTLM (Kerberos) auth

Question about CORSHandler

Hi there,

Love the project, using it to create a web-API...

Wondering where to ask questions?

CORSHandler
should I make my handlers inherit from this or should I add it as a handler in the route chain before my handlers?

This:
(in my handler class)
namespace MyNameSpace.API { class MyApiHandlerMethod : Ceen.Httpd.Handler.CORSHandler { public new async Task<bool> HandleAsync(IHttpContext context) {
or:

            config = new ServerConfig()
                .AddLogger(sqlLogger)
                .AddRoute("/*", new Ceen.Httpd.Handler.CORSHandler())
                .AddRoute("/someapifunction", new MyApiHandlerMethod())
                .AddRoute("/someotherapifunction", new MyOtherApiHandlerMethod(this))

Linux support

Hi!

Does this library support linux?
I can't seem to get it working...

My code

var httpConfig = new ServerConfig()
.AddRoute(new HttpRequestHandler());

var httpsConfig = new ServerConfig()
.AddRoute(new HttpRequestHandler());
httpsConfig.LoadCertificate(@"./bfmeladdercom.pfx", "4j4k0c2c");

HttpServerTask = HttpServer.ListenAsync(
    new IPEndPoint(IPAddress.Any, 80),
    false,
    httpConfig
);

HttpsServerTask = HttpServer.ListenAsync(
    new IPEndPoint(IPAddress.Any, 443),
    true,
    httpsConfig
);

No requests are being received by HttpRequestHandler...

Publish/build config
Screenshot 2024-01-04 083209

Any help would be apreciated!

REST APIs problem

for some reasons REST APIs example not work.
compile, not hit any function of ApiExampleController.
every time give me 404.

EDIT:
public IResult Index(IHttpContext context) only hit with /api/v1
but public IResult Index(int id) give me 404.
and public IResult Detail(int id) give me 500. !!

that's what i test

GET "/api/v1" => ApiExampleController.Index => Hit
GET "/api/v1/4" => ApiExampleController.Index(4) => NOT Hit
GET "/api/v1/4/detail => ApiExampleController.Detail(4) => NOT Hit

Could Ceen Support HTTP 2.0?

I'm using the ceenhttpd on version 0.9.9 and I have a client which can only support HTTP 2.0. Right now the ceen http request thows "HTTP Version Not Supported" error, is there a chance to make it support HTTP 2.0/3.0?

Multipart Upload doesn't write the response

When I try to post a multipart/form-data I see the HandleAsync complete but the server never write the response back until it times out. Sending this to working handlers produces the same issue.

`
POST http://localhost:8888/upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="test.png"
Content-Type: image/png

< test.png
------WebKitFormBoundary7MA4YWxkTrZu0gW--
`

IVirtualFileSystem interface visibility

I'm trying to implement own VirtualFileSystem - unfortunately, the IVirtualFileSystem interface is not visible: it is defined inside FileHandler class, should be outside, so adding custom VirtualFileSystem is not possible. Is there any (unknown for me) reason for that this is hidden? If not, would I like to ask you about change this?
IMHO the best solution will be splitting FileHandler.cs file into two parts: one containing the FileSystem, and the second containing FileHandler without own FileSystem implementation.

Dynamic content example not working

Hi, thanks for your work and for sharing this module. It makes serving HTTPS web content really easy without the need of importing certs to the MMC store.

However, I was not able to use your provided dynamic content example..

When I add your example code to my project, it always tells me

'Program.TimeOfDayHandler' does not implement interface member 'IHttpModule.HandleAsync(IHttpContext)'

I use Ceen.Httpd version 9.3 because of compatibility needs for .NET 4.5.
What should I do here to make this work?

Also, can you provide slightly more documentation about how to serve content via ceen.httpd (without config file)?

Many thanks!

Poor Preformance

Hello, i am trying to implement a custom web application based on this project.
first of all i want to say that this is a really cool project that is almost perfect for my needs.
however i am facing one major issue, it looks like there is a very high processing time for the http requests.
i am using a rather simple setup with 5 routes set up,.
when i am starting up my app, and the index.html file starts to load (which requires 30 something js and css files) it takes more than 10 seconds to load.
single file requests can take up to 5 and even 10 seconds.

even putting a breakpoint on one of the handlers i can tell that it takes almost a second until the HandleAsync request is called

any idea what is happening here?

application/x-www-form-urlencoded

Hello,

In HttpRequest.cs, you test the content type:
if (string.Equals("application/x-www-form-urlencoded", this.ContentType))

But in some case the browser send "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"
So the test fails ...

Congratulations again for this superb work.
Thank you

Daniel

Parallel Requests

Hi,

Just a quick question (hopefully). I have just tested the CEEN library using the timeofday example in your notes. The server works well but when ramping up the requests, it seems that I cannot get anymore than 20 parallel requests before I get errors. I have downloaded (and debugged) the source and I cannot see any errors. It seems that the TCP connection is being refused (although I could be wrong).

Any ideas on where I could look?

C# VS2019 .NET 4.7.2

KR
Andy


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

MVC Example in Readme doesn't work

Hi - ceen seems like exactly what I'm looking for, but I ran into a few issues trying to set it up. I basically copy/pasted the MVC example from the readme and the Index with no parameters works, but none of the other ones ("/api/v1/{id}", "/api/v1/{id}/detail") work - one gives a 404 and the other a 500.

Is it possible the readme example wasn't updated after a change that modified the way that stuff would need to be set up at some point? Am I missing better documentation that exists elsewhere? I'm about to download the source and debug through it, but wanted to ask as well just in case.

Implementing Event-Stream

I would like to keep writing to response stream without closing the current request to implement Event-Stream. Is this possible?

The way I currently do it in HttpListener is write contentType = "text/event-stream" send the status code. Then I just keep writing to
response.OutputStream.Write(...);
response.OutputStream.Flush();

If the client gets disconnected the write will throw an exception that the client is not connected anymore. Then I close the output stream.

Unhandled Exception: System.AggregateException: One or more errors occurred.

When I compile in Debug mode and run from bin\Debug folder everything started fine.
Error appear when I press key for stopping server.
What I need to do for handle this error?

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: An attempt was made to transition a task to a final state when it had already completed.
   at System.Threading.Tasks.TaskCompletionSource`1.SetResult(TResult result)
   at Ceen.Httpd.HttpServer.RunnerControl.Stop(String logtaskid)
   at Ceen.Httpd.HttpServer.RunnerControl.<.ctor>b__27_0()
   at System.Threading.CancellationToken.ActionToActionObjShunt(Object obj)
   at System.Threading.CancellationCallbackInfo.ExecutionContextCallback(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.CancellationCallbackInfo.ExecuteCallback()
   at System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments args)
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   --- End of inner exception stack trace ---
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean throwOnFirstException)
   at System.Threading.CancellationTokenSource.Cancel()
   at ConsoleApp1.Program.Main(String[] args) in D:\dotnet\ConsoleApp2\ConsoleApp1\Program.cs:line 43

Assign object reference to a Session

Hey,

I'm using Ceen.Httpd.Handler.SessionHandler to handle sessions context.

So, there is a IHttpContext.Session (Dictionary), to assign Key and Value strings.

I wonder if can I assign an object reference to the session context.

Until now I have a separated list of objects with an ID, so the context has a "ID" key with a identity value to manually reference list index. But, the problem is to know when the session context ends, so I can release my object.

Better method will be assign object directly to the session context, of course.

Thanks,
Best regards.

SSL Example?

Hey there, thanks for a great tool.
I'd like to understand if/how I can serve files via HTTPS in the local network with Ceen, ideally with some automatic way of setting up a self-signed certificate (usecase is a small tool that will run on machines in the local network only).
Are there any docs for SSL usage and certificate handling?


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Can't stop server

Hi, I have problems stopping the server. When it's time to close the program I call the Stop method, and then the application hangs on serverTask.Wait(). This is the code I use on my application.

namespace App.Web.WebServer
{
    static class WebServer
    {
        static System.Threading.CancellationTokenSource tcs = null;
        static Task serverTask = null;

        public static void init()
        {
            WebServer.tcs = new System.Threading.CancellationTokenSource();
            var srvConf = new ServerConfig()
                .AddLogger(new CLFStdOut())
                .AddRoute("/jquery-3.3.1.min.js", new common.jqueryHandler())
                .AddRoute("/favicon.ico", new common.favicoHandler())
                //... more routes on other classes
                .AddRoute(new FileHandler("."));

            var usessl = true;
            srvConf.SSLCertificate = new X509Certificate2("certName.pfx", "certPass");

            serverTask = Ceen.Httpd.HttpServer.ListenAsync(
                new IPEndPoint(IPAddress.Any, 9000),
                usessl,
                srvConf,
                tcs.Token
            );

        }

        public static void Stop()
        {
            if (tcs != null)
            {
                tcs.Cancel();
                serverTask.Wait();
            }
        }
    }

    public static class common
    {
        public class jqueryHandler : Ceen.IHttpModule
        {
            public async System.Threading.Tasks.Task<bool> HandleAsync(Ceen.IHttpRequest request, Ceen.IHttpResponse response)
            {
                response.SetNonCacheable();
                await response.WriteAllAsync(new FileStream(AppDomain.CurrentDomain.BaseDirectory + @"\Data\web\scripts\jquery-3.3.1.min.js", FileMode.Open), "text/javascript");
                return true;
            }

            public System.Threading.Tasks.Task<bool> HandleAsync(IHttpContext context)
            {
                return HandleAsync(context.Request, context.Response);
            }
        }

        public class favicoHandler : Ceen.IHttpModule
        {
            public async System.Threading.Tasks.Task<bool> HandleAsync(Ceen.IHttpRequest request, Ceen.IHttpResponse response)
            {
                response.SetNonCacheable();
                await response.WriteAllAsync(new FileStream(AppDomain.CurrentDomain.BaseDirectory + @"\Data\web\img\ico\appIco.ico", FileMode.Open));
                return true;
            }

            public System.Threading.Tasks.Task<bool> HandleAsync(IHttpContext context)
            {
                return HandleAsync(context.Request, context.Response);
            }
        }
    }
}

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

nuget broken?

No dependencies are listed in your nuget packages. As a result, when trying to pull in, nuget refuses.

Are you only supporting .net core/6+? Came here from a post in 2019 which would make it seem as if you could support older .net frameworks.

"Dynamic content" example does not work

There seems to be information missing from this example. I get multiple errors trying to use it.

There is no definition for WriteAllJsonAsync or SetNonCacheable. Plus, the IHttpModule interface says that two functions are not implemented.

The references should also include:

using System;
**using System.Web;**
using Ceen.Httpd;
using Ceen.Httpd.Handler;
using Ceen.Httpd.Logging;
using System.Net;
using System.Threading;
using Newtonsoft.Json;

Ceen 0.9.9 crashing on large upload requests

Hi,

when serving content with ceen via HTTPS and sending a large multipart form request to it, it crashes silently.
The browser tells that there was a connection error.

File upload requests around ~2.5Mb are fine, but crashes stat to happen from 6Mb on.


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Server gives a 400 Bad Request error

I am using a wifi device that connects to a host application running the http server. When the device logs on, it sends an http post in the following format:

POST HTTP/1.1
Host: 192.168.10.172:8080
Keep-Alive: 115
Connection: keep-alive
Content-Length: 98
Content-Type: application/x-www-form-urlencoded

user=demo&pswd=password&termID=000666213dfd&serverID=XXXXX+XXXX+Demo&PID=000&CKS=099&termdata=0%0F

The Ceen server however always responds with a "400 Bad Request" error with no information. I think the form post is properly formatted. Any suggestions as to how I would debug this to find out what the problem is?

Ok, I'm posting this edit because I figured it out. The server chokes on line 255 in HttpRequest.cs. The reason is that there are two spaces after "POST" in the header and no path to a handler is specified. Would it be reasonable to modify the code such that if the path is empty, "/" is assumed?

Support WebSocket?

Hi, I found amazing this library, wanted to know if you have support for WebSocket? SAlu2s

Add session module

Add a module that will inject a session cookie into the response, if no session cookie was found.

The module could then offer something like:

var session = Ceen.Httpd.Handlers.Session.GetSession(request);

The module should keep track of cookie expiration and purge memory when that happens.

The session state should survive AppDomain reloads, so it should support custom session data storage, to allow the Cli loader to store data in the primary AppDomain. This could also be used/abused to support more persistent storage in a database, or even share the session between different hosts via an external service.

It should support at some configuration:

  • Cookie expiration
  • Cookie name
  • Cookie via url

Changelog for nuget 0.9.10 update

Hi there, noticed there is an update from 0.9.9 to 0.9.10 in nuget... however I see no changelog, or mention of it here in github?

Is the changelog available somewhere else?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.