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";
56 struct hreq_data *next;
63 static struct json_object *req_json(struct afb_hreq *hreq);
64 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
65 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
66 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
67 static const char *req_raw(struct afb_hreq *hreq, size_t *size);
68 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size);
69 static int req_session_create(struct afb_hreq *hreq);
70 static int req_session_check(struct afb_hreq *hreq, int refresh);
71 static void req_session_close(struct afb_hreq *hreq);
73 static const struct afb_req_itf afb_hreq_itf = {
74 .json = (void*)req_json,
75 .get = (void*)req_get,
76 .success = (void*)req_success,
77 .fail = (void*)req_fail,
78 .raw = (void*)req_raw,
79 .send = (void*)req_send,
80 .session_create = (void*)req_session_create,
81 .session_check = (void*)req_session_check,
82 .session_close = (void*)req_session_close
85 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
87 struct hreq_data *data = hreq->data;
88 while (data != NULL) {
89 if (!strcasecmp(data->key, key))
94 data = calloc(1, sizeof *data);
96 data->key = strdup(key);
97 if (data->key == NULL) {
101 data->next = hreq->data;
109 /* a valid subpath is a relative path not looking deeper than root using .. */
110 static int validsubpath(const char *subpath)
115 switch (subpath[i++]) {
119 if (subpath[i] == '/') {
123 if (subpath[i++] == '.') {
129 if (subpath[i++] == '/') {
136 while (subpath[i] && subpath[i] != '/')
146 #if defined(USE_MAGIC_MIME_TYPE)
148 #if !defined(MAGIC_DB)
149 #define MAGIC_DB "/usr/share/misc/magic.mgc"
152 static magic_t lazy_libmagic()
155 static magic_t result = NULL;
159 /* MAGIC_MIME tells magic to return a mime of the file,
160 but you can specify different things */
162 printf("Loading mimetype default magic database\n");
164 result = magic_open(MAGIC_MIME_TYPE);
165 if (result == NULL) {
166 fprintf(stderr,"ERROR: unable to initialize magic library\n");
168 /* Warning: should not use NULL for DB
169 [libmagic bug wont pass efence check] */
170 else if (magic_load(result, MAGIC_DB) != 0) {
171 fprintf(stderr,"cannot load magic database - %s\n",
172 magic_error(result));
181 static const char *magic_mimetype_fd(int fd)
183 magic_t lib = lazy_libmagic();
184 return lib ? magic_descriptor(lib, fd) : NULL;
189 static const char *mimetype_fd_name(int fd, const char *filename)
191 const char *result = NULL;
193 #if defined(INFER_EXTENSION)
194 const char *extension = strrchr(filename, '.');
196 static const char *const known[][2] = {
197 { ".js", "text/javascript" },
198 { ".html", "text/html" },
202 while (known[i][0]) {
203 if (!strcasecmp(extension, known[i][0])) {
204 result = known[i][1];
211 #if defined(USE_MAGIC_MIME_TYPE)
213 result = magic_mimetype_fd(fd);
218 void afb_hreq_free(struct afb_hreq *hreq)
220 struct hreq_data *data;
222 if (hreq->postform != NULL)
223 MHD_destroy_post_processor(hreq->postform);
224 for (data = hreq->data; data; data = hreq->data) {
225 hreq->data = data->next;
230 ctxClientPut(hreq->context);
236 * Removes the 'prefix' of 'length' from the tail of 'hreq'
237 * if and only if the prefix exists and is terminated by a leading
240 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
242 /* check the prefix ? */
243 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
244 || strncasecmp(prefix, hreq->tail, length))
247 /* removes successives / */
248 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
251 /* update the tail */
252 hreq->lentail -= length;
253 hreq->tail += length;
257 int afb_hreq_valid_tail(struct afb_hreq *hreq)
259 return validsubpath(hreq->tail);
262 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
266 struct MHD_Response *response;
268 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
270 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
272 buffer = "<html><body>error</body></html>";
273 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
275 if (!MHD_queue_response(hreq->connection, status, response))
276 fprintf(stderr, "Failed to reply error code %u", status);
277 MHD_destroy_response(response);
280 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
286 char etag[1 + 2 * sizeof(int)];
288 struct MHD_Response *response;
289 const char *mimetype;
291 /* Opens the file or directory */
293 fd = openat(dirfd, filename, O_RDONLY);
297 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
303 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
308 /* Retrieves file's status */
309 if (fstat(fd, &st) != 0) {
311 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
315 /* serve directory */
316 if (S_ISDIR(st.st_mode)) {
317 static const char *indexes[] = { "index.html", NULL };
320 while (indexes[i] != NULL) {
321 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
322 if (hreq->url[hreq->lenurl - 1] != '/') {
323 /* the redirect is needed for reliability of relative path */
324 char *tourl = alloca(hreq->lenurl + 2);
325 memcpy(tourl, hreq->url, hreq->lenurl);
326 tourl[hreq->lenurl] = '/';
327 tourl[hreq->lenurl + 1] = 0;
328 rc = afb_hreq_redirect_to(hreq, tourl);
330 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
340 /* Don't serve special files */
341 if (!S_ISREG(st.st_mode)) {
343 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
347 /* Check the method */
348 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
350 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
354 /* computes the etag */
355 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
357 /* checks the etag */
358 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
359 if (inm && 0 == strcmp(inm, etag)) {
360 /* etag ok, return NOT MODIFIED */
363 fprintf(stderr, "Not Modified: [%s]\n", filename);
364 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
365 status = MHD_HTTP_NOT_MODIFIED;
368 if (st.st_size != (off_t) (size_t) st.st_size) {
370 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
374 /* create the response */
375 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
376 status = MHD_HTTP_OK;
379 mimetype = mimetype_fd_name(fd, filename);
380 if (mimetype != NULL)
381 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
384 /* fills the value and send */
385 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout);
386 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
387 MHD_queue_response(hreq->connection, status, response);
388 MHD_destroy_response(response);
392 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
394 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
396 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
400 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
402 struct MHD_Response *response;
404 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
405 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
406 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
407 MHD_destroy_response(response);
409 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
413 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
415 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
418 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
420 struct hreq_data *data = get_data(hreq, name, 0);
421 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
424 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
426 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
429 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
432 struct hreq_data *hdat = get_data(hreq, key, 1);
433 if (hdat->path != NULL) {
436 p = realloc(hdat->value, hdat->length + size + 1);
441 memcpy(&hdat->value[hdat->length], data, size);
442 hdat->length += size;
443 hdat->value[hdat->length] = 0;
447 static int opentempfile(char **path)
452 fname = strdup("XXXXXX"); /* TODO improve the path */
456 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
464 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
468 struct hreq_data *hdat = get_data(hreq, key, 1);
470 if (hdat->value == NULL) {
471 hdat->value = strdup(file);
472 if (hdat->value == NULL)
474 fd = opentempfile(&hdat->path);
475 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
478 fd = open(hdat->path, O_WRONLY|O_APPEND);
483 sz = write(fd, data, size);
485 hdat->length += (size_t)sz;
488 } else if (errno != EINTR)
495 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
497 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
500 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
502 struct hreq_data *hdat = get_data(hreq, name, 0);
504 return (struct afb_arg){
506 .value = hdat->value,
510 return (struct afb_arg){
512 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
517 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
519 json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
523 static struct json_object *req_json(struct afb_hreq *hreq)
525 struct hreq_data *hdat;
526 struct json_object *obj, *val;
530 hreq->json = obj = json_object_new_object();
533 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
534 for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
535 if (hdat->path == NULL)
536 val = hdat->value ? json_object_new_string(hdat->value) : NULL;
538 val = json_object_new_object();
541 json_object_object_add(val, "file", json_object_new_string(hdat->value));
542 json_object_object_add(val, "path", json_object_new_string(hdat->path));
545 json_object_object_add(obj, hdat->key, val);
552 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
554 const char *result = json_object_get_string(req_json(hreq));
555 *size = result ? strlen(result) : 0;
559 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
561 struct MHD_Response *response = MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE);
562 MHD_queue_response(hreq->connection, MHD_HTTP_OK, response);
563 MHD_destroy_response(response);
566 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
568 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
572 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
574 json_object *root, *request;
575 struct MHD_Response *response;
577 root = json_object_new_object();
578 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
579 request = json_object_new_object();
580 json_object_object_add(root, "request", request);
581 json_object_object_add(request, "status", json_object_new_string(status));
583 json_object_object_add(request, "info", json_object_new_string(info));
585 json_object_object_add(root, "response", resp);
587 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
588 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
591 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
592 MHD_queue_response(hreq->connection, retcode, response);
593 MHD_destroy_response(response);
596 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
598 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
601 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
603 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
606 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
610 if (hreq->context == NULL) {
611 uuid = afb_hreq_get_header(hreq, uuid_header);
613 uuid = afb_hreq_get_argument(hreq, uuid_arg);
615 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
616 hreq->context = ctxClientGetForUuid(uuid);
618 return hreq->context;
621 static int req_session_create(struct afb_hreq *hreq)
623 struct AFB_clientCtx *context = afb_hreq_context(hreq);
626 if (context->created)
628 return req_session_check(hreq, 1);
631 static int req_session_check(struct afb_hreq *hreq, int refresh)
635 struct AFB_clientCtx *context = afb_hreq_context(hreq);
640 token = afb_hreq_get_header(hreq, token_header);
642 token = afb_hreq_get_argument(hreq, token_arg);
644 token = afb_hreq_get_cookie(hreq, token_cookie);
648 if (!ctxTokenCheck (context, token))
652 ctxTokenNew (context);
658 static void req_session_close(struct afb_hreq *hreq)
660 struct AFB_clientCtx *context = afb_hreq_context(hreq);
662 ctxClientClose(context);