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>
31 #if defined(USE_MAGIC_MIME_TYPE)
35 #include "local-def.h"
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 afb_arg req_get(struct afb_hreq *hreq, const char *name);
64 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
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 int req_session_create(struct afb_hreq *hreq);
68 static int req_session_check(struct afb_hreq *hreq, int refresh);
69 static void req_session_close(struct afb_hreq *hreq);
71 static const struct afb_req_itf afb_hreq_itf = {
72 .get = (void*)req_get,
73 .iterate = (void*)req_iterate,
74 .fail = (void*)req_fail,
75 .success = (void*)req_success,
76 .session_create = (void*)req_session_create,
77 .session_check = (void*)req_session_check,
78 .session_close = (void*)req_session_close
81 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
83 struct hreq_data *data = hreq->data;
86 while (data != NULL) {
87 if (!strcasecmp(data->key, key))
92 data = calloc(1, sizeof *data);
94 data->key = strdup(key);
95 if (data->key == NULL) {
99 data->next = hreq->data;
107 /* a valid subpath is a relative path not looking deeper than root using .. */
108 static int validsubpath(const char *subpath)
113 switch (subpath[i++]) {
117 if (subpath[i] == '/') {
121 if (subpath[i++] == '.') {
127 if (subpath[i++] == '/') {
134 while (subpath[i] && subpath[i] != '/')
144 #if defined(USE_MAGIC_MIME_TYPE)
146 #if !defined(MAGIC_DB)
147 #define MAGIC_DB "/usr/share/misc/magic.mgc"
150 static magic_t lazy_libmagic()
153 static magic_t result = NULL;
157 /* MAGIC_MIME tells magic to return a mime of the file,
158 but you can specify different things */
160 printf("Loading mimetype default magic database\n");
162 result = magic_open(MAGIC_MIME_TYPE);
163 if (result == NULL) {
164 fprintf(stderr,"ERROR: unable to initialize magic library\n");
166 /* Warning: should not use NULL for DB
167 [libmagic bug wont pass efence check] */
168 else if (magic_load(result, MAGIC_DB) != 0) {
169 fprintf(stderr,"cannot load magic database - %s\n",
170 magic_error(result));
179 static const char *magic_mimetype_fd(int fd)
181 magic_t lib = lazy_libmagic();
182 return lib ? magic_descriptor(lib, fd) : NULL;
187 static const char *mimetype_fd_name(int fd, const char *filename)
189 const char *result = NULL;
191 #if defined(INFER_EXTENSION)
192 const char *extension = strrchr(filename, '.');
194 static const char *const known[][2] = {
195 { ".js", "text/javascript" },
196 { ".html", "text/html" },
200 while (known[i][0]) {
201 if (!strcasecmp(extension, known[i][0])) {
202 result = known[i][1];
209 #if defined(USE_MAGIC_MIME_TYPE)
211 result = magic_mimetype_fd(fd);
216 void afb_hreq_free(struct afb_hreq *hreq)
218 struct hreq_data *data;
220 if (hreq->postform != NULL)
221 MHD_destroy_post_processor(hreq->postform);
222 for (data = hreq->data; data; data = hreq->data) {
223 hreq->data = data->next;
228 ctxClientPut(hreq->context);
234 * Removes the 'prefix' of 'length' from the tail of 'hreq'
235 * if and only if the prefix exists and is terminated by a leading
238 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
240 /* check the prefix ? */
241 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
242 || strncasecmp(prefix, hreq->tail, length))
245 /* removes successives / */
246 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
249 /* update the tail */
250 hreq->lentail -= length;
251 hreq->tail += length;
255 int afb_hreq_valid_tail(struct afb_hreq *hreq)
257 return validsubpath(hreq->tail);
260 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
264 struct MHD_Response *response;
266 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
268 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
270 buffer = "<html><body>error</body></html>";
271 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
273 if (!MHD_queue_response(hreq->connection, status, response))
274 fprintf(stderr, "Failed to reply error code %u", status);
275 MHD_destroy_response(response);
278 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
284 char etag[1 + 2 * sizeof(int)];
286 struct MHD_Response *response;
287 const char *mimetype;
289 /* Opens the file or directory */
291 fd = openat(dirfd, filename, O_RDONLY);
295 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
301 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
306 /* Retrieves file's status */
307 if (fstat(fd, &st) != 0) {
309 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
313 /* serve directory */
314 if (S_ISDIR(st.st_mode)) {
315 static const char *indexes[] = { "index.html", NULL };
318 while (indexes[i] != NULL) {
319 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
320 if (hreq->url[hreq->lenurl - 1] != '/') {
321 /* the redirect is needed for reliability of relative path */
322 char *tourl = alloca(hreq->lenurl + 2);
323 memcpy(tourl, hreq->url, hreq->lenurl);
324 tourl[hreq->lenurl] = '/';
325 tourl[hreq->lenurl + 1] = 0;
326 rc = afb_hreq_redirect_to(hreq, tourl);
328 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
338 /* Don't serve special files */
339 if (!S_ISREG(st.st_mode)) {
341 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
345 /* Check the method */
346 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
348 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
352 /* computes the etag */
353 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
355 /* checks the etag */
356 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
357 if (inm && 0 == strcmp(inm, etag)) {
358 /* etag ok, return NOT MODIFIED */
361 fprintf(stderr, "Not Modified: [%s]\n", filename);
362 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
363 status = MHD_HTTP_NOT_MODIFIED;
366 if (st.st_size != (off_t) (size_t) st.st_size) {
368 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
372 /* create the response */
373 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
374 status = MHD_HTTP_OK;
377 mimetype = mimetype_fd_name(fd, filename);
378 if (mimetype != NULL)
379 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
382 /* fills the value and send */
383 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
384 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
385 MHD_queue_response(hreq->connection, status, response);
386 MHD_destroy_response(response);
390 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
392 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
394 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
398 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
400 struct MHD_Response *response;
402 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
403 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
404 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
405 MHD_destroy_response(response);
407 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
411 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
413 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
416 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
418 struct hreq_data *data = get_data(hreq, name, 0);
419 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
422 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
424 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
427 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
430 struct hreq_data *hdat = get_data(hreq, key, 1);
431 if (hdat->path != NULL) {
434 p = realloc(hdat->value, hdat->length + size + 1);
439 memcpy(&hdat->value[hdat->length], data, size);
440 hdat->length += size;
441 hdat->value[hdat->length] = 0;
445 static int opentempfile(char **path)
450 fname = strdup("XXXXXX"); /* TODO improve the path */
454 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
462 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
466 struct hreq_data *hdat = get_data(hreq, key, 1);
468 fprintf(stderr, "%s=%s %s=%s %s\n",key,hdat->key,file,hdat->value,hdat->path);
469 if (hdat->value == NULL) {
470 hdat->value = strdup(file);
471 if (hdat->value == NULL)
473 fd = opentempfile(&hdat->path);
474 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
477 fd = open(hdat->path, O_WRONLY|O_APPEND);
482 sz = write(fd, data, size);
484 hdat->length += (size_t)sz;
487 } else if (errno != EINTR)
494 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
496 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
499 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
501 struct hreq_data *hdat = get_data(hreq, name, 0);
503 return (struct afb_arg){
505 .value = hdat->value,
506 .size = hdat->length,
510 return (struct afb_arg){
512 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
520 struct afb_hreq *hreq;
521 int (*iterator)(void *closure, struct afb_arg arg);
525 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
527 if (get_data(id->hreq, key, 0))
529 return id->iterator(id->closure, (struct afb_arg){
531 .value = value ? : "",
532 .size = value ? strlen(value) : 0,
537 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
539 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
540 struct hreq_data *hdat = hreq->data;
542 if (!iterator(closure, (struct afb_arg){
544 .value = hdat->value,
545 .size = hdat->length,
546 .path = hdat->path}))
550 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
553 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
555 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
559 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
561 json_object *root, *request;
562 struct MHD_Response *response;
564 root = json_object_new_object();
565 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
566 request = json_object_new_object();
567 json_object_object_add(root, "request", request);
568 json_object_object_add(request, "status", json_object_new_string(status));
570 json_object_object_add(request, "info", json_object_new_string(info));
572 json_object_object_add(root, "response", resp);
574 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
575 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
578 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
579 MHD_queue_response(hreq->connection, retcode, response);
580 MHD_destroy_response(response);
583 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
585 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
588 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
590 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
593 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
597 if (hreq->context == NULL) {
598 uuid = afb_hreq_get_header(hreq, uuid_header);
600 uuid = afb_hreq_get_argument(hreq, uuid_arg);
602 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
603 hreq->context = ctxClientGetForUuid(uuid);
605 return hreq->context;
608 static int req_session_create(struct afb_hreq *hreq)
610 struct AFB_clientCtx *context = afb_hreq_context(hreq);
613 if (context->created)
615 return req_session_check(hreq, 1);
618 static int req_session_check(struct afb_hreq *hreq, int refresh)
622 struct AFB_clientCtx *context = afb_hreq_context(hreq);
627 token = afb_hreq_get_header(hreq, token_header);
629 token = afb_hreq_get_argument(hreq, token_arg);
631 token = afb_hreq_get_cookie(hreq, token_cookie);
635 if (!ctxTokenCheck (context, token))
639 ctxTokenNew (context);
645 static void req_session_close(struct afb_hreq *hreq)
647 struct AFB_clientCtx *context = afb_hreq_context(hreq);
649 ctxClientClose(context);