2 * Copyright (C) 2016-2019 "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 #if WITH_LIBMICROHTTPD
31 #include <sys/socket.h>
34 #include <json-c/json.h>
35 #include <microhttpd.h>
36 #if MHD_VERSION < 0x00095206
37 # define MHD_ALLOW_SUSPEND_RESUME MHD_USE_SUSPEND_RESUME
40 #include "afb-method.h"
41 #include "afb-context.h"
46 #include "afb-socket.h"
50 #include "locale-root.h"
54 #define JSON_CONTENT "application/json"
55 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
58 struct hsrv_itf *next;
59 struct afb_hsrv *hsrv;
65 struct hsrv_handler *next;
68 int (*handler) (struct afb_hreq *, void *);
74 struct locale_root *root;
80 struct hsrv_handler *handlers;
81 struct hsrv_itf *interfaces;
82 struct MHD_Daemon *httpd;
87 static void reply_error(struct MHD_Connection *connection, unsigned int status)
89 struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
90 MHD_queue_response(connection, status, response);
91 MHD_destroy_response(response);
94 static int postproc(void *cls,
95 enum MHD_ValueKind kind,
98 const char *content_type,
99 const char *transfer_encoding,
104 struct afb_hreq *hreq = cls;
105 if (filename != NULL)
106 return afb_hreq_post_add_file(hreq, key, filename, data, size);
108 return afb_hreq_post_add(hreq, key, data, size);
111 static int access_handler(
113 struct MHD_Connection *connection,
115 const char *methodstr,
117 const char *upload_data,
118 size_t *upload_data_size,
122 struct afb_hreq *hreq;
123 enum afb_method method;
124 struct afb_hsrv *hsrv;
125 struct hsrv_handler *iter;
127 enum json_tokener_error jerr;
133 method = get_method(methodstr);
134 method &= afb_method_get | afb_method_post;
135 if (method == afb_method_none) {
136 WARNING("Unsupported HTTP operation %s", methodstr);
137 reply_error(connection, MHD_HTTP_BAD_REQUEST);
141 /* create the request */
142 hreq = afb_hreq_create();
144 ERROR("Can't allocate 'hreq'");
145 reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
149 /* init the request */
151 hreq->cacheTimeout = hsrv->cache_to;
152 hreq->connection = connection;
153 hreq->method = method;
154 hreq->version = version;
155 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
156 hreq->tail = hreq->url = url;
157 hreq->lentail = hreq->lenurl = strlen(url);
160 /* init the post processing */
161 if (method == afb_method_post) {
162 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
164 /* an empty post, let's process it as a get */
165 hreq->method = afb_method_get;
166 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
167 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
168 if (hreq->postform == NULL) {
169 ERROR("Can't create POST processor");
170 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
173 } else if (strcasestr(type, JSON_CONTENT) != NULL) {
174 hreq->tokener = json_tokener_new();
175 if (hreq->tokener == NULL) {
176 ERROR("Can't create tokener for POST");
177 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
181 WARNING("Unsupported media type %s", type);
182 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
188 /* process further data */
189 if (*upload_data_size) {
190 if (hreq->postform != NULL) {
191 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
192 ERROR("error in POST processor");
193 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
196 } else if (hreq->tokener) {
197 hreq->json = json_tokener_parse_ex(hreq->tokener, upload_data, (int)*upload_data_size);
198 jerr = json_tokener_get_error(hreq->tokener);
199 if (jerr == json_tokener_continue) {
200 hreq->json = json_tokener_parse_ex(hreq->tokener, "", 1);
201 jerr = json_tokener_get_error(hreq->tokener);
203 if (jerr != json_tokener_success) {
204 ERROR("error in POST json: %s", json_tokener_error_desc(jerr));
205 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
209 *upload_data_size = 0;
214 if (hreq->postform != NULL) {
215 rc = MHD_destroy_post_processor(hreq->postform);
216 hreq->postform = NULL;
218 ERROR("error detected in POST processing");
219 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
223 if (hreq->tokener != NULL) {
224 json_tokener_free(hreq->tokener);
225 hreq->tokener = NULL;
228 if (hreq->scanned != 0) {
229 if (hreq->replied == 0 && hreq->suspended == 0) {
230 MHD_suspend_connection (connection);
236 /* search an handler for the request */
238 iter = hsrv->handlers;
240 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
241 if (iter->handler(hreq, iter->data)) {
242 if (hreq->replied == 0 && hreq->suspended == 0) {
243 MHD_suspend_connection (connection);
248 hreq->tail = hreq->url;
249 hreq->lentail = hreq->lenurl;
255 NOTICE("Unhandled request to %s", hreq->url);
256 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
260 /* Because of POST call multiple time requestApi we need to free POST handle here */
261 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
262 enum MHD_RequestTerminationCode toe)
264 struct afb_hreq *hreq;
268 afb_hreq_unref(hreq);
272 static void do_run(int signum, void *arg)
274 MHD_UNSIGNED_LONG_LONG to;
275 struct afb_hsrv *hsrv = arg;
278 do { MHD_run(hsrv->httpd); } while(MHD_get_timeout(hsrv->httpd, &to) == MHD_YES && !to);
280 fdev_set_events(hsrv->fdev, EPOLLIN);
283 void afb_hsrv_run(struct afb_hsrv *hsrv)
285 fdev_set_events(hsrv->fdev, 0);
286 if (jobs_queue(hsrv, 0, do_run, hsrv) < 0)
290 static void listen_callback(void *hsrv, uint32_t revents, struct fdev *fdev)
295 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
300 static struct hsrv_handler *new_handler(
301 struct hsrv_handler *head,
303 int (*handler) (struct afb_hreq *, void *),
307 struct hsrv_handler *link, *iter, *previous;
310 /* get the length of the prefix without its leading / */
311 length = strlen(prefix);
312 while (length && prefix[length - 1] == '/')
315 /* allocates the new link */
316 link = malloc(sizeof *link);
321 link->prefix = prefix;
322 link->length = length;
323 link->handler = handler;
325 link->priority = priority;
330 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
335 if (previous == NULL)
337 previous->next = link;
341 static int handle_alias(struct afb_hreq *hreq, void *data)
344 struct hsrv_alias *da = data;
345 struct locale_search *search;
347 if (hreq->method != afb_method_get) {
350 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
354 search = locale_root_search(da->root, hreq->lang, 0);
355 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
356 locale_search_unref(search);
360 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
365 int afb_hsrv_add_handler(
366 struct afb_hsrv *hsrv,
368 int (*handler) (struct afb_hreq *, void *),
372 struct hsrv_handler *head;
374 head = new_handler(hsrv->handlers, prefix, handler, data, priority);
377 hsrv->handlers = head;
381 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
383 struct hsrv_alias *da;
385 da = malloc(sizeof *da);
389 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
390 locale_root_addref(root);
398 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
400 struct locale_root *root;
403 root = locale_root_create_at(dirfd, alias);
405 ERROR("can't connect to directory %s: %m", alias);
408 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
409 locale_root_unref(root);
414 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
419 rc = asprintf(&dur, "%d", duration);
423 free(hsrv->cache_to);
424 hsrv->cache_to = dur;
428 int afb_hsrv_start(struct afb_hsrv *hsrv, unsigned int connection_timeout)
431 struct MHD_Daemon *httpd;
432 const union MHD_DaemonInfo *info;
434 httpd = MHD_start_daemon(
437 | MHD_USE_TCP_FASTOPEN
438 | MHD_USE_NO_LISTEN_SOCKET
440 | MHD_ALLOW_SUSPEND_RESUME,
442 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
443 access_handler, hsrv, /* Http Request Call back + extra attribute */
444 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
445 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
446 MHD_OPTION_END); /* options-end */
449 ERROR("httpStart invalid httpd");
453 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD);
455 MHD_stop_daemon(httpd);
456 ERROR("httpStart no pollfd");
460 fdev = afb_fdev_create(info->epoll_fd);
462 MHD_stop_daemon(httpd);
463 ERROR("connection to events for httpd failed");
466 fdev_set_autoclose(fdev, 0);
467 fdev_set_events(fdev, EPOLLIN);
468 fdev_set_callback(fdev, listen_callback, hsrv);
475 void afb_hsrv_stop(struct afb_hsrv *hsrv)
477 if (hsrv->fdev != NULL) {
478 fdev_unref(hsrv->fdev);
481 if (hsrv->httpd != NULL)
482 MHD_stop_daemon(hsrv->httpd);
486 struct afb_hsrv *afb_hsrv_create()
488 struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
490 result->refcount = 1;
494 void afb_hsrv_put(struct afb_hsrv *hsrv)
496 assert(hsrv->refcount != 0);
497 if (!--hsrv->refcount) {
503 static int hsrv_itf_connect(struct hsrv_itf *itf);
505 static void hsrv_itf_callback(void *closure, uint32_t revents, struct fdev *fdev)
507 struct hsrv_itf *itf = closure;
509 struct sockaddr addr;
512 if ((revents & EPOLLHUP) != 0) {
513 ERROR("disconnection for server %s: %m", itf->uri);
514 hsrv_itf_connect(itf);
516 } else if ((revents & EPOLLIN) != 0) {
517 lenaddr = (socklen_t)sizeof addr;
518 fd = accept(fdev_fd(fdev), &addr, &lenaddr);
520 ERROR("can't accept connection to %s: %m", itf->uri);
522 sts = MHD_add_connection(itf->hsrv->httpd, fd, &addr, lenaddr);
523 if (sts != MHD_YES) {
524 ERROR("can't add incoming connection to %s: %m", itf->uri);
531 static int hsrv_itf_connect(struct hsrv_itf *itf)
533 struct sockaddr addr;
535 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
538 itf->fdev = afb_socket_open_fdev(itf->uri, 1);
540 ERROR("can't create socket %s", itf->uri);
543 fdev_set_events(itf->fdev, EPOLLIN);
544 fdev_set_callback(itf->fdev, hsrv_itf_callback, itf);
545 memset(&addr, 0, sizeof addr);
546 lenaddr = (socklen_t)sizeof addr;
547 getsockname(fdev_fd(itf->fdev), &addr, &lenaddr);
548 if (addr.sa_family == AF_INET && !((struct sockaddr_in*)&addr)->sin_addr.s_addr) {
549 strncpy(hbuf, "*", NI_MAXHOST);
550 sprintf(sbuf, "%d", (int)ntohs(((struct sockaddr_in*)&addr)->sin_port));
552 rgni = getnameinfo(&addr, lenaddr, hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICSERV);
554 ERROR("getnameinfo returned %d: %s", rgni, gai_strerror(rgni));
555 hbuf[0] = sbuf[0] = '?';
556 hbuf[1] = sbuf[1] = 0;
559 NOTICE("Listening interface %s:%s", hbuf, sbuf);
563 int afb_hsrv_add_interface(struct afb_hsrv *hsrv, const char *uri)
565 struct hsrv_itf *itf;
567 itf = malloc(sizeof *itf + strlen(uri));
573 strcpy(itf->uri, uri);
574 itf->next = hsrv->interfaces;
575 hsrv->interfaces = itf;
576 return hsrv_itf_connect(itf);
579 int afb_hsrv_add_interface_tcp(struct afb_hsrv *hsrv, const char *itf, uint16_t port)
585 itf = "*"; /* awaiting getifaddrs impl */
587 rc = snprintf(buffer, sizeof buffer, "tcp:%s:%d", itf, (int)port);
588 if (rc < 0 || rc >= (int)sizeof buffer) {
593 return afb_hsrv_add_interface(hsrv, buffer);