better handling of lengths
[src/app-framework-binder.git] / src / afb-hreq.c
index 00c27eb..2e74f2d 100644 (file)
@@ -15,7 +15,6 @@
  * limitations under the License.
  */
 
-#define USE_MAGIC_MIME_TYPE
 #define _GNU_SOURCE
 
 #include <stdlib.h>
 
 #include "afb-method.h"
 #include "afb-req-itf.h"
+#include "afb-msg-json.h"
 #include "afb-hreq.h"
 #include "session.h"
 #include "verbose.h"
 
-#define SIZE_RESPONSE_BUFFER   8000
+#define SIZE_RESPONSE_BUFFER   8192
 
 static char empty_string[] = "";
 
@@ -51,6 +51,9 @@ static const char token_header[] = "x-afb-token";
 static const char token_arg[] = "token";
 static const char token_cookie[] = "token";
 
+static char *cookie_name = NULL;
+static char *cookie_setter = NULL;
+static char *tmp_pattern = NULL;
 
 struct hreq_data {
        struct hreq_data *next;
@@ -79,7 +82,9 @@ static const struct afb_req_itf afb_hreq_itf = {
        .send = (void*)req_send,
        .session_create = (void*)req_session_create,
        .session_check = (void*)req_session_check,
-       .session_close = (void*)req_session_close
+       .session_close = (void*)req_session_close,
+       .context_get = (void*)afb_context_get,
+       .context_set = (void*)afb_context_set
 };
 
 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
@@ -143,6 +148,64 @@ static int validsubpath(const char *subpath)
        return 1;
 }
 
+static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
+{
+       char *cookie;
+       const char *k, *v;
+       k = va_arg(args, const char *);
+       while (k != NULL) {
+               v = va_arg(args, const char *);
+               MHD_add_response_header(response, k, v);
+               k = va_arg(args, const char *);
+       }
+       if (hreq->context != NULL && asprintf(&cookie, cookie_setter, hreq->context->uuid)) {
+               MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
+               free(cookie);
+       }
+       MHD_queue_response(hreq->connection, status, response);
+       MHD_destroy_response(response);
+}
+
+void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
+{
+       va_list args;
+       va_start(args, response);
+       afb_hreq_reply_v(hreq, status, response, args);
+       va_end(args);
+}
+
+void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
+{
+       va_list args;
+       va_start(args, status);
+       afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
+       va_end(args);
+}
+
+void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
+{
+       va_list args;
+       va_start(args, buffer);
+       afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_PERSISTENT), args);
+       va_end(args);
+}
+
+void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
+{
+       va_list args;
+       va_start(args, buffer);
+       afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_COPY), args);
+       va_end(args);
+}
+
+void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
+{
+       va_list args;
+       va_start(args, buffer);
+       afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
+       va_end(args);
+}
+
 #if defined(USE_MAGIC_MIME_TYPE)
 
 #if !defined(MAGIC_DB)
@@ -159,7 +222,7 @@ static magic_t lazy_libmagic()
                /* MAGIC_MIME tells magic to return a mime of the file,
                         but you can specify different things */
                if (verbosity)
-                       printf("Loading mimetype default magic database\n");
+                       fprintf(stderr, "Loading mimetype default magic database\n");
 
                result = magic_open(MAGIC_MIME_TYPE);
                if (result == NULL) {
@@ -194,8 +257,9 @@ static const char *mimetype_fd_name(int fd, const char *filename)
        const char *extension = strrchr(filename, '.');
        if (extension) {
                static const char *const known[][2] = {
-                       { ".js", "text/javascript" },
+                       { ".js",   "text/javascript" },
                        { ".html", "text/html" },
+                       { ".css",  "text/css" },
                        { NULL, NULL }
                };
                int i = 0;
@@ -223,11 +287,16 @@ void afb_hreq_free(struct afb_hreq *hreq)
                        MHD_destroy_post_processor(hreq->postform);
                for (data = hreq->data; data; data = hreq->data) {
                        hreq->data = data->next;
+                       if (data->path) {
+                               unlink(data->path);
+                               free(data->path);
+                       }
                        free(data->key);
                        free(data->value);
                        free(data);
                }
                ctxClientPut(hreq->context);
+               json_object_put(hreq->json);
                free(hreq);
        }
 }
@@ -261,20 +330,7 @@ int afb_hreq_valid_tail(struct afb_hreq *hreq)
 
 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
 {
-       char *buffer;
-       int length;
-       struct MHD_Response *response;
-
-       length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
-       if (length > 0)
-               response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
-       else {
-               buffer = "<html><body>error</body></html>";
-               response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
-       }
-       if (!MHD_queue_response(hreq->connection, status, response))
-               fprintf(stderr, "Failed to reply error code %u", status);
-       MHD_destroy_response(response);
+       afb_hreq_reply_empty(hreq, status, NULL);
 }
 
 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
@@ -382,10 +438,10 @@ int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *f
        }
 
        /* fills the value and send */
