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.
18 #define USE_MAGIC_MIME_TYPE
29 #include <microhttpd.h>
32 #if defined(USE_MAGIC_MIME_TYPE)
36 #include "afb-method.h"
37 #include "afb-req-itf.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;
58 struct hreq_data *next;
65 static struct json_object *req_json(struct afb_hreq *hreq);
66 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
67 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
68 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
69 static const char *req_raw(struct afb_hreq *hreq, size_t *size);
70 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size);
71 static int req_session_create(struct afb_hreq *hreq);
72 static int req_session_check(struct afb_hreq *hreq, int refresh);
73 static void req_session_close(struct afb_hreq *hreq);
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 .session_create = (void*)req_session_create,
83 .session_check = (void*)req_session_check,
84 .session_close = (void*)req_session_close
87 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
89 struct hreq_data *data = hreq->data;
90 while (data != NULL) {
91 if (!strcasecmp(data->key, key))
96 data = calloc(1, sizeof *data);
98 data->key = strdup(key);
99 if (data->key == NULL) {
103 data->next = hreq->data;
111 /* a valid subpath is a relative path not looking deeper than root using .. */
112 static int validsubpath(const char *subpath)
117 switch (subpath[i++]) {
121 if (subpath[i] == '/') {
125 if (subpath[i++] == '.') {
131 if (subpath[i++] == '/') {
138 while (subpath[i] && subpath[i] != '/')
148 #if defined(USE_MAGIC_MIME_TYPE)
150 #if !defined(MAGIC_DB)
151 #define MAGIC_DB "/usr/share/misc/magic.mgc"
154 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
158 k = va_arg(args, const char *);
160 v = va_arg(args, const char *);
161 MHD_add_response_header(response, k, v);
162 k = va_arg(args, const char *);
164 if (hreq->context != NULL && asprintf(&cookie, cookie_setter, hreq->context->uuid)) {
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 void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
175 va_start(args, response);
176 afb_hreq_reply_v(hreq, status, response, args);
180 void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
183 va_start(args, status);
184 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
188 void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
191 va_start(args, buffer);
192 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_PERSISTENT), args);
196 void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
199 va_start(args, buffer);
200 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_COPY), args);
204 void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
207 va_start(args, buffer);
208 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
212 static magic_t lazy_libmagic()
215 static magic_t result = NULL;
219 /* MAGIC_MIME tells magic to return a mime of the file,
220 but you can specify different things */
222 fprintf(stderr, "Loading mimetype default magic database\n");
224 result = magic_open(MAGIC_MIME_TYPE);
225 if (result == NULL) {
226 fprintf(stderr,"ERROR: unable to initialize magic library\n");
228 /* Warning: should not use NULL for DB
229 [libmagic bug wont pass efence check] */
230 else if (magic_load(result, MAGIC_DB) != 0) {
231 fprintf(stderr,"cannot load magic database - %s\n",
232 magic_error(result));
241 static const char *magic_mimetype_fd(int fd)
243 magic_t lib = lazy_libmagic();
244 return lib ? magic_descriptor(lib, fd) : NULL;
249 static const char *mimetype_fd_name(int fd, const char *filename)
251 const char *result = NULL;
253 #if defined(INFER_EXTENSION)
254 const char *extension = strrchr(filename, '.');
256 static const char *const known[][2] = {
257 { ".js", "text/javascript" },
258 { ".html", "text/html" },
262 while (known[i][0]) {
263 if (!strcasecmp(extension, known[i][0])) {
264 result = known[i][1];
271 #if defined(USE_MAGIC_MIME_TYPE)
273 result = magic_mimetype_fd(fd);
278 void afb_hreq_free(struct afb_hreq *hreq)
280 struct hreq_data *data;
282 if (hreq->postform != NULL)
283 MHD_destroy_post_processor(hreq->postform);
284 for (data = hreq->data; data; data = hreq->data) {
285 hreq->data = data->next;
294 ctxClientPut(hreq->context);
295 json_object_put(hreq->json);
301 * Removes the 'prefix' of 'length' from the tail of 'hreq'
302 * if and only if the prefix exists and is terminated by a leading
305 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
307 /* check the prefix ? */
308 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
309 || strncasecmp(prefix, hreq->tail, length))
312 /* removes successives / */
313 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
316 /* update the tail */
317 hreq->lentail -= length;
318 hreq->tail += length;
322 int afb_hreq_valid_tail(struct afb_hreq *hreq)
324 return validsubpath(hreq->tail);
327 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
329 afb_hreq_reply_empty(hreq, status, NULL);
332 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
338 char etag[1 + 2 * sizeof(int)];
340 struct MHD_Response *response;
341 const char *mimetype;
343 /* Opens the file or directory */
345 fd = openat(dirfd, filename, O_RDONLY);
349 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
355 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
360 /* Retrieves file's status */
361 if (fstat(fd, &st) != 0) {
363 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
367 /* serve directory */
368 if (S_ISDIR(st.st_mode)) {
369 static const char *indexes[] = { "index.html", NULL };
372 while (indexes[i] != NULL) {
373 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
374 if (hreq->url[hreq->lenurl - 1] != '/') {
375 /* the redirect is needed for reliability of relative path */
376 char *tourl = alloca(hreq->lenurl + 2);
377 memcpy(tourl, hreq->url, hreq->lenurl);
378 tourl[hreq->lenurl] = '/';
379 tourl[hreq->lenurl + 1] = 0;
380 rc = afb_hreq_redirect_to(hreq, tourl);
382 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
392 /* Don't serve special files */
393 if (!S_ISREG(st.st_mode)) {
395 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
399 /* Check the method */
400 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
402 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
406 /* computes the etag */
407 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
409 /* checks the etag */
410 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
411 if (inm && 0 == strcmp(inm, etag)) {
412 /* etag ok, return NOT MODIFIED */
415 fprintf(stderr, "Not Modified: [%s]\n", filename);
416 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
417 status = MHD_HTTP_NOT_MODIFIED;
420 if (st.st_size != (off_t) (size_t) st.st_size) {
422 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
426 /* create the response */
427 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
428 status = MHD_HTTP_OK;
431 mimetype = mimetype_fd_name(fd, filename);
432 if (mimetype != NULL)
433 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
436 /* fills the value and send */
437 afb_hreq_reply(hreq, status, response,
438 MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
439 MHD_HTTP_HEADER_ETAG, etag,
444 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
446 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
448 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
452 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
454 afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
455 MHD_HTTP_HEADER_LOCATION, url, NULL);
457 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
461 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
463 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
466 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
468 struct hreq_data *data = get_data(hreq, name, 0);
469 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
472 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
474 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
477 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
480 struct hreq_data *hdat = get_data(hreq, key, 1);
481 if (hdat->path != NULL) {
484 p = realloc(hdat->value, hdat->length + size + 1);
489 memcpy(&hdat->value[hdat->length], data, size);
490 hdat->length += size;
491 hdat->value[hdat->length] = 0;
495 static int opentempfile(char **path)
500 fname = strdup("XXXXXX"); /* TODO improve the path */
504 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
512 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
516 struct hreq_data *hdat = get_data(hreq, key, 1);
518 if (hdat->value == NULL) {
519 hdat->value = strdup(file);
520 if (hdat->value == NULL)
522 fd = opentempfile(&hdat->path);
523 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
526 fd = open(hdat->path, O_WRONLY|O_APPEND);
531 sz = write(fd, data, size);
533 hdat->length += (size_t)sz;
536 } else if (errno != EINTR)
543 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
545 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
548 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
550 struct hreq_data *hdat = get_data(hreq, name, 0);
552 return (struct afb_arg){
554 .value = hdat->value,
558 return (struct afb_arg){
560 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
565 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
567 json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
571 static struct json_object *req_json(struct afb_hreq *hreq)
573 struct hreq_data *hdat;
574 struct json_object *obj, *val;
578 hreq->json = obj = json_object_new_object();
581 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
582 for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
583 if (hdat->path == NULL)
584 val = hdat->value ? json_object_new_string(hdat->value) : NULL;
586 val = json_object_new_object();
589 json_object_object_add(val, "file", json_object_new_string(hdat->value));
590 json_object_object_add(val, "path", json_object_new_string(hdat->path));
593 json_object_object_add(obj, hdat->key, val);
600 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
602 const char *result = json_object_get_string(req_json(hreq));
603 *size = result ? strlen(result) : 0;
607 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
609 afb_hreq_reply_free(hreq, MHD_HTTP_OK, size, buffer, NULL);
612 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
614 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
618 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
620 json_object *root, *request;
621 struct MHD_Response *response;
623 root = json_object_new_object();
624 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
625 request = json_object_new_object();
626 json_object_object_add(root, "request", request);
627 json_object_object_add(request, "status", json_object_new_string(status));
629 json_object_object_add(request, "info", json_object_new_string(info));
631 json_object_object_add(root, "response", resp);
633 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
634 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
637 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
638 afb_hreq_reply(hreq, retcode, response, NULL);
641 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
643 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
646 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
648 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
651 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
655 if (hreq->context == NULL) {
656 uuid = afb_hreq_get_header(hreq, uuid_header);
658 uuid = afb_hreq_get_argument(hreq, uuid_arg);
660 uuid = afb_hreq_get_cookie(hreq, cookie_name);
661 hreq->context = ctxClientGetForUuid(uuid);
663 return hreq->context;
666 static int req_session_create(struct afb_hreq *hreq)
668 struct AFB_clientCtx *context = afb_hreq_context(hreq);
671 if (context->created)
673 return req_session_check(hreq, 1);
676 static int req_session_check(struct afb_hreq *hreq, int refresh)
680 struct AFB_clientCtx *context = afb_hreq_context(hreq);
685 token = afb_hreq_get_header(hreq, token_header);
687 token = afb_hreq_get_argument(hreq, token_arg);
689 token = afb_hreq_get_cookie(hreq, token_cookie);
693 if (!ctxTokenCheck (context, token))
697 ctxTokenNew (context);
703 static void req_session_close(struct afb_hreq *hreq)
705 struct AFB_clientCtx *context = afb_hreq_context(hreq);
707 ctxClientClose(context);
710 int afb_hreq_init_cookie(int port, const char *path, int maxage)
717 cookie_setter = NULL;
720 rc = asprintf(&cookie_name, "x-afb-uuid-%d", port);
723 rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
724 cookie_name, path, maxage);