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.
27 #include <microhttpd.h>
29 #include "local-def.h"
30 #include "afb-method.h"
32 #include "afb-websock.h"
34 #include "afb-req-itf.h"
37 #define JSON_CONTENT "application/json"
38 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
41 struct afb_hsrv_handler {
42 struct afb_hsrv_handler *next;
45 int (*handler) (struct afb_hreq *, void *);
52 const char *directory;
57 int afb_hreq_one_page_api_redirect(
58 struct afb_hreq *hreq,
64 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
67 * Here we have for example:
68 * url = "/pre/dir/page" lenurl = 13
69 * tail = "/dir/page" lentail = 9
71 * We will produce "/pre/#!dir/page"
73 * Let compute plen that include the / at end (for "/pre/")
75 plen = hreq->lenurl - hreq->lentail + 1;
76 url = alloca(hreq->lenurl + 3);
77 memcpy(url, hreq->url, plen);
80 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
81 return afb_hreq_redirect_to(hreq, url);
84 static struct afb_hsrv_handler *new_handler(
85 struct afb_hsrv_handler *head,
87 int (*handler) (struct afb_hreq *, void *),
91 struct afb_hsrv_handler *link, *iter, *previous;
94 /* get the length of the prefix without its leading / */
95 length = strlen(prefix);
96 while (length && prefix[length - 1] == '/')
99 /* allocates the new link */
100 link = malloc(sizeof *link);
105 link->prefix = prefix;
106 link->length = length;
107 link->handler = handler;
109 link->priority = priority;
114 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
119 if (previous == NULL)
121 previous->next = link;
125 int afb_hsrv_add_handler(
126 AFB_session * session,
128 int (*handler) (struct afb_hreq *, void *),
132 struct afb_hsrv_handler *head;
134 head = new_handler(session->handlers, prefix, handler, data, priority);
137 session->handlers = head;
141 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
145 afb_hreq_context(hreq);
146 if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
150 struct afb_websock *ws = afb_websock_create(hreq->connection);
160 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
162 const char *api, *verb;
163 size_t lenapi, lenverb;
164 struct AFB_clientCtx *context;
166 api = &hreq->tail[strspn(hreq->tail, "/")];
167 lenapi = strcspn(api, "/");
169 verb = &verb[strspn(verb, "/")];
170 lenverb = strcspn(verb, "/");
172 if (!(*api && *verb && lenapi && lenverb))
175 context = afb_hreq_context(hreq);
176 return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
179 static int handle_alias(struct afb_hreq *hreq, void *data)
181 struct afb_diralias *da = data;
183 if (hreq->method != afb_method_get) {
184 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
188 if (!afb_hreq_valid_tail(hreq)) {
189 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
193 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
196 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
198 struct afb_diralias *da;
201 dirfd = open(alias, O_PATH|O_DIRECTORY);
206 da = malloc(sizeof *da);
209 da->directory = alias;
210 da->lendir = strlen(da->directory);
212 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
220 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
224 struct MHD_Response *response;
226 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
228 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
230 buffer = "<html><body>error</body></html>";
231 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
233 if (!MHD_queue_response(connection, status, response))
234 fprintf(stderr, "Failed to reply error code %u", status);
235 MHD_destroy_response(response);
238 static int postproc(void *cls,
239 enum MHD_ValueKind kind,
241 const char *filename,
242 const char *content_type,
243 const char *transfer_encoding,
248 struct afb_hreq *hreq = cls;
249 if (filename != NULL)
250 return afb_hreq_post_add_file(hreq, key, filename, data, size);
252 return afb_hreq_post_add(hreq, key, data, size);
255 static int access_handler(
257 struct MHD_Connection *connection,
259 const char *methodstr,
261 const char *upload_data,
262 size_t *upload_data_size,
266 struct afb_hreq *hreq;
267 enum afb_method method;
268 AFB_session *session;
269 struct afb_hsrv_handler *iter;
275 /* create the request */
276 hreq = calloc(1, sizeof *hreq);
282 method = get_method(methodstr);
283 method &= afb_method_get | afb_method_post;
284 if (method == afb_method_none)
287 /* init the request */
289 hreq->connection = connection;
290 hreq->method = method;
291 hreq->version = version;
292 hreq->tail = hreq->url = url;
293 hreq->lentail = hreq->lenurl = strlen(url);
295 /* init the post processing */
296 if (method == afb_method_post) {
297 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
299 /* an empty post, let's process it as a get */
300 hreq->method = afb_method_get;
301 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
302 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
303 if (hreq->postform == NULL)
305 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
306 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
312 /* process further data */
313 if (*upload_data_size) {
314 if (hreq->postform != NULL) {
315 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
318 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
321 *upload_data_size = 0;
326 afb_hreq_post_end(hreq);
327 if (hreq->postform != NULL) {
328 rc = MHD_destroy_post_processor(hreq->postform);
329 hreq->postform = NULL;
334 /* search an handler for the request */
335 iter = session->handlers;
337 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
338 if (iter->handler(hreq, iter->data))
340 hreq->tail = hreq->url;
341 hreq->lentail = hreq->lenurl;
347 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
351 afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
355 afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
359 /* Because of POST call multiple time requestApi we need to free POST handle here */
360 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
361 enum MHD_RequestTerminationCode toe)
363 struct afb_hreq *hreq;
370 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
375 #if defined(USE_MAGIC_MIME_TYPE)
377 #if !defined(MAGIC_DB)
378 #define MAGIC_DB "/usr/share/misc/magic.mgc"
381 static int init_lib_magic (AFB_session *session)
383 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
385 printf("Loading mimetype default magic database\n");
387 session->magic = magic_open(MAGIC_MIME_TYPE);
388 if (session->magic == NULL) {
389 fprintf(stderr,"ERROR: unable to initialize magic library\n");
393 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
394 if (magic_load(session->magic, MAGIC_DB) != 0) {
395 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
396 magic_close(session->magic);
397 session->magic = NULL;
405 static int my_default_init(AFB_session * session)
409 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
412 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
415 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
416 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
419 if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
422 if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
428 AFB_error httpdStart(AFB_session * session)
430 if (!my_default_init(session)) {
431 printf("Error: initialisation of httpd failed");
435 #if defined(USE_MAGIC_MIME_TYPE)
436 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
437 init_lib_magic (session);
441 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
442 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
445 session->httpd = MHD_start_daemon(
446 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
447 (uint16_t) session->config->httpdPort, /* port */
448 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
449 access_handler, session, /* Http Request Call back + extra attribute */
450 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
451 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
452 MHD_OPTION_END); /* options-end */
454 if (session->httpd == NULL) {
455 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
462 AFB_error httpdLoop(AFB_session * session)
465 const union MHD_DaemonInfo *info;
468 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
470 printf("Error: httpLoop no pollfd");
473 pfd.fd = info->listen_fd;
477 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
480 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
481 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
482 MHD_run(session->httpd);
486 /* should never return from here */
490 int httpdStatus(AFB_session * session)
492 return MHD_run(session->httpd);
495 void httpdStop(AFB_session * session)
497 MHD_stop_daemon(session->httpd);