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"
36 #define JSON_CONTENT "application/json"
37 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
40 struct afb_hsrv_handler {
41 struct afb_hsrv_handler *next;
44 int (*handler) (struct afb_hreq *, void *);
51 const char *directory;
56 int afb_hreq_one_page_api_redirect(
57 struct afb_hreq *hreq,
63 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
66 * Here we have for example:
67 * url = "/pre/dir/page" lenurl = 13
68 * tail = "/dir/page" lentail = 9
70 * We will produce "/pre/#!dir/page"
72 * Let compute plen that include the / at end (for "/pre/")
74 plen = hreq->lenurl - hreq->lentail + 1;
75 url = alloca(hreq->lenurl + 3);
76 memcpy(url, hreq->url, plen);
79 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
80 return afb_hreq_redirect_to(hreq, url);
83 static struct afb_hsrv_handler *new_handler(
84 struct afb_hsrv_handler *head,
86 int (*handler) (struct afb_hreq *, void *),
90 struct afb_hsrv_handler *link, *iter, *previous;
93 /* get the length of the prefix without its leading / */
94 length = strlen(prefix);
95 while (length && prefix[length - 1] == '/')
98 /* allocates the new link */
99 link = malloc(sizeof *link);
104 link->prefix = prefix;
105 link->length = length;
106 link->handler = handler;
108 link->priority = priority;
113 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
118 if (previous == NULL)
120 previous->next = link;
124 int afb_hsrv_add_handler(
125 AFB_session * session,
127 int (*handler) (struct afb_hreq *, void *),
131 struct afb_hsrv_handler *head;
133 head = new_handler(session->handlers, prefix, handler, data, priority);
136 session->handlers = head;
140 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
144 afb_hreq_context(hreq);
145 if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
149 struct afb_websock *ws = afb_websock_create(hreq->connection);
159 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
161 const char *api, *verb;
162 size_t lenapi, lenverb;
163 struct AFB_clientCtx *context;
165 api = &hreq->tail[strspn(hreq->tail, "/")];
166 lenapi = strcspn(api, "/");
168 verb = &verb[strspn(verb, "/")];
169 lenverb = strcspn(verb, "/");
171 if (!(*api && *verb && lenapi && lenverb))
174 context = afb_hreq_context(hreq);
175 return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
178 static int handle_alias(struct afb_hreq *hreq, void *data)
180 struct afb_diralias *da = data;
182 if (hreq->method != afb_method_get) {
183 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
187 if (!afb_hreq_valid_tail(hreq)) {
188 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
192 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
195 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
197 struct afb_diralias *da;
200 dirfd = open(alias, O_PATH|O_DIRECTORY);
205 da = malloc(sizeof *da);
208 da->directory = alias;
209 da->lendir = strlen(da->directory);
211 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
219 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
223 struct MHD_Response *response;
225 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
227 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
229 buffer = "<html><body>error</body></html>";
230 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
232 if (!MHD_queue_response(connection, status, response))
233 fprintf(stderr, "Failed to reply error code %u", status);
234 MHD_destroy_response(response);
237 static int postproc(void *cls,
238 enum MHD_ValueKind kind,
240 const char *filename,
241 const char *content_type,
242 const char *transfer_encoding,
247 struct afb_hreq *hreq = cls;
248 if (filename != NULL)
249 return afb_hreq_post_add_file(hreq, key, filename, data, size);
251 return afb_hreq_post_add(hreq, key, data, size);
254 static int access_handler(
256 struct MHD_Connection *connection,
258 const char *methodstr,
260 const char *upload_data,
261 size_t *upload_data_size,
265 struct afb_hreq *hreq;
266 enum afb_method method;
267 AFB_session *session;
268 struct afb_hsrv_handler *iter;
274 /* create the request */
275 hreq = calloc(1, sizeof *hreq);
281 method = get_method(methodstr);
282 method &= afb_method_get | afb_method_post;
283 if (method == afb_method_none)
286 /* init the request */
288 hreq->connection = connection;
289 hreq->method = method;
290 hreq->version = version;
291 hreq->tail = hreq->url = url;
292 hreq->lentail = hreq->lenurl = strlen(url);
294 /* init the post processing */
295 if (method == afb_method_post) {
296 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
298 /* an empty post, let's process it as a get */
299 hreq->method = afb_method_get;
300 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
301 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
302 if (hreq->postform == NULL)
304 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
305 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
311 /* process further data */
312 if (*upload_data_size) {
313 if (hreq->postform != NULL) {
314 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
317 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
320 *upload_data_size = 0;
325 afb_hreq_post_end(hreq);
326 if (hreq->postform != NULL) {
327 rc = MHD_destroy_post_processor(hreq->postform);
328 hreq->postform = NULL;
333 /* search an handler for the request */
334 iter = session->handlers;
336 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
337 if (iter->handler(hreq, iter->data))
339 hreq->tail = hreq->url;
340 hreq->lentail = hreq->lenurl;
346 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
350 afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
354 afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
358 /* Because of POST call multiple time requestApi we need to free POST handle here */
359 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
360 enum MHD_RequestTerminationCode toe)
362 struct afb_hreq *hreq;
369 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
374 #if defined(USE_MAGIC_MIME_TYPE)
376 #if !defined(MAGIC_DB)
377 #define MAGIC_DB "/usr/share/misc/magic.mgc"
380 static int init_lib_magic (AFB_session *session)
382 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
384 printf("Loading mimetype default magic database\n");
386 session->magic = magic_open(MAGIC_MIME_TYPE);
387 if (session->magic == NULL) {
388 fprintf(stderr,"ERROR: unable to initialize magic library\n");
392 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
393 if (magic_load(session->magic, MAGIC_DB) != 0) {
394 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
395 magic_close(session->magic);
396 session->magic = NULL;
404 static int my_default_init(AFB_session * session)
408 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
411 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
414 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
415 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
418 if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
421 if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
427 AFB_error httpdStart(AFB_session * session)
429 if (!my_default_init(session)) {
430 printf("Error: initialisation of httpd failed");
434 #if defined(USE_MAGIC_MIME_TYPE)
435 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
436 init_lib_magic (session);
440 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
441 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
444 session->httpd = MHD_start_daemon(
445 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
446 (uint16_t) session->config->httpdPort, /* port */
447 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
448 access_handler, session, /* Http Request Call back + extra attribute */
449 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
450 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
451 MHD_OPTION_END); /* options-end */
453 if (session->httpd == NULL) {
454 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
461 AFB_error httpdLoop(AFB_session * session)
464 const union MHD_DaemonInfo *info;
467 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
469 printf("Error: httpLoop no pollfd");
472 pfd.fd = info->listen_fd;
476 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
479 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
480 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
481 MHD_run(session->httpd);
485 /* should never return from here */
489 int httpdStatus(AFB_session * session)
491 return MHD_run(session->httpd);
494 void httpdStop(AFB_session * session)
496 MHD_stop_daemon(session->httpd);