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.
19 #include <microhttpd.h>
24 #include "../include/local-def.h"
25 #include "afb-method.h"
27 #include "afb-websock.h"
30 #include "afb-req-itf.h"
32 #define JSON_CONTENT "application/json"
33 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
35 struct afb_hsrv_handler {
36 struct afb_hsrv_handler *next;
39 int (*handler) (struct afb_hreq *, void *);
46 const char *directory;
51 int afb_hreq_one_page_api_redirect(
52 struct afb_hreq *hreq,
58 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
61 * Here we have for example:
62 * url = "/pre/dir/page" lenurl = 13
63 * tail = "/dir/page" lentail = 9
65 * We will produce "/pre/#!dir/page"
67 * Let compute plen that include the / at end (for "/pre/")
69 plen = hreq->lenurl - hreq->lentail + 1;
70 url = alloca(hreq->lenurl + 3);
71 memcpy(url, hreq->url, plen);
74 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
75 return afb_hreq_redirect_to(hreq, url);
78 static struct afb_hsrv_handler *new_handler(
79 struct afb_hsrv_handler *head,
81 int (*handler) (struct afb_hreq *, void *),
85 struct afb_hsrv_handler *link, *iter, *previous;
88 /* get the length of the prefix without its leading / */
89 length = strlen(prefix);
90 while (length && prefix[length - 1] == '/')
93 /* allocates the new link */
94 link = malloc(sizeof *link);
99 link->prefix = prefix;
100 link->length = length;
101 link->handler = handler;
103 link->priority = priority;
108 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
113 if (previous == NULL)
115 previous->next = link;
119 int afb_hsrv_add_handler(
120 AFB_session * session,
122 int (*handler) (struct afb_hreq *, void *),
126 struct afb_hsrv_handler *head;
128 head = new_handler(session->handlers, prefix, handler, data, priority);
131 session->handlers = head;
135 static const char uuid_header[] = "x-afb-uuid";
136 static const char uuid_arg[] = "uuid";
137 static const char uuid_cookie[] = "uuid";
139 static struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
143 if (hreq->context == NULL) {
144 uuid = afb_hreq_get_header(hreq, uuid_header);
146 uuid = afb_hreq_get_argument(hreq, uuid_arg);
148 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
149 hreq->context = _ctxClientGet(uuid);
151 return hreq->context;
154 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
158 afb_hreq_context(hreq);
159 if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
163 struct afb_websock *ws = afb_websock_create(hreq->connection);
173 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
175 const char *api, *verb;
176 size_t lenapi, lenverb;
178 api = &hreq->tail[strspn(hreq->tail, "/")];
179 lenapi = strcspn(api, "/");
181 verb = &verb[strspn(verb, "/")];
182 lenverb = strcspn(verb, "/");
184 if (!(*api && *verb && lenapi && lenverb))
187 return afb_apis_handle(afb_hreq_to_req(hreq), api, lenapi, verb, lenverb);
190 static int handle_alias(struct afb_hreq *hreq, void *data)
192 struct afb_diralias *da = data;
194 if (hreq->method != afb_method_get) {
195 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
199 if (!afb_hreq_valid_tail(hreq)) {
200 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
204 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
207 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
209 struct afb_diralias *da;
212 dirfd = open(alias, O_PATH|O_DIRECTORY);
217 da = malloc(sizeof *da);
220 da->directory = alias;
221 da->lendir = strlen(da->directory);
223 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
231 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
235 struct MHD_Response *response;
237 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
239 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
241 buffer = "<html><body>error</body></html>";
242 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
244 if (!MHD_queue_response(connection, status, response))
245 fprintf(stderr, "Failed to reply error code %u", status);
246 MHD_destroy_response(response);
249 static int postproc(void *cls,
250 enum MHD_ValueKind kind,
252 const char *filename,
253 const char *content_type,
254 const char *transfer_encoding,
259 struct afb_hreq *hreq = cls;
260 if (filename != NULL)
261 return afb_hreq_post_add_file(hreq, key, filename, data, size);
263 return afb_hreq_post_add(hreq, key, data, size);
266 static int access_handler(
268 struct MHD_Connection *connection,
270 const char *methodstr,
272 const char *upload_data,
273 size_t *upload_data_size,
277 struct afb_hreq *hreq;
278 enum afb_method method;
279 AFB_session *session;
280 struct afb_hsrv_handler *iter;
286 /* create the request */
287 hreq = calloc(1, sizeof *hreq);
293 method = get_method(methodstr);
294 method &= afb_method_get | afb_method_post;
295 if (method == afb_method_none)
298 /* init the request */
300 hreq->connection = connection;
301 hreq->method = method;
302 hreq->version = version;
303 hreq->tail = hreq->url = url;
304 hreq->lentail = hreq->lenurl = strlen(url);
306 /* init the post processing */
307 if (method == afb_method_post) {
308 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
310 /* an empty post, let's process it as a get */
311 hreq->method = afb_method_get;
312 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
313 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
314 if (hreq->postform == NULL)
316 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
317 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
323 /* process further data */
324 if (*upload_data_size) {
325 if (hreq->postform != NULL) {
326 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
329 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
332 *upload_data_size = 0;
337 afb_hreq_post_end(hreq);
338 if (hreq->postform != NULL) {
339 rc = MHD_destroy_post_processor(hreq->postform);
340 hreq->postform = NULL;
345 /* search an handler for the request */
346 iter = session->handlers;
348 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
349 if (iter->handler(hreq, iter->data))
351 hreq->tail = hreq->url;
352 hreq->lentail = hreq->lenurl;
358 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
362 afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
366 afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
370 /* Because of POST call multiple time requestApi we need to free POST handle here */
371 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
372 enum MHD_RequestTerminationCode toe)
374 AFB_session *session;
375 struct afb_hreq *hreq;
381 if (hreq->postform != NULL)
382 MHD_destroy_post_processor(hreq->postform);
383 afb_hreq_drop_data(hreq);
388 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
393 #if defined(USE_MAGIC_MIME_TYPE)
395 #if !defined(MAGIC_DB)
396 #define MAGIC_DB "/usr/share/misc/magic.mgc"
399 static int init_lib_magic (AFB_session *session)
401 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
403 printf("Loading mimetype default magic database\n");
405 session->magic = magic_open(MAGIC_MIME_TYPE);
406 if (session->magic == NULL) {
407 fprintf(stderr,"ERROR: unable to initialize magic library\n");
411 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
412 if (magic_load(session->magic, MAGIC_DB) != 0) {
413 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
414 magic_close(session->magic);
415 session->magic = NULL;
423 static int my_default_init(AFB_session * session)
427 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
430 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
433 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
434 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
437 if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
440 if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
446 AFB_error httpdStart(AFB_session * session)
448 if (!my_default_init(session)) {
449 printf("Error: initialisation of httpd failed");
453 #if defined(USE_MAGIC_MIME_TYPE)
454 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
455 init_lib_magic (session);
459 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
460 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
463 session->httpd = MHD_start_daemon(
464 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
465 (uint16_t) session->config->httpdPort, /* port */
466 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
467 access_handler, session, /* Http Request Call back + extra attribute */
468 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
469 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
470 MHD_OPTION_END); /* options-end */
472 if (session->httpd == NULL) {
473 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
480 AFB_error httpdLoop(AFB_session * session)
483 const union MHD_DaemonInfo *info;
486 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
488 printf("Error: httpLoop no pollfd");
491 pfd.fd = info->listen_fd;
495 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
498 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
499 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
500 MHD_run(session->httpd);
504 /* should never return from here */
508 int httpdStatus(AFB_session * session)
510 return MHD_run(session->httpd);
513 void httpdStop(AFB_session * session)
515 MHD_stop_daemon(session->httpd);