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"
41 #define SIZE_RESPONSE_BUFFER 8000
43 static char empty_string[] = "";
45 static const char uuid_header[] = "x-afb-uuid";
46 static const char uuid_arg[] = "uuid";
47 static const char uuid_cookie[] = "uuid";
49 static const char token_header[] = "x-afb-token";
50 static const char token_arg[] = "token";
51 static const char token_cookie[] = "token";
53 static char *cookie_name = NULL;
54 static char *cookie_setter = NULL;
55 static char *tmp_pattern = 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,
85 .context_get = (void*)afb_context_get,
86 .context_set = (void*)afb_context_set
89 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
91 struct hreq_data *data = hreq->data;
92 while (data != NULL) {
93 if (!strcasecmp(data->key, key))
98 data = calloc(1, sizeof *data);
100 data->key = strdup(key);
101 if (data->key == NULL) {
105 data->next = hreq->data;
113 /* a valid subpath is a relative path not looking deeper than root using .. */
114 static int validsubpath(const char *subpath)
119 switch (subpath[i++]) {
123 if (subpath[i] == '/') {
127 if (subpath[i++] == '.') {
133 if (subpath[i++] == '/') {
140 while (subpath[i] && subpath[i] != '/')
150 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
154 k = va_arg(args, const char *);
156 v = va_arg(args, const char *);
157 MHD_add_response_header(response, k, v);
158 k = va_arg(args, const char *);
160 if (hreq->context != NULL && asprintf(&cookie, cookie_setter, hreq->context->uuid)) {
161 MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
164 MHD_queue_response(hreq->connection, status, response);
165 MHD_destroy_response(response);
168 void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
171 va_start(args, response);
172 afb_hreq_reply_v(hreq, status, response, args);
176 void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
179 va_start(args, status);
180 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
184 void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
187 va_start(args, buffer);
188 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_PERSISTENT), args);
192 void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
195 va_start(args, buffer);
196 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_COPY), args);
200 void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
203 va_start(args, buffer);
204 afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
208 #if defined(USE_MAGIC_MIME_TYPE)
210 #if !defined(MAGIC_DB)
211 #define MAGIC_DB "/usr/share/misc/magic.mgc"
214 static magic_t lazy_libmagic()
217 static magic_t result = NULL;
221 /* MAGIC_MIME tells magic to return a mime of the file,
222 but you can specify different things */
224 fprintf(stderr, "Loading mimetype default magic database\n");
226 result = magic_open(MAGIC_MIME_TYPE);
227 if (result == NULL) {
228 fprintf(stderr,"ERROR: unable to initialize magic library\n");
230 /* Warning: should not use NULL for DB
231 [libmagic bug wont pass efence check] */
232 else if (magic_load(result, MAGIC_DB) != 0) {
233 fprintf(stderr,"cannot load magic database - %s\n",
234 magic_error(result));
243 static const char *magic_mimetype_fd(int fd)
245 magic_t lib = lazy_libmagic();
246 return lib ? magic_descriptor(lib, fd) : NULL;
251 static const char *mimetype_fd_name(int fd, const char *filename)
253 const char *result = NULL;
255 #if defined(INFER_EXTENSION)
256 const char *extension = strrchr(filename, '.');
258 static const char *const known[][2] = {
259 { ".js", "text/javascript" },
260 { ".html", "text/html" },
261 { ".css", "text/css" },
265 while (known[i][0]) {
266 if (!strcasecmp(extension, known[i][0])) {
267 result = known[i][1];
274 #if defined(USE_MAGIC_MIME_TYPE)
276 result = magic_mimetype_fd(fd);
281 void afb_hreq_free(struct afb_hreq *hreq)
283 struct hreq_data *data;
285 if (hreq->postform != NULL)
286 MHD_destroy_post_processor(hreq->postform);
287 for (data = hreq->data; data; data = hreq->data) {
288 hreq->data = data->next;
297 ctxClientPut(hreq->context);
298 json_object_put(hreq->json);
304 * Removes the 'prefix' of 'length' from the tail of 'hreq'
305 * if and only if the prefix exists and is terminated by a leading
308 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
310 /* check the prefix ? */
311 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
312 || strncasecmp(prefix, hreq->tail, length))
315 /* removes successives / */
316 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
319 /* update the tail */
320 hreq->lentail -= length;
321 hreq->tail += length;
325 int afb_hreq_valid_tail(struct afb_hreq *hreq)
327 return validsubpath(hreq->tail);
330 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
332 afb_hreq_reply_empty(hreq, status, NULL);
335 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
341 char etag[1 + 2 * sizeof(int)];
343 struct MHD_Response *response;
344 const char *mimetype;
346 /* Opens the file or directory */
348 fd = openat(dirfd, filename, O_RDONLY);
352 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
358 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
363 /* Retrieves file's status */
364 if (fstat(fd, &st) != 0) {
366 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
370 /* serve directory */
371 if (S_ISDIR(st.st_mode)) {
372 static const char *indexes[] = { "index.html", NULL };
375 while (indexes[i] != NULL) {
376 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
377 if (hreq->url[hreq->lenurl - 1] != '/') {
378 /* the redirect is needed for reliability of relative path */
379 char *tourl = alloca(hreq->lenurl + 2);
380 memcpy(tourl, hreq->url, hreq->lenurl);
381 tourl[hreq->lenurl] = '/';
382 tourl[hreq->lenurl + 1] = 0;
383 rc = afb_hreq_redirect_to(hreq, tourl);
385 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
395 /* Don't serve special files */
396 if (!S_ISREG(st.st_mode)) {
398 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
402 /* Check the method */
403 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
405 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
409 /* computes the etag */
410 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
412 /* checks the etag */
413 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
414 if (inm && 0 == strcmp(inm, etag)) {
415 /* etag ok, return NOT MODIFIED */
418 fprintf(stderr, "Not Modified: [%s]\n", filename);
419 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
420 status = MHD_HTTP_NOT_MODIFIED;
423 if (st.st_size != (off_t) (size_t) st.st_size) {
425 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
429 /* create the response */
430 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
431 status = MHD_HTTP_OK;
434 mimetype = mimetype_fd_name(fd, filename);
435 if (mimetype != NULL)
436 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
439 /* fills the value and send */
440 afb_hreq_reply(hreq, status, response,
441 MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
442 MHD_HTTP_HEADER_ETAG, etag,
447 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
449 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
451 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
455 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
457 afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
458 MHD_HTTP_HEADER_LOCATION, url, NULL);
460 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
464 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
466 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
469 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
471 struct hreq_data *data = get_data(hreq, name, 0);
472 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
475 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
477 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
480 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
483 struct hreq_data *hdat = get_data(hreq, key, 1);
484 if (hdat->path != NULL) {
487 p = realloc(hdat->value, hdat->length + size + 1);
492 memcpy(&hdat->value[hdat->length], data, size);
493 hdat->length += size;
494 hdat->value[hdat->length] = 0;
498 int afb_hreq_init_download_path(const char *directory)
504 if (access(directory, R_OK|W_OK)) {
505 /* no read/write access */
508 if (stat(directory, &st)) {
512 if (!S_ISDIR(st.st_mode)) {
513 /* not a directory */
517 n = strlen(directory);
518 while(n > 1 && directory[n-1] == '/') n--;
521 /* can't allocate memory */
525 memcpy(p, directory, n);
539 static int opentempfile(char **path)
544 fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
548 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
556 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
560 struct hreq_data *hdat = get_data(hreq, key, 1);
562 if (hdat->value == NULL) {
563 hdat->value = strdup(file);
564 if (hdat->value == NULL)
566 fd = opentempfile(&hdat->path);
567 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
570 fd = open(hdat->path, O_WRONLY|O_APPEND);
575 sz = write(fd, data, size);
577 hdat->length += (size_t)sz;
580 } else if (errno != EINTR)
587 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
589 return (struct afb_req){ .itf = &afb_hreq_itf, .req_closure = hreq };
592 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
594 struct hreq_data *hdat = get_data(hreq, name, 0);
596 return (struct afb_arg){
598 .value = hdat->value,
602 return (struct afb_arg){
604 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
609 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
611 json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
615 static struct json_object *req_json(struct afb_hreq *hreq)
617 struct hreq_data *hdat;
618 struct json_object *obj, *val;
622 hreq->json = obj = json_object_new_object();
625 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
626 for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
627 if (hdat->path == NULL)
628 val = hdat->value ? json_object_new_string(hdat->value) : NULL;
630 val = json_object_new_object();
633 json_object_object_add(val, "file", json_object_new_string(hdat->value));
634 json_object_object_add(val, "path", json_object_new_string(hdat->path));
637 json_object_object_add(obj, hdat->key, val);
644 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
646 const char *result = json_object_get_string(req_json(hreq));
647 *size = result ? strlen(result) : 0;
651 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
653 afb_hreq_reply_free(hreq, MHD_HTTP_OK, size, buffer, NULL);
656 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
658 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
662 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
664 json_object *root, *request;
665 struct MHD_Response *response;
667 root = json_object_new_object();
668 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
669 request = json_object_new_object();
670 json_object_object_add(root, "request", request);
671 json_object_object_add(request, "status", json_object_new_string(status));
673 json_object_object_add(request, "info", json_object_new_string(info));
675 json_object_object_add(root, "response", resp);
677 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
678 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
681 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
682 afb_hreq_reply(hreq, retcode, response, NULL);
685 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
687 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
690 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
692 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
695 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
699 if (hreq->context == NULL) {
700 uuid = afb_hreq_get_header(hreq, uuid_header);
702 uuid = afb_hreq_get_argument(hreq, uuid_arg);
704 uuid = afb_hreq_get_cookie(hreq, cookie_name);
705 hreq->context = ctxClientGetForUuid(uuid);
707 return hreq->context;
710 static int req_session_create(struct afb_hreq *hreq)
712 struct AFB_clientCtx *context = afb_hreq_context(hreq);
715 if (context->created)
717 return req_session_check(hreq, 1);
720 static int req_session_check(struct afb_hreq *hreq, int refresh)
724 struct AFB_clientCtx *context = afb_hreq_context(hreq);
729 token = afb_hreq_get_header(hreq, token_header);
731 token = afb_hreq_get_argument(hreq, token_arg);
733 token = afb_hreq_get_cookie(hreq, token_cookie);
737 if (!ctxTokenCheck (context, token))
741 ctxTokenNew (context);
747 static void req_session_close(struct afb_hreq *hreq)
749 struct AFB_clientCtx *context = afb_hreq_context(hreq);
751 ctxClientClose(context);
754 int afb_hreq_init_cookie(int port, const char *path, int maxage)
761 cookie_setter = NULL;
764 rc = asprintf(&cookie_name, "x-afb-uuid-%d", port);
767 rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
768 cookie_name, path, maxage);