-       MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout);
-       MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
-       MHD_queue_response(hreq->connection, status, response);
-       MHD_destroy_response(response);
+       afb_hreq_reply(hreq, status, response,
+                       MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
+                       MHD_HTTP_HEADER_ETAG, etag,
+                       NULL);
        return 1;
 }
 
@@ -399,12 +455,8 @@ int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
 
 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
 {
-       struct MHD_Response *response;
-
-       response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
-       MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
-       MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
-       MHD_destroy_response(response);
+       afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
+                       MHD_HTTP_HEADER_LOCATION, url, NULL);
        if (verbosity)
                fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
        return 1;
@@ -444,12 +496,53 @@ int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data,
        return 1;
 }
 
+int afb_hreq_init_download_path(const char *directory)
+{
+       struct stat st;
+       size_t n;
+       char *p;
+
+       if (access(directory, R_OK|W_OK)) {
+               /* no read/write access */
+               return -1;
+       }
+       if (stat(directory, &st)) {
+               /* can't get info */
+               return -1;
+       }
+       if (!S_ISDIR(st.st_mode)) {
+               /* not a directory */
+               errno = ENOTDIR;
+               return -1;
+       }
+       n = strlen(directory);
+       while(n > 1 && directory[n-1] == '/') n--;
+       p = malloc(n + 8);
+       if (p == NULL) {
+               /* can't allocate memory */
+               errno = ENOMEM;
+               return -1;
+       }
+       memcpy(p, directory, n);
+       p[n++] = '/';
+       p[n++] = 'X';
+       p[n++] = 'X';
+       p[n++] = 'X';
+       p[n++] = 'X';
+       p[n++] = 'X';
+       p[n++] = 'X';
+       p[n] = 0;
+       free(tmp_pattern);
+       tmp_pattern = p;
+       return 0;
+}
+
 static int opentempfile(char **path)
 {
        int fd;
        char *fname;
 
-       fname = strdup("XXXXXX"); /* TODO improve the path */
+       fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
        if (fname == NULL)
                return -1;
 
@@ -494,7 +587,7 @@ int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *f
 
 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
 {
-       return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
+       return (struct afb_req){ .itf = &afb_hreq_itf, .req_closure = hreq };
 }
 
 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
@@ -558,39 +651,30 @@ static const char *req_raw(struct afb_hreq *hreq, size_t *size)
 
 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
 {
-       struct MHD_Response *response = MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE);
-       MHD_queue_response(hreq->connection, MHD_HTTP_OK, response);
-       MHD_destroy_response(response);
+       afb_hreq_reply_free(hreq, MHD_HTTP_OK, size, buffer, NULL);
 }
 
 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
 {
        ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
-       return len ? : -1;
+       return len ? : MHD_CONTENT_READER_END_OF_STREAM;
 }
 
 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
 {
-       json_object *root, *request;
+       struct json_object *reply;
+       const char *token, *uuid;
        struct MHD_Response *response;
 
-       root = json_object_new_object();
-       json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
-       request = json_object_new_object();
-       json_object_object_add(root, "request", request);
-       json_object_object_add(request, "status", json_object_new_string(status));
-       if (info)
-               json_object_object_add(request, "info", json_object_new_string(info));
-       if (resp)
-               json_object_object_add(root, "response", resp);
-       if (hreq->context) {
-               json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
-               json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
+       if (hreq->context == NULL) {
+               token = uuid = NULL;
+       } else {
+               token = hreq->context->token;
+               uuid = hreq->context->uuid;
        }
-
-       response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
-       MHD_queue_response(hreq->connection, retcode, response);
-       MHD_destroy_response(response);
+       reply = afb_msg_json_reply(status, info, resp, token, uuid);
+       response = MHD_create_response_from_callback((uint64_t)strlen(json_object_to_json_string(reply)), SIZE_RESPONSE_BUFFER, (void*)send_json_cb, reply, (void*)json_object_put);
+       afb_hreq_reply(hreq, retcode, response, NULL);
 }
 
 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
@@ -612,7 +696,7 @@ struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
                if (uuid == NULL)
                        uuid = afb_hreq_get_argument(hreq, uuid_arg);
                if (uuid == NULL)
-                       uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
+                       uuid = afb_hreq_get_cookie(hreq, cookie_name);
                hreq->context = ctxClientGetForUuid(uuid);
        }
        return hreq->context;
@@ -662,5 +746,24 @@ static void req_session_close(struct afb_hreq *hreq)
                ctxClientClose(context);
 }
 
+int afb_hreq_init_cookie(int port, const char *path, int maxage)
+{
+       int rc;
+
+       free(cookie_name);
+       free(cookie_setter);
+       cookie_name = NULL;
+       cookie_setter = NULL;
+
+       path = path ? : "/";
+       rc = asprintf(&cookie_name, "x-afb-uuid-%d", port);
+       if (rc < 0)
+               return 0;
+       rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
+                       cookie_name, path, maxage);
+       if (rc < 0)
+               return 0;
+       return 1;
+}