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 if (hreq->url[hreq->lenurl - 1] != '/') {
316 /* the redirect is needed for reliability of relative path */
317 char *tourl = alloca(hreq->lenurl + 2);
318 memcpy(tourl, hreq->url, hreq->lenurl);
319 tourl[hreq->lenurl] = '/';
320 tourl[hreq->lenurl + 1] = 0;
321 rc = afb_hreq_redirect_to(hreq, tourl);
323 rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
329 /* Don't serve special files */
330 if (!S_ISREG(st.st_mode)) {
332 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
336 /* Check the method */
337 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
339 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
343 /* computes the etag */
344 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
346 /* checks the etag */
347 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
348 if (inm && 0 == strcmp(inm, etag)) {
349 /* etag ok, return NOT MODIFIED */
352 fprintf(stderr, "Not Modified: [%s]\n", filename);
353 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
354 status = MHD_HTTP_NOT_MODIFIED;
357 if (st.st_size != (off_t) (size_t) st.st_size) {
359 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
363 /* create the response */
364 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
365 status = MHD_HTTP_OK;
368 mimetype = mimetype_fd_name(fd, filename);
369 if (mimetype != NULL)
370 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
373 /* fills the value and send */
374 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
375 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
376 MHD_queue_response(hreq->connection, status, response);
377 MHD_destroy_response(response);
381 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
383 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
385 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
389 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
391 struct MHD_Response *response;
393 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
394 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
395 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
396 MHD_destroy_response(response);
398 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
402 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
404 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
407 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
409 struct hreq_data *data = get_data(hreq, name, 0);
410 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
413 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
415 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
418 void afb_hreq_post_end(struct afb_hreq *hreq)
420 struct hreq_data *data = hreq->data;
422 if (data->file > 0) {
430 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
433 struct hreq_data *hdat = get_data(hreq, key, 1);
437 p = realloc(hdat->value, hdat->length + size + 1);
442 memcpy(&hdat->value[hdat->length], data, size);
443 hdat->length += size;
444 hdat->value[hdat->length] = 0;
448 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
450 struct hreq_data *hdat = get_data(hreq, key, 1);
452 /* continuation with reopening */
453 if (hdat->file < 0) {
454 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
455 if (hdat->file == 0) {
462 if (hdat->file > 0) {
463 write(hdat->file, data, size);
473 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
475 struct hreq_data *hdat = get_data(hreq, key, 0);
476 return hdat != NULL && hdat->file != 0;
480 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
482 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
485 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
487 struct hreq_data *hdat = get_data(hreq, name, 0);
489 return (struct afb_arg){
491 .value = hdat->value,
492 .size = hdat->length,
493 .is_file = (hdat->file != 0)
496 return (struct afb_arg){
498 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
506 struct afb_hreq *hreq;
507 int (*iterator)(void *closure, struct afb_arg arg);
511 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
513 if (get_data(id->hreq, key, 0))
515 return id->iterator(id->closure, (struct afb_arg){
523 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
525 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
526 struct hreq_data *hdat = hreq->data;
528 if (!iterator(closure, (struct afb_arg){
530 .value = hdat->value,
531 .size = hdat->length,
532 .is_file = (hdat->file != 0)}))
536 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
539 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
541 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
545 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
547 json_object *root, *request;
548 struct MHD_Response *response;
550 root = json_object_new_object();
551 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
552 request = json_object_new_object();
553 json_object_object_add(root, "request", request);
554 json_object_object_add(request, "status", json_object_new_string(status));
556 json_object_object_add(request, "info", json_object_new_string(info));
558 json_object_object_add(root, "response", resp);
560 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
561 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
564 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
565 MHD_queue_response(hreq->connection, retcode, response);
566 MHD_destroy_response(response);
569 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
571 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
574 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
576 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
579 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
583 if (hreq->context == NULL) {
584 uuid = afb_hreq_get_header(hreq, uuid_header);
586 uuid = afb_hreq_get_argument(hreq, uuid_arg);
588 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
589 hreq->context = ctxClientGetForUuid(uuid);
591 return hreq->context;
594 static int req_session_create(struct afb_hreq *hreq)
596 struct AFB_clientCtx *context = afb_hreq_context(hreq);
599 if (context->created)
601 return req_session_check(hreq, 1);
604 static int req_session_check(struct afb_hreq *hreq, int refresh)
608 struct AFB_clientCtx *context = afb_hreq_context(hreq);
613 token = afb_hreq_get_header(hreq, token_header);
615 token = afb_hreq_get_argument(hreq, token_arg);
617 token = afb_hreq_get_cookie(hreq, token_cookie);
621 if (!ctxTokenCheck (context, token))
625 ctxTokenNew (context);
631 static void req_session_close(struct afb_hreq *hreq)
633 struct AFB_clientCtx *context = afb_hreq_context(hreq);
635 ctxClientClose(context);