ubus: add CORS header support
authorJo-Philipp Wich <jow@openwrt.org>
Tue, 27 May 2014 12:40:58 +0000 (14:40 +0200)
committerJo-Philipp Wich <jow@openwrt.org>
Tue, 10 Jun 2014 10:33:59 +0000 (12:33 +0200)
In order to support cross-domain AJAX requests to the /ubus endpoint
we need to implement the Cross-Origin Resource Sharing (CORS) spec
in the ubus plugin.

- Implement a new option "-X" to enable CORS support in ubus
- Implement rudimentary support for "OPTIONS" HTTP requests
- Implement essential CORS headers the ubus plugin

The current CORS response headers merely reflect the request headers
sent by the client, this way any requesting origin is automatically
allowed. Cross-domain cookies (Access-Control-Allow-Credentials) are
unconditionally enabled.

Restricting permitted origins and toggle the credential accepting can
be made configurable in a future commit to allow more fine grained
control over permitted AJAX clients.

Signed-off-by: Jo-Philipp Wich <jow@openwrt.org>
client.c
main.c
ubus.c
uhttpd.h
utils.c

index 3a6b09eea20b36b23cf59c05714c55f85fc18b6f..9b8fb07025037a30c52548f1e006bb4042a01c81 100644 (file)
--- a/client.c
+++ b/client.c
@@ -39,6 +39,7 @@ const char * const http_methods[] = {
        [UH_HTTP_MSG_GET] = "GET",
        [UH_HTTP_MSG_POST] = "POST",
        [UH_HTTP_MSG_HEAD] = "HEAD",
+       [UH_HTTP_MSG_OPTIONS] = "OPTIONS",
 };
 
 void uh_http_header(struct client *cl, int code, const char *summary)
diff --git a/main.c b/main.c
index e89a99a765240d06a7485ada879f87bc8a25c81c..44c3226bff93a8c3ac647488585e36b2b9c00697 100644 (file)
--- a/main.c
+++ b/main.c
@@ -151,6 +151,7 @@ static int usage(const char *name)
                "       -u string       URL prefix for UBUS via JSON-RPC handler\n"
                "       -U file         Override ubus socket path\n"
                "       -a              Do not authenticate JSON-RPC requests against UBUS session api\n"
+               "       -X              Enable CORS HTTP headers on JSON-RPC api\n"
 #endif
                "       -x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
                "       -i .ext=path    Use interpreter at path for files with the given extension\n"
@@ -226,7 +227,7 @@ int main(int argc, char **argv)
        init_defaults_pre();
        signal(SIGPIPE, SIG_IGN);
 
