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 #include "utils-upoll.h"
38 #define JSON_CONTENT "application/json"
39 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
42 struct afb_hsrv_handler {
43 struct afb_hsrv_handler *next;
46 int (*handler) (struct afb_hreq *, void *);
53 const char *directory;
58 static struct upoll *upoll = NULL;
60 int afb_hreq_one_page_api_redirect(
61 struct afb_hreq *hreq,
67 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
70 * Here we have for example:
71 * url = "/pre/dir/page" lenurl = 13
72 * tail = "/dir/page" lentail = 9
74 * We will produce "/pre/#!dir/page"
76 * Let compute plen that include the / at end (for "/pre/")
78 plen = hreq->lenurl - hreq->lentail + 1;
79 url = alloca(hreq->lenurl + 3);
80 memcpy(url, hreq->url, plen);
83 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
84 return afb_hreq_redirect_to(hreq, url);
87 static struct afb_hsrv_handler *new_handler(
88 struct afb_hsrv_handler *head,
90 int (*handler) (struct afb_hreq *, void *),
94 struct afb_hsrv_handler *link, *iter, *previous;
97 /* get the length of the prefix without its leading / */
98 length = strlen(prefix);
99 while (length && prefix[length - 1] == '/')
102 /* allocates the new link */
103 link = malloc(sizeof *link);
108 link->prefix = prefix;
109 link->length = length;
110 link->handler = handler;
112 link->priority = priority;
117 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
122 if (previous == NULL)
124 previous->next = link;
128 int afb_hsrv_add_handler(
129 AFB_session * session,
131 int (*handler) (struct afb_hreq *, void *),
135 struct afb_hsrv_handler *head;
137 head = new_handler(session->handlers, prefix, handler, data, priority);
140 session->handlers = head;
144 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
148 afb_hreq_context(hreq);
149 if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
153 struct afb_websock *ws = afb_websock_create(hreq->connection);
163 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
165 const char *api, *verb;
166 size_t lenapi, lenverb;
167 struct AFB_clientCtx *context;
169 api = &hreq->tail[strspn(hreq->tail, "/")];
170 lenapi = strcspn(api, "/");
172 verb = &verb[strspn(verb, "/")];
173 lenverb = strcspn(verb, "/");
175 if (!(*api && *verb && lenapi && lenverb))
178 context = afb_hreq_context(hreq);
179 return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
182 static int handle_alias(struct afb_hreq *hreq, void *data)
184 struct afb_diralias *da = data;
186 if (hreq->method != afb_method_get) {
187 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
191 if (!afb_hreq_valid_tail(hreq)) {
192 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
196 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
199 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
201 struct afb_diralias *da;
204 dirfd = open(alias, O_PATH|O_DIRECTORY);
209 da = malloc(sizeof *da);
212 da->directory = alias;
213 da->lendir = strlen(da->directory);
215 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
223 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
227 struct MHD_Response *response;
229 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
231 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
233 buffer = "<html><body>error</body></html>";
234 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
236 if (!MHD_queue_response(connection, status, response))
237 fprintf(stderr, "Failed to reply error code %u", status);
238 MHD_destroy_response(response);
241 static int postproc(void *cls,
242 enum MHD_ValueKind kind,
244 const char *filename,
245 const char *content_type,
246 const char *transfer_encoding,
251 struct afb_hreq *hreq = cls;
252 if (filename != NULL)
253 return afb_hreq_post_add_file(hreq, key, filename, data, size);
255 return afb_hreq_post_add(hreq, key, data, size);
258 static int access_handler(
260 struct MHD_Connection *connection,
262 const char *methodstr,
264 const char *upload_data,
265 size_t *upload_data_size,
269 struct afb_hreq *hreq;
270 enum afb_method method;
271 AFB_session *session;
272 struct afb_hsrv_handler *iter;
278 /* create the request */
279 hreq = calloc(1, sizeof *hreq);
285 method = get_method(methodstr);
286 method &= afb_method_get | afb_method_post;
287 if (method == afb_method_none)
290 /* init the request */
292 hreq->connection = connection;
293 hreq->method = method;
294 hreq->version = version;
295 hreq->tail = hreq->url = url;
296 hreq->lentail = hreq->lenurl = strlen(url);
298 /* init the post processing */
299 if (method == afb_method_post) {
300 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
302 /* an empty post, let's process it as a get */
303 hreq->method = afb_method_get;
304 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
305 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
306 if (hreq->postform == NULL)
308 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
309 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
315 /* process further data */
316 if (*upload_data_size) {
317 if (hreq->postform != NULL) {
318 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
321 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
324 *upload_data_size = 0;
329 afb_hreq_post_end(hreq);
330 if (hreq->postform != NULL) {
331 rc = MHD_destroy_post_processor(hreq->postform);
332 hreq->postform = NULL;
337 /* search an handler for the request */
338 iter = session->handlers;
340 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
341 if (iter->handler(hreq, iter->data))
343 hreq->tail = hreq->url;
344 hreq->lentail = hreq->lenurl;
350 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
354 afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
358 afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
362 /* Because of POST call multiple time requestApi we need to free POST handle here */
363 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
364 enum MHD_RequestTerminationCode toe)
366 struct afb_hreq *hreq;
373 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
378 #if defined(USE_MAGIC_MIME_TYPE)
380 #if !defined(MAGIC_DB)
381 #define MAGIC_DB "/usr/share/misc/magic.mgc"
384 static int init_lib_magic (AFB_session *session)
386 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
388 printf("Loading mimetype default magic database\n");
390 session->magic = magic_open(MAGIC_MIME_TYPE);
391 if (session->magic == NULL) {
392 fprintf(stderr,"ERROR: unable to initialize magic library\n");
396 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
397 if (magic_load(session->magic, MAGIC_DB) != 0) {
398 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
399 magic_close(session->magic);
400 session->magic = NULL;
408 static int my_default_init(AFB_session * session)
412 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
415 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
418 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
419 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
422 if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
425 if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
428 #if defined(USE_MAGIC_MIME_TYPE)
429 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
430 init_lib_magic (session);
437 static void hsrv_handle_event(struct MHD_Daemon *httpd)
442 int afb_hsrv_start(AFB_session * session)
444 struct MHD_Daemon *httpd;
445 const union MHD_DaemonInfo *info;
447 if (!my_default_init(session)) {
448 printf("Error: initialisation of httpd failed");
453 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
454 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
457 httpd = MHD_start_daemon(
458 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
459 (uint16_t) session->config->httpdPort, /* port */
460 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
461 access_handler, session, /* Http Request Call back + extra attribute */
462 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
463 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
464 MHD_OPTION_END); /* options-end */
467 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
471 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
473 MHD_stop_daemon(httpd);
474 fprintf(stderr, "Error: httpStart no pollfd");
478 upoll = upoll_open(info->listen_fd, httpd);
480 MHD_stop_daemon(httpd);
481 fprintf(stderr, "Error: connection to upoll of httpd failed");
484 upoll_on_readable(upoll, (void*)hsrv_handle_event);
486 session->httpd = httpd;
490 void afb_hsrv_stop(AFB_session * session)
495 if (session->httpd != NULL)
496 MHD_stop_daemon(session->httpd);
497 session->httpd = NULL;