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;
189 void afb_hreq_free(struct afb_hreq *hreq)
191 struct hreq_data *data;
193 if (hreq->postform != NULL)
194 MHD_destroy_post_processor(hreq->postform);
195 for (data = hreq->data; data; data = hreq->data) {
196 hreq->data = data->next;
201 ctxClientPut(hreq->context);
207 * Removes the 'prefix' of 'length' from the tail of 'hreq'
208 * if and only if the prefix exists and is terminated by a leading
211 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
213 /* check the prefix ? */
214 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
215 || strncasecmp(prefix, hreq->tail, length))
218 /* removes successives / */
219 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
222 /* update the tail */
223 hreq->lentail -= length;
224 hreq->tail += length;
228 int afb_hreq_valid_tail(struct afb_hreq *hreq)
230 return validsubpath(hreq->tail);
233 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
237 struct MHD_Response *response;
239 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
241 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
243 buffer = "<html><body>error</body></html>";
244 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
246 if (!MHD_queue_response(hreq->connection, status, response))
247 fprintf(stderr, "Failed to reply error code %u", status);
248 MHD_destroy_response(response);
251 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
257 char etag[1 + 2 * sizeof(int)];
259 struct MHD_Response *response;
261 /* Opens the file or directory */
263 fd = openat(dirfd, filename, O_RDONLY);
267 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
273 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
278 /* Retrieves file's status */
279 if (fstat(fd, &st) != 0) {
281 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
285 /* serve directory */
286 if (S_ISDIR(st.st_mode)) {
287 if (hreq->url[hreq->lenurl - 1] != '/') {
288 /* the redirect is needed for reliability of relative path */
289 char *tourl = alloca(hreq->lenurl + 2);
290 memcpy(tourl, hreq->url, hreq->lenurl);
291 tourl[hreq->lenurl] = '/';
292 tourl[hreq->lenurl + 1] = 0;
293 rc = afb_hreq_redirect_to(hreq, tourl);
295 rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
301 /* Don't serve special files */
302 if (!S_ISREG(st.st_mode)) {
304 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
308 /* Check the method */
309 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
311 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
315 /* computes the etag */
316 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
318 /* checks the etag */
319 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
320 if (inm && 0 == strcmp(inm, etag)) {
321 /* etag ok, return NOT MODIFIED */
324 fprintf(stderr, "Not Modified: [%s]\n", filename);
325 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
326 status = MHD_HTTP_NOT_MODIFIED;
329 if (st.st_size != (off_t) (size_t) st.st_size) {
331 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
335 /* create the response */
336 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
337 status = MHD_HTTP_OK;
339 #if defined(USE_MAGIC_MIME_TYPE)
342 const char *mimetype = magic_mimetype_fd(fd);
343 if (mimetype != NULL)
344 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
349 /* fills the value and send */
350 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
351 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
352 MHD_queue_response(hreq->connection, status, response);
353 MHD_destroy_response(response);
357 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
359 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
361 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
365 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
367 struct MHD_Response *response;
369 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
370 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
371 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
372 MHD_destroy_response(response);
374 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
378 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
380 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
383 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
385 struct hreq_data *data = get_data(hreq, name, 0);
386 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
389 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
391 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
394 void afb_hreq_post_end(struct afb_hreq *hreq)
396 struct hreq_data *data = hreq->data;
398 if (data->file > 0) {
406 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
409 struct hreq_data *hdat = get_data(hreq, key, 1);
413 p = realloc(hdat->value, hdat->length + size + 1);
418 memcpy(&hdat->value[hdat->length], data, size);
419 hdat->length += size;
420 hdat->value[hdat->length] = 0;
424 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
426 struct hreq_data *hdat = get_data(hreq, key, 1);
428 /* continuation with reopening */
429 if (hdat->file < 0) {
430 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
431 if (hdat->file == 0) {
438 if (hdat->file > 0) {
439 write(hdat->file, data, size);
449 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
451 struct hreq_data *hdat = get_data(hreq, key, 0);
452 return hdat != NULL && hdat->file != 0;
456 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
458 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
461 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
463 struct hreq_data *hdat = get_data(hreq, name, 0);
465 return (struct afb_arg){
467 .value = hdat->value,
468 .size = hdat->length,
469 .is_file = (hdat->file != 0)
472 return (struct afb_arg){
474 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
482 struct afb_hreq *hreq;
483 int (*iterator)(void *closure, struct afb_arg arg);
487 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
489 if (get_data(id->hreq, key, 0))
491 return id->iterator(id->closure, (struct afb_arg){
499 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
501 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
502 struct hreq_data *hdat = hreq->data;
504 if (!iterator(closure, (struct afb_arg){
506 .value = hdat->value,
507 .size = hdat->length,
508 .is_file = (hdat->file != 0)}))
512 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
515 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
517 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
521 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
523 json_object *root, *request;
524 struct MHD_Response *response;
526 root = json_object_new_object();
527 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
528 request = json_object_new_object();
529 json_object_object_add(root, "request", request);
530 json_object_object_add(request, "status", json_object_new_string(status));
532 json_object_object_add(request, "info", json_object_new_string(info));
534 json_object_object_add(root, "response", resp);
536 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
537 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
540 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
541 MHD_queue_response(hreq->connection, retcode, response);
542 MHD_destroy_response(response);
545 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
547 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
550 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
552 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
555 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
559 if (hreq->context == NULL) {
560 uuid = afb_hreq_get_header(hreq, uuid_header);
562 uuid = afb_hreq_get_argument(hreq, uuid_arg);
564 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
565 hreq->context = ctxClientGet(uuid);
567 return hreq->context;
570 static int req_session_create(struct afb_hreq *hreq)
572 struct AFB_clientCtx *context = afb_hreq_context(hreq);
575 if (context->created)
577 return req_session_check(hreq, 1);
580 static int req_session_check(struct afb_hreq *hreq, int refresh)
584 struct AFB_clientCtx *context = afb_hreq_context(hreq);
589 token = afb_hreq_get_header(hreq, token_header);
591 token = afb_hreq_get_argument(hreq, token_arg);
593 token = afb_hreq_get_cookie(hreq, token_cookie);
597 if (!ctxTokenCheck (context, token))
601 ctxTokenNew (context);
607 static void req_session_close(struct afb_hreq *hreq)
609 struct AFB_clientCtx *context = afb_hreq_context(hreq);
611 ctxClientClose(context);