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;
234 ctxClientPut(hreq->context);
235 json_object_put(hreq->json);
241 * Removes the 'prefix' of 'length' from the tail of 'hreq'
242 * if and only if the prefix exists and is terminated by a leading
245 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
247 /* check the prefix ? */
248 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
249 || strncasecmp(prefix, hreq->tail, length))
252 /* removes successives / */
253 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
256 /* update the tail */
257 hreq->lentail -= length;
258 hreq->tail += length;
262 int afb_hreq_valid_tail(struct afb_hreq *hreq)
264 return validsubpath(hreq->tail);
267 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
271 struct MHD_Response *response;
273 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
275 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
277 buffer = "<html><body>error</body></html>";
278 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
280 if (!MHD_queue_response(hreq->connection, status, response))
281 fprintf(stderr, "Failed to reply error code %u", status);
282 MHD_destroy_response(response);
285 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
291 char etag[1 + 2 * sizeof(int)];
293 struct MHD_Response *response;
294 const char *mimetype;
296 /* Opens the file or directory */
298 fd = openat(dirfd, filename, O_RDONLY);
302 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
308 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
313 /* Retrieves file's status */
314 if (fstat(fd, &st) != 0) {
316 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
320 /* serve directory */
321 if (S_ISDIR(st.st_mode)) {
322 static const char *indexes[] = { "index.html", NULL };
325 while (indexes[i] != NULL) {
326 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
327 if (hreq->url[hreq->lenurl - 1] != '/') {
328 /* the redirect is needed for reliability of relative path */
329 char *tourl = alloca(hreq->lenurl + 2);
330 memcpy(tourl, hreq->url, hreq->lenurl);
331 tourl[hreq->lenurl] = '/';
332 tourl[hreq->lenurl + 1] = 0;
333 rc = afb_hreq_redirect_to(hreq, tourl);
335 rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
345 /* Don't serve special files */
346 if (!S_ISREG(st.st_mode)) {
348 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
352 /* Check the method */
353 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
355 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
359 /* computes the etag */
360 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
362 /* checks the etag */
363 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
364 if (inm && 0 == strcmp(inm, etag)) {
365 /* etag ok, return NOT MODIFIED */
368 fprintf(stderr, "Not Modified: [%s]\n", filename);
369 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
370 status = MHD_HTTP_NOT_MODIFIED;
373 if (st.st_size != (off_t) (size_t) st.st_size) {
375 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
379 /* create the response */
380 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
381 status = MHD_HTTP_OK;
384 mimetype = mimetype_fd_name(fd, filename);
385 if (mimetype != NULL)
386 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
389 /* fills the value and send */
390 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout);
391 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
392 MHD_queue_response(hreq->connection, status, response);
393 MHD_destroy_response(response);
397 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
399 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
401 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
405 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
407 struct MHD_Response *response;
409 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
410 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
411 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
412 MHD_destroy_response(response);
414 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
418 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
420 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
423 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
425 struct hreq_data *data = get_data(hreq, name, 0);
426 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
429 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
431 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
434 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
437 struct hreq_data *hdat = get_data(hreq, key, 1);
438 if (hdat->path != NULL) {
441 p = realloc(hdat->value, hdat->length + size + 1);
446 memcpy(&hdat->value[hdat->length], data, size);
447 hdat->length += size;
448 hdat->value[hdat->length] = 0;
452 static int opentempfile(char **path)
457 fname = strdup("XXXXXX"); /* TODO improve the path */
461 fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
469 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
473 struct hreq_data *hdat = get_data(hreq, key, 1);
475 if (hdat->value == NULL) {
476 hdat->value = strdup(file);
477 if (hdat->value == NULL)
479 fd = opentempfile(&hdat->path);
480 } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
483 fd = open(hdat->path, O_WRONLY|O_APPEND);
488 sz = write(fd, data, size);
490 hdat->length += (size_t)sz;
493 } else if (errno != EINTR)
500 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
502 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
505 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
507 struct hreq_data *hdat = get_data(hreq, name, 0);
509 return (struct afb_arg){
511 .value = hdat->value,
515 return (struct afb_arg){
517 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
522 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
524 json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
528 static struct json_object *req_json(struct afb_hreq *hreq)
530 struct hreq_data *hdat;
531 struct json_object *obj, *val;
535 hreq->json = obj = json_object_new_object();
538 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
539 for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
540 if (hdat->path == NULL)
541 val = hdat->value ? json_object_new_string(hdat->value) : NULL;
543 val = json_object_new_object();
546 json_object_object_add(val, "file", json_object_new_string(hdat->value));
547 json_object_object_add(val, "path", json_object_new_string(hdat->path));
550 json_object_object_add(obj, hdat->key, val);
557 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
559 const char *result = json_object_get_string(req_json(hreq));
560 *size = result ? strlen(result) : 0;
564 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
566 struct MHD_Response *response = MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE);
567 MHD_queue_response(hreq->connection, MHD_HTTP_OK, response);
568 MHD_destroy_response(response);
571 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
573 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
577 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
579 json_object *root, *request;
580 struct MHD_Response *response;
582 root = json_object_new_object();
583 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
584 request = json_object_new_object();
585 json_object_object_add(root, "request", request);
586 json_object_object_add(request, "status", json_object_new_string(status));
588 json_object_object_add(request, "info", json_object_new_string(info));
590 json_object_object_add(root, "response", resp);
592 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
593 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
596 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
597 MHD_queue_response(hreq->connection, retcode, response);
598 MHD_destroy_response(response);
601 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
603 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
606 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
608 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
611 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
615 if (hreq->context == NULL) {
616 uuid = afb_hreq_get_header(hreq, uuid_header);
618 uuid = afb_hreq_get_argument(hreq, uuid_arg);
620 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
621 hreq->context = ctxClientGetForUuid(uuid);
623 return hreq->context;
626 static int req_session_create(struct afb_hreq *hreq)
628 struct AFB_clientCtx *context = afb_hreq_context(hreq);
631 if (context->created)
633 return req_session_check(hreq, 1);
636 static int req_session_check(struct afb_hreq *hreq, int refresh)
640 struct AFB_clientCtx *context = afb_hreq_context(hreq);
645 token = afb_hreq_get_header(hreq, token_header);
647 token = afb_hreq_get_argument(hreq, token_arg);
649 token = afb_hreq_get_cookie(hreq, token_cookie);
653 if (!ctxTokenCheck (context, token))
657 ctxTokenNew (context);
663 static void req_session_close(struct afb_hreq *hreq)
665 struct AFB_clientCtx *context = afb_hreq_context(hreq);
667 ctxClientClose(context);