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.
29 #include <sys/socket.h>
32 #include <json-c/json.h>
33 #include <microhttpd.h>
34 #if MHD_VERSION < 0x00095206
35 # define MHD_ALLOW_SUSPEND_RESUME MHD_USE_SUSPEND_RESUME
38 #include "afb-method.h"
39 #include "afb-context.h"
44 #include "afb-socket.h"
48 #include "locale-root.h"
52 #define JSON_CONTENT "application/json"
53 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
56 struct hsrv_itf *next;
57 struct afb_hsrv *hsrv;
63 struct hsrv_handler *next;
66 int (*handler) (struct afb_hreq *, void *);
72 struct locale_root *root;
78 struct hsrv_handler *handlers;
79 struct hsrv_itf *interfaces;
80 struct MHD_Daemon *httpd;
85 static void reply_error(struct MHD_Connection *connection, unsigned int status)
87 struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
88 MHD_queue_response(connection, status, response);
89 MHD_destroy_response(response);
92 static int postproc(void *cls,
93 enum MHD_ValueKind kind,
96 const char *content_type,
97 const char *transfer_encoding,
102 struct afb_hreq *hreq = cls;
103 if (filename != NULL)
104 return afb_hreq_post_add_file(hreq, key, filename, data, size);
106 return afb_hreq_post_add(hreq, key, data, size);
109 static int access_handler(
111 struct MHD_Connection *connection,
113 const char *methodstr,
115 const char *upload_data,
116 size_t *upload_data_size,
120 struct afb_hreq *hreq;
121 enum afb_method method;
122 struct afb_hsrv *hsrv;
123 struct hsrv_handler *iter;
125 enum json_tokener_error jerr;
131 method = get_method(methodstr);
132 method &= afb_method_get | afb_method_post;
133 if (method == afb_method_none) {
134 WARNING("Unsupported HTTP operation %s", methodstr);
135 reply_error(connection, MHD_HTTP_BAD_REQUEST);
139 /* create the request */
140 hreq = afb_hreq_create();
142 ERROR("Can't allocate 'hreq'");
143 reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
147 /* init the request */
149 hreq->cacheTimeout = hsrv->cache_to;
150 hreq->connection = connection;
151 hreq->method = method;
152 hreq->version = version;
153 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
154 hreq->tail = hreq->url = url;
155 hreq->lentail = hreq->lenurl = strlen(url);
158 /* init the post processing */
159 if (method == afb_method_post) {
160 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
162 /* an empty post, let's process it as a get */
163 hreq->method = afb_method_get;
164 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
165 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
166 if (hreq->postform == NULL) {
167 ERROR("Can't create POST processor");
168 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
171 } else if (strcasestr(type, JSON_CONTENT) != NULL) {
172 hreq->tokener = json_tokener_new();
173 if (hreq->tokener == NULL) {
174 ERROR("Can't create tokener for POST");
175 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
179 WARNING("Unsupported media type %s", type);
180 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
186 /* process further data */
187 if (*upload_data_size) {
188 if (hreq->postform != NULL) {
189 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
190 ERROR("error in POST processor");
191 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
194 } else if (hreq->tokener) {
195 hreq->json = json_tokener_parse_ex(hreq->tokener, upload_data, (int)*upload_data_size);
196 jerr = json_tokener_get_error(hreq->tokener);
197 if (jerr == json_tokener_continue) {
198 hreq->json = json_tokener_parse_ex(hreq->tokener, "", 1);
199 jerr = json_tokener_get_error(hreq->tokener);
201 if (jerr != json_tokener_success) {
202 ERROR("error in POST json: %s", json_tokener_error_desc(jerr));
203 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
207 *upload_data_size = 0;
212 if (hreq->postform != NULL) {
213 rc = MHD_destroy_post_processor(hreq->postform);
214 hreq->postform = NULL;
216 ERROR("error detected in POST processing");
217 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
221 if (hreq->tokener != NULL) {
222 json_tokener_free(hreq->tokener);
223 hreq->tokener = NULL;
226 if (hreq->scanned != 0) {
227 if (hreq->replied == 0 && hreq->suspended == 0) {
228 MHD_suspend_connection (connection);
234 /* search an handler for the request */
236 iter = hsrv->handlers;
238 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
239 if (iter->handler(hreq, iter->data)) {
240 if (hreq->replied == 0 && hreq->suspended == 0) {
241 MHD_suspend_connection (connection);
246 hreq->tail = hreq->url;
247 hreq->lentail = hreq->lenurl;
253 NOTICE("Unhandled request to %s", hreq->url);
254 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
258 /* Because of POST call multiple time requestApi we need to free POST handle here */
259 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
260 enum MHD_RequestTerminationCode toe)
262 struct afb_hreq *hreq;
266 afb_hreq_unref(hreq);
270 static void do_run(int signum, void *arg)
272 MHD_UNSIGNED_LONG_LONG to;
273 struct afb_hsrv *hsrv = arg;
276 do { MHD_run(hsrv->httpd); } while(MHD_get_timeout(hsrv->httpd, &to) == MHD_YES && !to);
278 fdev_set_events(hsrv->fdev, EPOLLIN);
281 void afb_hsrv_run(struct afb_hsrv *hsrv)
283 fdev_set_events(hsrv->fdev, 0);
284 if (jobs_queue(hsrv, 0, do_run, hsrv) < 0)
288 static void listen_callback(void *hsrv, uint32_t revents, struct fdev *fdev)
293 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
298 static struct hsrv_handler *new_handler(
299 struct hsrv_handler *head,
301 int (*handler) (struct afb_hreq *, void *),
305 struct hsrv_handler *link, *iter, *previous;
308 /* get the length of the prefix without its leading / */
309 length = strlen(prefix);
310 while (length && prefix[length - 1] == '/')
313 /* allocates the new link */
314 link = malloc(sizeof *link);
319 link->prefix = prefix;
320 link->length = length;
321 link->handler = handler;
323 link->priority = priority;
328 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
333 if (previous == NULL)
335 previous->next = link;
339 static int handle_alias(struct afb_hreq *hreq, void *data)
342 struct hsrv_alias *da = data;
343 struct locale_search *search;
345 if (hreq->method != afb_method_get) {
348 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
352 search = locale_root_search(da->root, hreq->lang, 0);
353 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
354 locale_search_unref(search);
358 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
363 int afb_hsrv_add_handler(
364 struct afb_hsrv *hsrv,
366 int (*handler) (struct afb_hreq *, void *),
370 struct hsrv_handler *head;
372 head = new_handler(hsrv->handlers, prefix, handler, data, priority);
375 hsrv->handlers = head;
379 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
381 struct hsrv_alias *da;
383 da = malloc(sizeof *da);
387 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
388 locale_root_addref(root);
396 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
398 struct locale_root *root;
401 root = locale_root_create_at(dirfd, alias);
403 ERROR("can't connect to directory %s: %m", alias);
406 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
407 locale_root_unref(root);
412 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
417 rc = asprintf(&dur, "%d", duration);
421 free(hsrv->cache_to);
422 hsrv->cache_to = dur;
426 int afb_hsrv_start(struct afb_hsrv *hsrv, unsigned int connection_timeout)
429 struct MHD_Daemon *httpd;
430 const union MHD_DaemonInfo *info;
432 httpd = MHD_start_daemon(
435 | MHD_USE_TCP_FASTOPEN
436 | MHD_USE_NO_LISTEN_SOCKET
438 | MHD_ALLOW_SUSPEND_RESUME,
440 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
441 access_handler, hsrv, /* Http Request Call back + extra attribute */
442 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
443 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
444 MHD_OPTION_END); /* options-end */
447 ERROR("httpStart invalid httpd");
451 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD);
453 MHD_stop_daemon(httpd);
454 ERROR("httpStart no pollfd");
458 fdev = afb_fdev_create(info->epoll_fd);
460 MHD_stop_daemon(httpd);
461 ERROR("connection to events for httpd failed");
464 fdev_set_autoclose(fdev, 0);
465 fdev_set_events(fdev, EPOLLIN);
466 fdev_set_callback(fdev, listen_callback, hsrv);
473 void afb_hsrv_stop(struct afb_hsrv *hsrv)
475 if (hsrv->fdev != NULL) {
476 fdev_unref(hsrv->fdev);
479 if (hsrv->httpd != NULL)
480 MHD_stop_daemon(hsrv->httpd);
484 struct afb_hsrv *afb_hsrv_create()
486 struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
488 result->refcount = 1;
492 void afb_hsrv_put(struct afb_hsrv *hsrv)
494 assert(hsrv->refcount != 0);
495 if (!--hsrv->refcount) {
501 static int hsrv_itf_connect(struct hsrv_itf *itf);
503 static void hsrv_itf_callback(void *closure, uint32_t revents, struct fdev *fdev)
505 struct hsrv_itf *itf = closure;
507 struct sockaddr addr;
510 if ((revents & EPOLLHUP) != 0) {
511 ERROR("disconnection for server %s: %m", itf->uri);
512 hsrv_itf_connect(itf);
514 } else if ((revents & EPOLLIN) != 0) {
515 lenaddr = (socklen_t)sizeof addr;
516 fd = accept(fdev_fd(fdev), &addr, &lenaddr);
518 ERROR("can't accept connection to %s: %m", itf->uri);
520 sts = MHD_add_connection(itf->hsrv->httpd, fd, &addr, lenaddr);
521 if (sts != MHD_YES) {
522 ERROR("can't add incoming connection to %s: %m", itf->uri);
529 static int hsrv_itf_connect(struct hsrv_itf *itf)
531 struct sockaddr addr;
533 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
536 itf->fdev = afb_socket_open_fdev(itf->uri, 1);
538 ERROR("can't create socket %s", itf->uri);
541 fdev_set_events(itf->fdev, EPOLLIN);
542 fdev_set_callback(itf->fdev, hsrv_itf_callback, itf);
543 memset(&addr, 0, sizeof addr);
544 lenaddr = (socklen_t)sizeof addr;
545 getsockname(fdev_fd(itf->fdev), &addr, &lenaddr);
546 if (addr.sa_family == AF_INET && !((struct sockaddr_in*)&addr)->sin_addr.s_addr) {
547 strncpy(hbuf, "*", NI_MAXHOST);
548 sprintf(sbuf, "%d", (int)ntohs(((struct sockaddr_in*)&addr)->sin_port));
550 rgni = getnameinfo(&addr, lenaddr, hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICSERV);
552 ERROR("getnameinfo returned %d: %s", rgni, gai_strerror(rgni));
553 hbuf[0] = sbuf[0] = '?';
554 hbuf[1] = sbuf[1] = 0;
557 NOTICE("Listening interface %s:%s", hbuf, sbuf);
561 int afb_hsrv_add_interface(struct afb_hsrv *hsrv, const char *uri)
563 struct hsrv_itf *itf;
565 itf = malloc(sizeof *itf + 1 + strlen(uri));
571 strcpy(itf->uri, uri);
572 itf->next = hsrv->interfaces;
573 hsrv->interfaces = itf;
574 return hsrv_itf_connect(itf);
577 int afb_hsrv_add_interface_tcp(struct afb_hsrv *hsrv, const char *itf, uint16_t port)
583 itf = "*"; /* awaiting getifaddrs impl */
585 rc = snprintf(buffer, sizeof buffer, "tcp:%s:%d", itf, (int)port);
586 if (rc < 0 || rc >= (int)sizeof buffer) {
591 return afb_hsrv_add_interface(hsrv, buffer);