-       while ((ch = getopt(argc, argv, "afSDRC:K:E:I:p:s:h:c:l:L:d:r:m:n:N:x:i:t:k:T:A:u:U:")) != -1) {
+       while ((ch = getopt(argc, argv, "afSDRXC:K:E:I:p:s:h:c:l:L:d:r:m:n:N:x:i:t:k:T:A:u:U:")) != -1) {
                switch(ch) {
 #ifdef HAVE_TLS
                case 'C':
@@ -402,10 +403,15 @@ int main(int argc, char **argv)
                case 'U':
                        conf.ubus_socket = optarg;
                        break;
+
+               case 'X':
+                       conf.ubus_cors = 1;
+                       break;
 #else
                case 'a':
                case 'u':
                case 'U':
+               case 'X':
                        fprintf(stderr, "uhttpd: UBUS support not compiled, "
                                        "ignoring -%c\n", opt);
                        break;
diff --git a/ubus.c b/ubus.c
index 39dca359028c453191def2323967b922663f7319..269f7cdf85ed7195964399e9449cd97a65a9c595 100644 (file)
--- a/ubus.c
+++ b/ubus.c
@@ -104,6 +104,13 @@ static const struct {
        [ERROR_TIMEOUT] = { -32003, "ubus request timed out" },
 };
 
+enum cors_hdr {
+       HDR_ORIGIN,
+       HDR_ACCESS_CONTROL_REQUEST_METHOD,
+       HDR_ACCESS_CONTROL_REQUEST_HEADERS,
+       __HDR_MAX
+};
+
 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout);
 
 static void uh_ubus_next_batched_request(struct client *cl)
@@ -114,10 +121,52 @@ static void uh_ubus_next_batched_request(struct client *cl)
        uloop_timeout_set(&du->timeout, 1);
 }
 
+static void uh_ubus_add_cors_headers(struct client *cl)
+{
+       struct blob_attr *tb[__HDR_MAX];
+       static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
+               [HDR_ORIGIN] = { "origin", BLOBMSG_TYPE_STRING },
+               [HDR_ACCESS_CONTROL_REQUEST_METHOD] = { "access-control-request-method", BLOBMSG_TYPE_STRING },
+               [HDR_ACCESS_CONTROL_REQUEST_HEADERS] = { "access-control-request-headers", BLOBMSG_TYPE_STRING },
+       };
+
+       blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
+
+       if (!tb[HDR_ORIGIN])
+               return;
+
+       if (tb[HDR_ACCESS_CONTROL_REQUEST_METHOD])
+       {
+               char *hdr = (char *) blobmsg_data(tb[HDR_ACCESS_CONTROL_REQUEST_METHOD]);
+
+               if (strcmp(hdr, "POST") && strcmp(hdr, "OPTIONS"))
+                       return;
+       }
+
+       ustream_printf(cl->us, "Access-Control-Allow-Origin: %s\r\n",
+                      blobmsg_data(tb[HDR_ORIGIN]));
+
+       if (tb[HDR_ACCESS_CONTROL_REQUEST_HEADERS])
+               ustream_printf(cl->us, "Access-Control-Allow-Headers: %s\r\n",
+                              blobmsg_data(tb[HDR_ACCESS_CONTROL_REQUEST_HEADERS]));
+
+       ustream_printf(cl->us, "Access-Control-Allow-Methods: POST, OPTIONS\r\n");
+       ustream_printf(cl->us, "Access-Control-Allow-Credentials: true\r\n");
+}
+
 static void uh_ubus_send_header(struct client *cl)
 {
        ops->http_header(cl, 200, "OK");
-       ustream_printf(cl->us, "Content-Type: application/json\r\n\r\n");
+
+       if (conf.ubus_cors)
+               uh_ubus_add_cors_headers(cl);
+
+       ustream_printf(cl->us, "Content-Type: application/json\r\n");
+
+       if (cl->request.method == UH_HTTP_MSG_OPTIONS)
+               ustream_printf(cl->us, "Content-Length: 0\r\n");
+
+       ustream_printf(cl->us, "\r\n");
 }
 
 static void uh_ubus_send_response(struct client *cl)
@@ -571,14 +620,24 @@ static void uh_ubus_handle_request(struct client *cl, char *url, struct path_inf
 
        blob_buf_init(&buf, 0);
 
-       if (cl->request.method != UH_HTTP_MSG_POST)
-               return ops->client_error(cl, 400, "Bad Request", "Invalid Request");
+       switch (cl->request.method)
+       {
+       case UH_HTTP_MSG_POST:
+               d->data_send = uh_ubus_data_send;
+               d->data_done = uh_ubus_data_done;
+               d->close_fds = uh_ubus_close_fds;
+               d->free = uh_ubus_request_free;
+               d->ubus.jstok = json_tokener_new();
+               break;
+
+       case UH_HTTP_MSG_OPTIONS:
+               uh_ubus_send_header(cl);
+               ops->request_done(cl);
+               break;
 
-       d->close_fds = uh_ubus_close_fds;
-       d->free = uh_ubus_request_free;
-       d->data_send = uh_ubus_data_send;
-       d->data_done = uh_ubus_data_done;
-       d->ubus.jstok = json_tokener_new();
+       default:
+               ops->client_error(cl, 400, "Bad Request", "Invalid Request");
+       }
 }
 
 static bool
index daf68cecb39b9dbebffb547ecb20b0897ea4ede9..6ef28d922a5f2f90842149387528addd6a1e15db 100644 (file)
--- a/uhttpd.h
+++ b/uhttpd.h
@@ -68,6 +68,7 @@ struct config {
        int http_keepalive;
        int script_timeout;
        int ubus_noauth;
+       int ubus_cors;
 };
 
 struct auth_realm {
@@ -81,6 +82,7 @@ enum http_method {
        UH_HTTP_MSG_GET,
        UH_HTTP_MSG_POST,
        UH_HTTP_MSG_HEAD,
+       UH_HTTP_MSG_OPTIONS,
 };
 
 enum http_version {
diff --git a/utils.c b/utils.c
index b1d7d37c68cd311525b35d650133590a6493f464..1c21fc56eaddc555aac290000042ed2731411c4a 100644 (file)
--- a/utils.c
+++ b/utils.c
@@ -25,7 +25,7 @@ bool uh_use_chunked(struct client *cl)
        if (cl->request.version != UH_HTTP_VER_1_1)
                return false;
 
-       if (cl->request.method == UH_HTTP_MSG_HEAD)
+       if (cl->request.method == UH_HTTP_MSG_HEAD || cl->request.method == UH_HTTP_MSG_OPTIONS)
                return false;
 
        return true;