2 * Copyright (C) 2016, 2017, 2018 "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.
30 #include <json-c/json.h>
31 #include <microhttpd.h>
32 #if MHD_VERSION < 0x00095206
33 # define MHD_ALLOW_SUSPEND_RESUME MHD_USE_SUSPEND_RESUME
36 #include "afb-method.h"
37 #include "afb-context.h"
44 #include "locale-root.h"
46 #include "afb-systemd.h"
49 #define JSON_CONTENT "application/json"
50 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
54 struct hsrv_handler *next;
57 int (*handler) (struct afb_hreq *, void *);
63 struct locale_root *root;
69 struct hsrv_handler *handlers;
70 struct MHD_Daemon *httpd;
75 static void reply_error(struct MHD_Connection *connection, unsigned int status)
77 struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
78 MHD_queue_response(connection, status, response);
79 MHD_destroy_response(response);
82 static int postproc(void *cls,
83 enum MHD_ValueKind kind,
86 const char *content_type,
87 const char *transfer_encoding,
92 struct afb_hreq *hreq = cls;
94 return afb_hreq_post_add_file(hreq, key, filename, data, size);
96 return afb_hreq_post_add(hreq, key, data, size);
99 static int access_handler(
101 struct MHD_Connection *connection,
103 const char *methodstr,
105 const char *upload_data,
106 size_t *upload_data_size,
110 struct afb_hreq *hreq;
111 enum afb_method method;
112 struct afb_hsrv *hsrv;
113 struct hsrv_handler *iter;
115 enum json_tokener_error jerr;
121 method = get_method(methodstr);
122 method &= afb_method_get | afb_method_post;
123 if (method == afb_method_none) {
124 WARNING("Unsupported HTTP operation %s", methodstr);
125 reply_error(connection, MHD_HTTP_BAD_REQUEST);
129 /* create the request */
130 hreq = afb_hreq_create();
132 ERROR("Can't allocate 'hreq'");
133 reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
137 /* init the request */
139 hreq->cacheTimeout = hsrv->cache_to;
140 hreq->connection = connection;
141 hreq->method = method;
142 hreq->version = version;
143 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
144 hreq->tail = hreq->url = url;
145 hreq->lentail = hreq->lenurl = strlen(url);
148 /* init the post processing */
149 if (method == afb_method_post) {
150 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
152 /* an empty post, let's process it as a get */
153 hreq->method = afb_method_get;
154 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
155 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
156 if (hreq->postform == NULL) {
157 ERROR("Can't create POST processor");
158 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
161 } else if (strcasestr(type, JSON_CONTENT) != NULL) {
162 hreq->tokener = json_tokener_new();
163 if (hreq->tokener == NULL) {
164 ERROR("Can't create tokener for POST");
165 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
169 WARNING("Unsupported media type %s", type);
170 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
176 /* process further data */
177 if (*upload_data_size) {
178 if (hreq->postform != NULL) {
179 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
180 ERROR("error in POST processor");
181 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
184 } else if (hreq->tokener) {
185 hreq->json = json_tokener_parse_ex(hreq->tokener, upload_data, (int)*upload_data_size);
186 jerr = json_tokener_get_error(hreq->tokener);
187 if (jerr == json_tokener_continue) {
188 hreq->json = json_tokener_parse_ex(hreq->tokener, "", 1);
189 jerr = json_tokener_get_error(hreq->tokener);
191 if (jerr != json_tokener_success) {
192 ERROR("error in POST json: %s", json_tokener_error_desc(jerr));
193 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
197 *upload_data_size = 0;
202 if (hreq->postform != NULL) {
203 rc = MHD_destroy_post_processor(hreq->postform);
204 hreq->postform = NULL;
206 ERROR("error detected in POST processing");
207 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
211 if (hreq->tokener != NULL) {
212 json_tokener_free(hreq->tokener);
213 hreq->tokener = NULL;
216 if (hreq->scanned != 0) {
217 if (hreq->replied == 0 && hreq->suspended == 0) {
218 MHD_suspend_connection (connection);
224 /* search an handler for the request */
226 iter = hsrv->handlers;
228 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
229 if (iter->handler(hreq, iter->data)) {
230 if (hreq->replied == 0 && hreq->suspended == 0) {
231 MHD_suspend_connection (connection);
236 hreq->tail = hreq->url;
237 hreq->lentail = hreq->lenurl;
243 NOTICE("Unhandled request to %s", hreq->url);
244 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
248 /* Because of POST call multiple time requestApi we need to free POST handle here */
249 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
250 enum MHD_RequestTerminationCode toe)
252 struct afb_hreq *hreq;
256 afb_hreq_unref(hreq);
260 static void do_run(int signum, void *arg)
262 MHD_UNSIGNED_LONG_LONG to;
263 struct afb_hsrv *hsrv = arg;
266 do { MHD_run(hsrv->httpd); } while(MHD_get_timeout(hsrv->httpd, &to) == MHD_YES && !to);
268 fdev_set_events(hsrv->fdev, EPOLLIN);
271 void afb_hsrv_run(struct afb_hsrv *hsrv)
273 fdev_set_events(hsrv->fdev, 0);
274 if (jobs_queue(hsrv, 0, do_run, hsrv) < 0)
278 static void listen_callback(void *hsrv, uint32_t revents, struct fdev *fdev)
283 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
288 static struct hsrv_handler *new_handler(
289 struct hsrv_handler *head,
291 int (*handler) (struct afb_hreq *, void *),
295 struct hsrv_handler *link, *iter, *previous;
298 /* get the length of the prefix without its leading / */
299 length = strlen(prefix);
300 while (length && prefix[length - 1] == '/')
303 /* allocates the new link */
304 link = malloc(sizeof *link);
309 link->prefix = prefix;
310 link->length = length;
311 link->handler = handler;
313 link->priority = priority;
318 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
323 if (previous == NULL)
325 previous->next = link;
329 static int handle_alias(struct afb_hreq *hreq, void *data)
332 struct hsrv_alias *da = data;
333 struct locale_search *search;
335 if (hreq->method != afb_method_get) {
338 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
342 search = locale_root_search(da->root, hreq->lang, 0);
343 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
344 locale_search_unref(search);
348 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
353 int afb_hsrv_add_handler(
354 struct afb_hsrv *hsrv,
356 int (*handler) (struct afb_hreq *, void *),
360 struct hsrv_handler *head;
362 head = new_handler(hsrv->handlers, prefix, handler, data, priority);
365 hsrv->handlers = head;
369 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
371 struct hsrv_alias *da;
373 da = malloc(sizeof *da);
377 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
378 locale_root_addref(root);
386 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
388 struct locale_root *root;
391 root = locale_root_create_at(dirfd, alias);
393 ERROR("can't connect to directory %s: %m", alias);
396 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
397 locale_root_unref(root);
402 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
407 rc = asprintf(&dur, "%d", duration);
411 free(hsrv->cache_to);
412 hsrv->cache_to = dur;
416 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
419 struct MHD_Daemon *httpd;
420 const union MHD_DaemonInfo *info;
422 httpd = MHD_start_daemon(
423 MHD_USE_EPOLL | MHD_ALLOW_UPGRADE | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_ALLOW_SUSPEND_RESUME,
425 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
426 access_handler, hsrv, /* Http Request Call back + extra attribute */
427 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
428 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
429 MHD_OPTION_END); /* options-end */
432 ERROR("httpStart invalid httpd port: %d", (int)port);
436 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
438 MHD_stop_daemon(httpd);
439 ERROR("httpStart no pollfd");
443 fdev = afb_fdev_create(info->listen_fd);
445 MHD_stop_daemon(httpd);
446 ERROR("connection to events for httpd failed");
449 fdev_set_autoclose(fdev, 0);
450 fdev_set_events(fdev, EPOLLIN);
451 fdev_set_callback(fdev, listen_callback, hsrv);
458 void afb_hsrv_stop(struct afb_hsrv *hsrv)
460 if (hsrv->fdev != NULL) {
461 fdev_unref(hsrv->fdev);
464 if (hsrv->httpd != NULL)
465 MHD_stop_daemon(hsrv->httpd);
469 struct afb_hsrv *afb_hsrv_create()
471 struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
473 result->refcount = 1;
477 void afb_hsrv_put(struct afb_hsrv *hsrv)
479 assert(hsrv->refcount != 0);
480 if (!--hsrv->refcount) {