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>
33 #include "afb-method.h"
34 #include "afb-context.h"
41 #include "locale-root.h"
43 #include "afb-systemd.h"
46 #define JSON_CONTENT "application/json"
47 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
51 struct hsrv_handler *next;
54 int (*handler) (struct afb_hreq *, void *);
60 struct locale_root *root;
66 struct hsrv_handler *handlers;
67 struct MHD_Daemon *httpd;
72 static void reply_error(struct MHD_Connection *connection, unsigned int status)
74 struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
75 MHD_queue_response(connection, status, response);
76 MHD_destroy_response(response);
79 static int postproc(void *cls,
80 enum MHD_ValueKind kind,
83 const char *content_type,
84 const char *transfer_encoding,
89 struct afb_hreq *hreq = cls;
91 return afb_hreq_post_add_file(hreq, key, filename, data, size);
93 return afb_hreq_post_add(hreq, key, data, size);
96 static int access_handler(
98 struct MHD_Connection *connection,
100 const char *methodstr,
102 const char *upload_data,
103 size_t *upload_data_size,
107 struct afb_hreq *hreq;
108 enum afb_method method;
109 struct afb_hsrv *hsrv;
110 struct hsrv_handler *iter;
112 enum json_tokener_error jerr;
118 method = get_method(methodstr);
119 method &= afb_method_get | afb_method_post;
120 if (method == afb_method_none) {
121 WARNING("Unsupported HTTP operation %s", methodstr);
122 reply_error(connection, MHD_HTTP_BAD_REQUEST);
126 /* create the request */
127 hreq = afb_hreq_create();
129 ERROR("Can't allocate 'hreq'");
130 reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
134 /* init the request */
136 hreq->cacheTimeout = hsrv->cache_to;
137 hreq->connection = connection;
138 hreq->method = method;
139 hreq->version = version;
140 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
141 hreq->tail = hreq->url = url;
142 hreq->lentail = hreq->lenurl = strlen(url);
145 /* init the post processing */
146 if (method == afb_method_post) {
147 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
149 /* an empty post, let's process it as a get */
150 hreq->method = afb_method_get;
151 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
152 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
153 if (hreq->postform == NULL) {
154 ERROR("Can't create POST processor");
155 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
158 } else if (strcasestr(type, JSON_CONTENT) != NULL) {
159 hreq->tokener = json_tokener_new();
160 if (hreq->tokener == NULL) {
161 ERROR("Can't create tokener for POST");
162 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
166 WARNING("Unsupported media type %s", type);
167 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
173 /* process further data */
174 if (*upload_data_size) {
175 if (hreq->postform != NULL) {
176 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
177 ERROR("error in POST processor");
178 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
181 } else if (hreq->tokener) {
182 hreq->json = json_tokener_parse_ex(hreq->tokener, upload_data, (int)*upload_data_size);
183 jerr = json_tokener_get_error(hreq->tokener);
184 if (jerr == json_tokener_continue) {
185 hreq->json = json_tokener_parse_ex(hreq->tokener, "", 1);
186 jerr = json_tokener_get_error(hreq->tokener);
188 if (jerr != json_tokener_success) {
189 ERROR("error in POST json: %s", json_tokener_error_desc(jerr));
190 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
194 *upload_data_size = 0;
199 if (hreq->postform != NULL) {
200 rc = MHD_destroy_post_processor(hreq->postform);
201 hreq->postform = NULL;
203 ERROR("error detected in POST processing");
204 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
208 if (hreq->tokener != NULL) {
209 json_tokener_free(hreq->tokener);
210 hreq->tokener = NULL;
213 if (hreq->scanned != 0) {
214 if (hreq->replied == 0 && hreq->suspended == 0) {
215 MHD_suspend_connection (connection);
221 /* search an handler for the request */
223 iter = hsrv->handlers;
225 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
226 if (iter->handler(hreq, iter->data)) {
227 if (hreq->replied == 0 && hreq->suspended == 0) {
228 MHD_suspend_connection (connection);
233 hreq->tail = hreq->url;
234 hreq->lentail = hreq->lenurl;
240 WARNING("Unhandled request to %s", hreq->url);
241 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
245 /* Because of POST call multiple time requestApi we need to free POST handle here */
246 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
247 enum MHD_RequestTerminationCode toe)
249 struct afb_hreq *hreq;
253 afb_hreq_unref(hreq);
257 static void do_run(int signum, void *arg)
259 MHD_UNSIGNED_LONG_LONG to;
260 struct afb_hsrv *hsrv = arg;
263 do { MHD_run(hsrv->httpd); } while(MHD_get_timeout(hsrv->httpd, &to) == MHD_YES && !to);
265 fdev_set_events(hsrv->fdev, EPOLLIN);
268 void afb_hsrv_run(struct afb_hsrv *hsrv)
270 fdev_set_events(hsrv->fdev, 0);
271 if (jobs_queue(hsrv, 0, do_run, hsrv) < 0)
275 static void listen_callback(void *hsrv, uint32_t revents, struct fdev *fdev)
280 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
285 static struct hsrv_handler *new_handler(
286 struct hsrv_handler *head,
288 int (*handler) (struct afb_hreq *, void *),
292 struct hsrv_handler *link, *iter, *previous;
295 /* get the length of the prefix without its leading / */
296 length = strlen(prefix);
297 while (length && prefix[length - 1] == '/')
300 /* allocates the new link */
301 link = malloc(sizeof *link);
306 link->prefix = prefix;
307 link->length = length;
308 link->handler = handler;
310 link->priority = priority;
315 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
320 if (previous == NULL)
322 previous->next = link;
326 static int handle_alias(struct afb_hreq *hreq, void *data)
329 struct hsrv_alias *da = data;
330 struct locale_search *search;
332 if (hreq->method != afb_method_get) {
335 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
339 search = locale_root_search(da->root, hreq->lang, 0);
340 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
341 locale_search_unref(search);
345 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
350 int afb_hsrv_add_handler(
351 struct afb_hsrv *hsrv,
353 int (*handler) (struct afb_hreq *, void *),
357 struct hsrv_handler *head;
359 head = new_handler(hsrv->handlers, prefix, handler, data, priority);
362 hsrv->handlers = head;
366 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
368 struct hsrv_alias *da;
370 da = malloc(sizeof *da);
374 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
375 locale_root_addref(root);
383 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
385 struct locale_root *root;
388 root = locale_root_create_at(dirfd, alias);
390 ERROR("can't connect to directory %s: %m", alias);
393 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
394 locale_root_unref(root);
399 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
404 rc = asprintf(&dur, "%d", duration);
408 free(hsrv->cache_to);
409 hsrv->cache_to = dur;
413 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
416 struct MHD_Daemon *httpd;
417 const union MHD_DaemonInfo *info;
419 httpd = MHD_start_daemon(
420 MHD_USE_EPOLL | MHD_ALLOW_UPGRADE | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
422 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
423 access_handler, hsrv, /* Http Request Call back + extra attribute */
424 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
425 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
426 MHD_OPTION_END); /* options-end */
429 ERROR("httpStart invalid httpd port: %d", (int)port);
433 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
435 MHD_stop_daemon(httpd);
436 ERROR("httpStart no pollfd");
440 fdev = afb_fdev_create(info->listen_fd);
442 MHD_stop_daemon(httpd);
443 ERROR("connection to events for httpd failed");
446 fdev_set_autoclose(fdev, 0);
447 fdev_set_events(fdev, EPOLLIN);
448 fdev_set_callback(fdev, listen_callback, hsrv);
455 void afb_hsrv_stop(struct afb_hsrv *hsrv)
457 if (hsrv->fdev != NULL) {
458 fdev_unref(hsrv->fdev);
461 if (hsrv->httpd != NULL)
462 MHD_stop_daemon(hsrv->httpd);
466 struct afb_hsrv *afb_hsrv_create()
468 struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
470 result->refcount = 1;
474 void afb_hsrv_put(struct afb_hsrv *hsrv)
476 assert(hsrv->refcount != 0);
477 if (!--hsrv->refcount) {