2 * Copyright (C) 2016 "IoT.bzh"
3 * Author: José Bollo <jose.bollo@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
28 #include <microhttpd.h>
29 #include <json-c/json.h>
31 #if defined(USE_MAGIC_MIME_TYPE)
35 #include "afb-method.h"
36 #include <afb/afb-req-itf.h>
37 #include "afb-msg-json.h"
38 #include "afb-context.h"
43 #define SIZE_RESPONSE_BUFFER 8192
45 static char empty_string[] = "";
47 static const char key_for_uuid[] = "x-afb-uuid";
48 static const char old_key_for_uuid[] = "uuid";
50 static const char key_for_token[] = "x-afb-token";
51 static const char old_key_for_token[] = "token";
53 static char *cookie_name = NULL;
54 static char *cookie_setter = NULL;
55 static char *tmp_pattern = NULL;
58 * Structure for storing key/values read from POST requests
61 struct hreq_data *next; /* chain to next data */
62 char *key; /* key name */
63 size_t length; /* length of the value (used for appending) */
64 char *value; /* the value (or original filename) */
65 char *path; /* path of the file saved */
68 static struct json_object *req_json(struct afb_hreq *hreq);
69 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
70 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
71 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
72 static const char *req_raw(struct afb_hreq *hreq, size_t *size);
73 static void req_send(struct afb_hreq *hreq, const char *buffer, size_t size);
75 static const struct afb_req_itf afb_hreq_itf = {
76 .json = (void*)req_json,
77 .get = (void*)req_get,
78 .success = (void*)req_success,
79 .fail = (void*)req_fail,
80 .raw = (void*)req_raw,
81 .send = (void*)req_send,
82 .context_get = (void*)afb_context_get,
83 .context_set = (void*)afb_context_set,
84 .addref = (void*)afb_hreq_addref,
85 .unref = (void*)afb_hreq_unref
88 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
90 struct hreq_data *data = hreq->data;
91 while (data != NULL) {
92 if (!strcasecmp(data->key, key))
97 data = calloc(1, sizeof *data);
99 data->key = strdup(key);
100 if (data->key == NULL) {
104 data->next = hreq->data;
112 /* a valid subpath is a relative path not looking deeper than root using .. */
113 static int validsubpath(const char *subpath)
118 switch (subpath[i++]) {
122 if (subpath[i] == '/') {
126 if (subpath[i++] == '.') {
132 if (subpath[i++] == '/') {
139 while (subpath[i] && subpath[i] != '/')
149 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
154 if (hreq->replied != 0)
157 k = va_arg(args, const char *);
159 v = va_arg(args, const char *);
160 MHD_add_response_header(response, k, v);
161 k = va_arg(args, const char *);
163 v = afb_context_sent_uuid(&hreq->context);
164 if (v != NULL && asprintf(&cookie, cookie_setter, v) > 0) {
165 MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
168 MHD_queue_response(hreq->connection, status, response);
169 MHD_destroy_response(response);
172 if (hreq->suspended != 0) {
173 extern void run_micro_httpd(struct afb_hsrv *hsrv);
174 MHD_resume_connection (hreq->connection);
176 run_micro_httpd(hreq->hsrv);
180 void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
183 va_start(args, response);
184 afb_hreq_reply_v(hreq, status, response, args);
188 void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
191 va_start(args, status);
192 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
196 void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, const char *buffer, ...)
199 va_start(args, buffer);
200 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, (char*)buffer, MHD_RESPMEM_PERSISTENT), args);
204 void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, const char *buffer, ...)
207 va_start(args, buffer);
208 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, (char*)buffer, MHD_RESPMEM_MUST_COPY), args);
212 void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
215 va_start(args, buffer);
216 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
220 #if defined(USE_MAGIC_MIME_TYPE)
222 #if !defined(MAGIC_DB)
223 #define MAGIC_DB "/usr/share/misc/magic.mgc"
226 static magic_t lazy_libmagic()
229 static magic_t result = NULL;
233 /* MAGIC_MIME tells magic to return a mime of the file,
234 but you can specify different things */
235 INFO("Loading mimetype default magic database");
236 result = magic_open(MAGIC_MIME_TYPE);
237 if (result == NULL) {
238 ERROR("unable to initialize magic library");
240 /* Warning: should not use NULL for DB
241 [libmagic bug wont pass efence check] */
242 else if (magic_load(result, MAGIC_DB) != 0) {
243 ERROR("cannot load magic database: %s", magic_error(result));
252 static const char *magic_mimetype_fd(int fd)
254 magic_t lib = lazy_libmagic();
255 return lib ? magic_descriptor(lib, fd) : NULL;
260 static const char *mimetype_fd_name(int fd, const char *filename)
262 const char *result = NULL;
264 #if defined(INFER_EXTENSION)
265 const char *extension = strrchr(filename, '.');
267 static const char *const known[][2] = {
268 { ".js", "text/javascript" },
269 { ".html", "text/html" },
270 { ".css", "text/css" },
274 while (known[i][0]) {
275 if (!strcasecmp(extension, known[i][0])) {
276 result = known[i][1];
283 #if defined(USE_MAGIC_MIME_TYPE)
285 result = magic_mimetype_fd(fd);
290 void afb_hreq_addref(struct afb_hreq *hreq)
295 void afb_hreq_unref(struct afb_hreq *hreq)
297 struct hreq_data *data;
299 if (hreq == NULL || --hreq->refcount)
302 if (hreq->postform != NULL)
303 MHD_destroy_post_processor(hreq->postform);
304 for (data = hreq->data; data; data = hreq->data) {
305 hreq->data = data->next;
314 afb_context_disconnect(&hreq->context);
315 json_object_put(hreq->json);
320 * Removes the 'prefix' of 'length' from the tail of 'hreq'
321 * if and only if the prefix exists and is terminated by a leading
324 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
326 /* check the prefix ? */
327 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
328 || strncasecmp(prefix, hreq->tail, length))
331 /* removes successives / */
332 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
335 /* update the tail */
336 hreq->lentail -= length;
337 hreq->tail += length;
341 int afb_hreq_valid_tail(struct afb_hreq *hreq)
343 return validsubpath(hreq->tail);
346 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
348 afb_hreq_reply_empty(hreq, status, NULL);
351 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
357 char etag[1 + 2 * sizeof(int)];
359 struct MHD_Response *response;
360 const char *mimetype;
362 /* Opens the file or directory */
364 fd = openat(dirfd, filename, O_RDONLY);
368 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
374 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
379 /* Retrieves file's status */
380 if (fstat(fd, &st) != 0) {
382 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
386 /* serve directory */
387 if (S_ISDIR(st.st_mode)) {
388 static const char *indexes[] = { "index.html", NULL };
391 while (indexes[i] != NULL) {
392 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
393 if (hreq->url[hreq->lenurl - 1] != '/') {
394 /* the redirect is needed for reliability of relative path */
395 char *tourl = alloca(hreq->lenurl + 2);
396 memcpy(tourl, hreq->url, hreq->lenurl);
397 tourl[hreq->lenurl] = '/';
398 tourl[hreq->lenurl + 1] = 0;
399 rc = afb_hreq_redirect_to(hreq, tourl);
401 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
411 /* Don't serve special files */
412 if (!S_ISREG(st.st_mode)) {
414 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
418 /* Check the method */
419 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
421 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
425 /* computes the etag */
426 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
428 /* checks the etag */
429 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
430 if (inm && 0 == strcmp(inm, etag)) {
431 /* etag ok, return NOT MODIFIED */
433 DEBUG("Not Modified: [%s]", filename);
434 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
435 status = MHD_HTTP_NOT_MODIFIED;
438 if (st.st_size != (off_t) (size_t) st.st_size) {
440 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
444 /* create the response */
445 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
446 status = MHD_HTTP_OK;
449 mimetype = mimetype_fd_name(fd, filename);
450 if (mimetype != NULL)
451 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
454 /* fills the value and send */
455 afb_hreq_reply(hreq, status, response,
456 MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
457 MHD_HTTP_HEADER_ETAG, etag,
462 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
464 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
466 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
470 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
472 /* TODO: append the query part! */
473 afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
474 MHD_HTTP_HEADER_LOCATION, url, NULL);
475 DEBUG("redirect from [%s] to [%s]", hreq->url, url);
479 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
481 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
484 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
486 struct hreq_data *data = get_data(hreq, name, 0);
487 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
490 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
492 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
495 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
498 struct hreq_data *hdat = get_data(hreq, key, 1);
499 if (hdat->path != NULL) {
502 p = realloc(hdat->value, hdat->length + size + 1);
507 memcpy(&hdat->value[hdat->length], data, size);
508 hdat->length += size;
509 hdat->value[hdat->length] = 0;
513 int afb_hreq_init_download_path(const char *directory)
519 if (access(directory, R_OK|W_OK)) {
520 /* no read/write access */
523 if (stat(directory, &st)) {
527 if (!S_ISDIR(st.st_mode)) {
528 /* not a directory */
532 n = strlen(directory);
533 while(n > 1 && directory[n-1] == '/') n--;
536 /* can't allocate memory */
540 memcpy(p, directory, n);
554 static int opentempfile(char **path)
559 fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
563 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
571 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
575 struct hreq_data *hdat = get_data(hreq, key, 1);
577 if (hdat->value == NULL) {
578 hdat->value = strdup(file);
579 if (hdat->value == NULL)
581 fd = opentempfile(&hdat->path);
582 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
585 fd = open(hdat->path, O_WRONLY|O_APPEND);
590 sz = write(fd, data, size);
592 hdat->length += (size_t)sz;
595 } else if (errno != EINTR)
602 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
604 return (struct afb_req){ .itf = &afb_hreq_itf, .closure = hreq };
607 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
609 struct hreq_data *hdat = get_data(hreq, name, 0);
611 return (struct afb_arg){
613 .value = hdat->value,
617 return (struct afb_arg){
619 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
624 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
626 json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
630 static struct json_object *req_json(struct afb_hreq *hreq)
632 struct hreq_data *hdat;
633 struct json_object *obj, *val;
637 hreq->json = obj = json_object_new_object();
640 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
641 for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
642 if (hdat->path == NULL)
643 val = hdat->value ? json_object_new_string(hdat->value) : NULL;
645 val = json_object_new_object();
648 json_object_object_add(val, "file", json_object_new_string(hdat->value));
649 json_object_object_add(val, "path", json_object_new_string(hdat->path));
652 json_object_object_add(obj, hdat->key, val);
659 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
661 const char *result = json_object_get_string(req_json(hreq));
662 *size = result ? strlen(result) : 0;
666 static void req_send(struct afb_hreq *hreq, const char *buffer, size_t size)
668 afb_hreq_reply_copy(hreq, MHD_HTTP_OK, size, buffer, NULL);
671 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
673 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
674 return len ? : (ssize_t)MHD_CONTENT_READER_END_OF_STREAM;
677 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
679 struct json_object *reply;
680 const char *token, *uuid;
681 struct MHD_Response *response;
683 token = afb_context_sent_token(&hreq->context);
684 uuid = afb_context_sent_uuid(&hreq->context);
686 reply = afb_msg_json_reply(status, info, resp, token, uuid);
687 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);
688 afb_hreq_reply(hreq, retcode, response, NULL);
691 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
693 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
696 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
698 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
701 int afb_hreq_init_context(struct afb_hreq *hreq)
706 if (hreq->context.session != NULL)
709 uuid = afb_hreq_get_header(hreq, key_for_uuid);
711 uuid = afb_hreq_get_argument(hreq, key_for_uuid);
713 uuid = afb_hreq_get_cookie(hreq, cookie_name);
715 uuid = afb_hreq_get_argument(hreq, old_key_for_uuid);
717 token = afb_hreq_get_header(hreq, key_for_token);
719 token = afb_hreq_get_argument(hreq, key_for_token);
721 token = afb_hreq_get_argument(hreq, old_key_for_token);
723 return afb_context_connect(&hreq->context, uuid, token);
726 int afb_hreq_init_cookie(int port, const char *path, int maxage)
733 cookie_setter = NULL;
736 rc = asprintf(&cookie_name, "%s-%d", key_for_uuid, port);
739 rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
740 cookie_name, path, maxage);