Quellcode durchsuchen

CORS for SSI pages

bel vor 11 Jahren
Ursprung
Commit
c62ded82e8
3 geänderte Dateien mit 21 neuen und 1 gelöschten Zeilen
  1. 13 1
      src/civetweb.c
  2. 1 0
      test/cors.html
  3. 7 0
      test/cors.reply.shtml

+ 13 - 1
src/civetweb.c

@@ -4407,6 +4407,16 @@ static void handle_ssi_file_request(struct mg_connection *conn,
     struct file file = STRUCT_FILE_INITIALIZER;
     char date[64];
     time_t curtime = time(NULL);
+    const char *cors1, *cors2, *cors3;
+
+    if (mg_get_header(conn, "Origin")) {
+        /* Cross-origin resource sharing (CORS). */
+        cors1 = "Access-Control-Allow-Origin: ";
+        cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
+        cors3 = "\r\n";
+    } else {
+        cors1 = cors2 = cors3 = "";
+    }
 
     if (!mg_fopen(conn, path, "rb", &file)) {
         send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
@@ -4416,10 +4426,12 @@ static void handle_ssi_file_request(struct mg_connection *conn,
         gmt_time_string(date, sizeof(date), &curtime);
         fclose_on_exec(&file, conn);
         mg_printf(conn, "HTTP/1.1 200 OK\r\n"
+                        "%s%s%s"
                         "Date: %s\r\n"
                         "Content-Type: text/html\r\n"
                         "Connection: %s\r\n\r\n",
-                  date, suggest_connection_header(conn));
+                        cors1, cors2, cors3,
+                        date, suggest_connection_header(conn));
         send_ssi_file(conn, path, &file, 0);
         mg_fclose(&file);
     }

+ 1 - 0
test/cors.html

@@ -67,6 +67,7 @@ function start() {
  <h1>Cross-origin resource sharing test</h1>
  <p id="from">*** Error: Javascript is not activated. This test will not work. ***</p>
  <button onclick="makeCorsRequest('GET', 'html')">Run CORS GET request (static resource)</button>
+ <button onclick="makeCorsRequest('GET', 'shtml')">Run CORS GET request (ssi)</button>
  <button onclick="makeCorsRequest('GET', 'lua/getit')">Run CORS GET request (dynamic resource)</button>
  <button onclick="makeCorsRequest('PUT', 'lua/putit')">Run CORS PUT request (dynamic resource)</button>
  <p>More information on CORS: See <a href="http://enable-cors.org/">enable-cors.org</a> and <a href="http://www.html5rocks.com/en/tutorials/cors/">html5rocks.com</a>.</p>

+ 7 - 0
test/cors.reply.shtml

@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<html>
+<head><title>CORS test reply - test OK</title></head>
+<body>
+Do not load this page directly - use cors.html instead!
+</body>
+</html>