2 * Copyright 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>
31 #if defined(USE_MAGIC_MIME_TYPE)
35 #include "afb-method.h"
36 #include "afb-req-itf.h"
37 #include "afb-msg-json.h"
42 #define SIZE_RESPONSE_BUFFER 8000
44 static char empty_string[] = "";
46 static const char uuid_header[] = "x-afb-uuid";
47 static const char uuid_arg[] = "uuid";
48 static const char uuid_cookie[] = "uuid";
50 static const char token_header[] = "x-afb-token";
51 static const char token_arg[] = "token";
52 static const char token_cookie[] = "token";
54 static char *cookie_name = NULL;
55 static char *cookie_setter = NULL;
56 static char *tmp_pattern = NULL;
59 struct hreq_data *next;
66 static struct json_object *req_json(struct afb_hreq *hreq);
67 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
68 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
69 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
70 static const char *req_raw(struct afb_hreq *hreq, size_t *size);
71 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size);
72 static int req_session_create(struct afb_hreq *hreq);
73 static int req_session_check(struct afb_hreq *hreq, int refresh);
74 static void req_session_close(struct afb_hreq *hreq);
76 static const struct afb_req_itf afb_hreq_itf = {
77 .json = (void*)req_json,
78 .get = (void*)req_get,
79 .success = (void*)req_success,
80 .fail = (void*)req_fail,
81 .raw = (void*)req_raw,
82 .send = (void*)req_send,
83 .session_create = (void*)req_session_create,
84 .session_check = (void*)req_session_check,
85 .session_close = (void*)req_session_close,
86 .context_get = (void*)afb_context_get,
87 .context_set = (void*)afb_context_set
90 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
92 struct hreq_data *data = hreq->data;
93 while (data != NULL) {
94 if (!strcasecmp(data->key, key))
99 data = calloc(1, sizeof *data);
101 data->key = strdup(key);
102 if (data->key == NULL) {
106 data->next = hreq->data;
114 /* a valid subpath is a relative path not looking deeper than root using .. */
115 static int validsubpath(const char *subpath)
120 switch (subpath[i++]) {
124 if (subpath[i] == '/') {
128 if (subpath[i++] == '.') {
134 if (subpath[i++] == '/') {
141 while (subpath[i] && subpath[i] != '/')
151 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
155 k = va_arg(args, const char *);
157 v = va_arg(args, const char *);
158 MHD_add_response_header(response, k, v);
159 k = va_arg(args, const char *);
161 if (hreq->context != NULL && asprintf(&cookie, cookie_setter, hreq->context->uuid)) {
162 MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
165 MHD_queue_response(hreq->connection, status, response);
166 MHD_destroy_response(response);
169 void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
172 va_start(args, response);
173 afb_hreq_reply_v(hreq, status, response, args);
177 void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
180 va_start(args, status);
181 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
185 void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
188 va_start(args, buffer);
189 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_PERSISTENT), args);
193 void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
196 va_start(args, buffer);
197 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_COPY), args);
201 void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
204 va_start(args, buffer);
205 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
209 #if defined(USE_MAGIC_MIME_TYPE)
211 #if !defined(MAGIC_DB)
212 #define MAGIC_DB "/usr/share/misc/magic.mgc"
215 static magic_t lazy_libmagic()
218 static magic_t result = NULL;
222 /* MAGIC_MIME tells magic to return a mime of the file,
223 but you can specify different things */
225 fprintf(stderr, "Loading mimetype default magic database\n");
227 result = magic_open(MAGIC_MIME_TYPE);
228 if (result == NULL) {
229 fprintf(stderr,"ERROR: unable to initialize magic library\n");
231 /* Warning: should not use NULL for DB
232 [libmagic bug wont pass efence check] */
233 else if (magic_load(result, MAGIC_DB) != 0) {
234 fprintf(stderr,"cannot load magic database - %s\n",
235 magic_error(result));
244 static const char *magic_mimetype_fd(int fd)
246 magic_t lib = lazy_libmagic();
247 return lib ? magic_descriptor(lib, fd) : NULL;
252 static const char *mimetype_fd_name(int fd, const char *filename)
254 const char *result = NULL;
256 #if defined(INFER_EXTENSION)
257 const char *extension = strrchr(filename, '.');
259 static const char *const known[][2] = {
260 { ".js", "text/javascript" },
261 { ".html", "text/html" },
262 { ".css", "text/css" },
266 while (known[i][0]) {
267 if (!strcasecmp(extension, known[i][0])) {
268 result = known[i][1];
275 #if defined(USE_MAGIC_MIME_TYPE)
277 result = magic_mimetype_fd(fd);
282 void afb_hreq_free(struct afb_hreq *hreq)
284 struct hreq_data *data;
286 if (hreq->postform != NULL)
287 MHD_destroy_post_processor(hreq->postform);
288 for (data = hreq->data; data; data = hreq->data) {
289 hreq->data = data->next;
298 ctxClientPut(hreq->context);
299 json_object_put(hreq->json);
305 * Removes the 'prefix' of 'length' from the tail of 'hreq'
306 * if and only if the prefix exists and is terminated by a leading
309 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
311 /* check the prefix ? */
312 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
313 || strncasecmp(prefix, hreq->tail, length))
316 /* removes successives / */
317 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
320 /* update the tail */
321 hreq->lentail -= length;
322 hreq->tail += length;
326 int afb_hreq_valid_tail(struct afb_hreq *hreq)
328 return validsubpath(hreq->tail);
331 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
333 afb_hreq_reply_empty(hreq, status, NULL);
336 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
342 char etag[1 + 2 * sizeof(int)];
344 struct MHD_Response *response;
345 const char *mimetype;
347 /* Opens the file or directory */
349 fd = openat(dirfd, filename, O_RDONLY);
353 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
359 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
364 /* Retrieves file's status */
365 if (fstat(fd, &st) != 0) {
367 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
371 /* serve directory */
372 if (S_ISDIR(st.st_mode)) {
373 static const char *indexes[] = { "index.html", NULL };
376 while (indexes[i] != NULL) {
377 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
378 if (hreq->url[hreq->lenurl - 1] != '/') {
379 /* the redirect is needed for reliability of relative path */
380 char *tourl = alloca(hreq->lenurl + 2);
381 memcpy(tourl, hreq->url, hreq->lenurl);
382 tourl[hreq->lenurl] = '/';
383 tourl[hreq->lenurl + 1] = 0;
384 rc = afb_hreq_redirect_to(hreq, tourl);
386 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
396 /* Don't serve special files */
397 if (!S_ISREG(st.st_mode)) {
399 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
403 /* Check the method */
404 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
406 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
410 /* computes the etag */
411 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
413 /* checks the etag */
414 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
415 if (inm && 0 == strcmp(inm, etag)) {
416 /* etag ok, return NOT MODIFIED */
419 fprintf(stderr, "Not Modified: [%s]\n", filename);
420 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
421 status = MHD_HTTP_NOT_MODIFIED;
424 if (st.st_size != (off_t) (size_t) st.st_size) {
426 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
430 /* create the response */
431 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
432 status = MHD_HTTP_OK;
435 mimetype = mimetype_fd_name(fd, filename);
436 if (mimetype != NULL)
437 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
440 /* fills the value and send */
441 afb_hreq_reply(hreq, status, response,
442 MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
443 MHD_HTTP_HEADER_ETAG, etag,
448 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
450 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
452 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
456 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
458 afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
459 MHD_HTTP_HEADER_LOCATION, url, NULL);
461 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
465 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
467 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
470 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
472 struct hreq_data *data = get_data(hreq, name, 0);
473 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
476 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
478 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
481 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
484 struct hreq_data *hdat = get_data(hreq, key, 1);
485 if (hdat->path != NULL) {
488 p = realloc(hdat->value, hdat->length + size + 1);
493 memcpy(&hdat->value[hdat->length], data, size);
494 hdat->length += size;
495 hdat->value[hdat->length] = 0;
499 int afb_hreq_init_download_path(const char *directory)
505 if (access(directory, R_OK|W_OK)) {
506 /* no read/write access */
509 if (stat(directory, &st)) {
513 if (!S_ISDIR(st.st_mode)) {
514 /* not a directory */
518 n = strlen(directory);
519 while(n > 1 && directory[n-1] == '/') n--;
522 /* can't allocate memory */
526 memcpy(p, directory, n);
540 static int opentempfile(char **path)
545 fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
549 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
557 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
561 struct hreq_data *hdat = get_data(hreq, key, 1);
563 if (hdat->value == NULL) {
564 hdat->value = strdup(file);
565 if (hdat->value == NULL)
567 fd = opentempfile(&hdat->path);
568 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
571 fd = open(hdat->path, O_WRONLY|O_APPEND);
576 sz = write(fd, data, size);
578 hdat->length += (size_t)sz;
581 } else if (errno != EINTR)
588 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
590 return (struct afb_req){ .itf = &afb_hreq_itf, .req_closure = hreq };
593 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
595 struct hreq_data *hdat = get_data(hreq, name, 0);
597 return (struct afb_arg){
599 .value = hdat->value,
603 return (struct afb_arg){
605 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
610 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
612 json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
616 static struct json_object *req_json(struct afb_hreq *hreq)
618 struct hreq_data *hdat;
619 struct json_object *obj, *val;
623 hreq->json = obj = json_object_new_object();
626 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
627 for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
628 if (hdat->path == NULL)
629 val = hdat->value ? json_object_new_string(hdat->value) : NULL;
631 val = json_object_new_object();
634 json_object_object_add(val, "file", json_object_new_string(hdat->value));
635 json_object_object_add(val, "path", json_object_new_string(hdat->path));
638 json_object_object_add(obj, hdat->key, val);
645 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
647 const char *result = json_object_get_string(req_json(hreq));
648 *size = result ? strlen(result) : 0;
652 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
654 afb_hreq_reply_free(hreq, MHD_HTTP_OK, size, buffer, NULL);
657 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
659 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
663 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
665 struct json_object *reply;
666 const char *token, *uuid;
667 struct MHD_Response *response;
669 if (hreq->context == NULL) {
672 token = hreq->context->token;
673 uuid = hreq->context->uuid;
675 reply = afb_msg_json_reply(status, info, resp, token, uuid);
677 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, reply, (void*)json_object_put);
678 afb_hreq_reply(hreq, retcode, response, NULL);
681 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
683 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
686 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
688 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
691 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
695 if (hreq->context == NULL) {
696 uuid = afb_hreq_get_header(hreq, uuid_header);
698 uuid = afb_hreq_get_argument(hreq, uuid_arg);
700 uuid = afb_hreq_get_cookie(hreq, cookie_name);
701 hreq->context = ctxClientGetForUuid(uuid);
703 return hreq->context;
706 static int req_session_create(struct afb_hreq *hreq)
708 struct AFB_clientCtx *context = afb_hreq_context(hreq);
711 if (context->created)
713 return req_session_check(hreq, 1);
716 static int req_session_check(struct afb_hreq *hreq, int refresh)
720 struct AFB_clientCtx *context = afb_hreq_context(hreq);
725 token = afb_hreq_get_header(hreq, token_header);
727 token = afb_hreq_get_argument(hreq, token_arg);
729 token = afb_hreq_get_cookie(hreq, token_cookie);
733 if (!ctxTokenCheck (context, token))
737 ctxTokenNew (context);
743 static void req_session_close(struct afb_hreq *hreq)
745 struct AFB_clientCtx *context = afb_hreq_context(hreq);
747 ctxClientClose(context);
750 int afb_hreq_init_cookie(int port, const char *path, int maxage)
757 cookie_setter = NULL;
760 rc = asprintf(&cookie_name, "x-afb-uuid-%d", port);
763 rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
764 cookie_name, path, maxage);