emikulic / darkhttpd

When you need a web server in a hurry.
https://unix4lyfe.org/darkhttpd/
ISC License
1.03k stars 83 forks source link

Simple CORS support #16

Closed aszkid closed 1 year ago

aszkid commented 2 years ago

Would you be open to merging a PR adding (very) simple support for CORS headers? My first thought is that passing an --allow-origin X argument would add the Access-Control-Allow-Origin: X header to successful HTTP responses. We don't care about pre-flight requests since we only respond to GET and HEAD requests.

Thanks for working on darkhttpd! It's pretty sweet.

emikulic commented 2 years ago

Yep, sounds good!

Seirdy commented 2 years ago

Might be easier to instead support defining arbitrary headers.

FallingSnow commented 2 years ago

Might be easier to instead support defining arbitrary headers.

Please this. Solves a host of other possible issues and is easier to implement than specific CORS support.

rdebath commented 2 years ago

Would this not count as "simple" support, after all darkhttpd only does "simple" cors requests (except auth).

diff --git a/darkhttpd.c b/darkhttpd.c
index 350a56a..0bcf3f5 100644
--- a/darkhttpd.c
+++ b/darkhttpd.c
@@ -302,7 +302,7 @@ static char *logfile_name = NULL;   /* NULL = no logging */
 static FILE *logfile = NULL;
 static char *pidfile_name = NULL;   /* NULL = no pidfile */
 static int want_chroot = 0, want_daemon = 0, want_accf = 0,
-           want_keepalive = 1, want_server_id = 1;
+           want_keepalive = 1, want_server_id = 1, want_wildcors = 0;
 static char *server_hdr = NULL;
 static char *auth_key = NULL;
 static uint64_t num_requests = 0, total_in = 0, total_out = 0;
@@ -1145,6 +1145,9 @@ static void parse_commandline(const int argc, char *argv[]) {
         else if (strcmp(argv[i], "--no-server-id") == 0) {
             want_server_id = 0;
         }
+        else if (strcmp(argv[i], "--cors") == 0) {
+            want_wildcors = 1;
+        }
         else if (strcmp(argv[i], "--timeout") == 0) {
             if (++i >= argc)
                 errx(1, "missing number after --timeout");
@@ -2802,6 +2805,11 @@ int main(int argc, char **argv) {
         xasprintf(&server_hdr, "Server: %s\r\n", pkgname);
     else
         server_hdr = xstrdup("");
+    if (want_wildcors && auth_key == 0) {
+        char * p = server_hdr;
+        xasprintf(&server_hdr, "%s%s", p, "access-control-allow-origin: *\r\n");
+        free(p);
+    }
     init_sockin();

     /* open logfile */
emikulic commented 1 year ago

Thanks to @kugland for taking care of this. :)