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.
19 #include <microhttpd.h>
24 #include "../include/local-def.h"
25 #include "afb-method.h"
27 #include "afb-websock.h"
29 #define JSON_CONTENT "application/json"
30 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
32 struct afb_hsrv_handler {
33 struct afb_hsrv_handler *next;
36 int (*handler) (struct afb_hreq *, void *);
43 const char *directory;
48 int afb_hreq_one_page_api_redirect(
49 struct afb_hreq *hreq,
55 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
58 * Here we have for example:
59 * url = "/pre/dir/page" lenurl = 13
60 * tail = "/dir/page" lentail = 9
62 * We will produce "/pre/#!dir/page"
64 * Let compute plen that include the / at end (for "/pre/")
66 plen = hreq->lenurl - hreq->lentail + 1;
67 url = alloca(hreq->lenurl + 3);
68 memcpy(url, hreq->url, plen);
71 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
72 return afb_hreq_redirect_to(hreq, url);
75 static struct afb_hsrv_handler *new_handler(
76 struct afb_hsrv_handler *head,
78 int (*handler) (struct afb_hreq *, void *),
82 struct afb_hsrv_handler *link, *iter, *previous;
85 /* get the length of the prefix without its leading / */
86 length = strlen(prefix);
87 while (length && prefix[length - 1] == '/')
90 /* allocates the new link */
91 link = malloc(sizeof *link);
96 link->prefix = prefix;
97 link->length = length;
98 link->handler = handler;
100 link->priority = priority;
105 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
110 if (previous == NULL)
112 previous->next = link;
116 int afb_hsrv_add_handler(
117 AFB_session * session,
119 int (*handler) (struct afb_hreq *, void *),
123 struct afb_hsrv_handler *head;
125 head = new_handler(session->handlers, prefix, handler, data, priority);
128 session->handlers = head;
132 static int relay_to_doRestApi(struct afb_hreq *hreq, void *data)
135 if (hreq->lentail == 0 && afb_websock_check(hreq, &later)) {
137 struct afb_websock *ws = afb_websock_create(hreq->connection);
144 return doRestApi(hreq->connection, hreq->session, &hreq->tail[1], get_method_name(hreq->method),
145 post->upload_data, post->upload_data_size, (void **)hreq->recorder);
149 static int handle_alias(struct afb_hreq *hreq, void *data)
151 struct afb_diralias *da = data;
153 if (hreq->method != afb_method_get) {
154 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
158 if (!afb_hreq_valid_tail(hreq)) {
159 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
163 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
166 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
168 struct afb_diralias *da;
171 dirfd = open(alias, O_PATH|O_DIRECTORY);
176 da = malloc(sizeof *da);
179 da->directory = alias;
180 da->lendir = strlen(da->directory);
182 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
190 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
194 struct MHD_Response *response;
196 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
198 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
200 buffer = "<html><body>error</body></html>";
201 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
203 if (!MHD_queue_response(connection, status, response))
204 fprintf(stderr, "Failed to reply error code %u", status);
205 MHD_destroy_response(response);
208 static int postproc(void *cls,
209 enum MHD_ValueKind kind,
211 const char *filename,
212 const char *content_type,
213 const char *transfer_encoding,
218 struct afb_hreq *hreq = cls;
219 if (filename != NULL)
220 return afb_hreq_post_add_file(hreq, key, filename, data, size);
222 return afb_hreq_post_add(hreq, key, data, size);
225 static int access_handler(
227 struct MHD_Connection *connection,
229 const char *methodstr,
231 const char *upload_data,
232 size_t *upload_data_size,
235 struct afb_hreq *hreq;
236 enum afb_method method;
237 AFB_session *session;
238 struct afb_hsrv_handler *iter;
244 /* create the request */
245 hreq = calloc(1, sizeof *hreq);
251 method = get_method(methodstr);
252 method &= afb_method_get | afb_method_post;
253 if (method == afb_method_none) {
254 afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
258 /* init the request */
260 hreq->connection = connection;
261 hreq->method = method;
262 hreq->version = version;
263 hreq->tail = hreq->url = url;
264 hreq->lentail = hreq->lenurl = strlen(url);
266 /* init the post processing */
267 if (method == afb_method_post) {
268 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
270 /* an empty post, let's process it as a get */
271 hreq->method = afb_method_get;
272 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
273 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
274 if (hreq->postform == NULL)
276 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
277 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
283 /* process further data */
284 if (*upload_data_size) {
285 if (hreq->postform != NULL) {
286 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
289 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
292 *upload_data_size = 0;
297 afb_hreq_post_end(hreq);
299 /* search an handler for the request */
300 iter = session->handlers;
302 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
303 if (iter->handler(hreq, iter->data))
305 hreq->tail = hreq->url;
306 hreq->lentail = hreq->lenurl;
312 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
316 afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
320 /* Because of POST call multiple time requestApi we need to free POST handle here */
321 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
322 enum MHD_RequestTerminationCode toe)
324 AFB_session *session;
325 struct afb_hreq *hreq;
331 if (hreq->postform != NULL)
332 MHD_destroy_post_processor(hreq->postform);
336 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
341 #if defined(USE_MAGIC_MIME_TYPE)
343 #if !defined(MAGIC_DB)
344 #define MAGIC_DB "/usr/share/misc/magic.mgc"
347 static int init_lib_magic (AFB_session *session)
349 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
351 printf("Loading mimetype default magic database\n");
353 session->magic = magic_open(MAGIC_MIME_TYPE);
354 if (session->magic == NULL) {
355 fprintf(stderr,"ERROR: unable to initialize magic library\n");
359 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
360 if (magic_load(session->magic, MAGIC_DB) != 0) {
361 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
362 magic_close(session->magic);
363 session->magic = NULL;
371 static int my_default_init(AFB_session * session)
375 if (!afb_hsrv_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
378 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
379 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
382 if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
385 if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
391 AFB_error httpdStart(AFB_session * session)
393 if (!my_default_init(session)) {
394 printf("Error: initialisation of httpd failed");
398 #if defined(USE_MAGIC_MIME_TYPE)
399 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
400 init_lib_magic (session);
404 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
405 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
408 session->httpd = MHD_start_daemon(
409 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
410 (uint16_t) session->config->httpdPort, /* port */
411 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
412 access_handler, session, /* Http Request Call back + extra attribute */
413 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
414 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
415 MHD_OPTION_END); /* options-end */
417 if (session->httpd == NULL) {
418 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
425 AFB_error httpdLoop(AFB_session * session)
428 const union MHD_DaemonInfo *info;
431 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
433 printf("Error: httpLoop no pollfd");
436 pfd.fd = info->listen_fd;
440 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
443 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
444 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
445 MHD_run(session->httpd);
449 /* should never return from here */
453 int httpdStatus(AFB_session * session)
455 return MHD_run(session->httpd);
458 void httpdStop(AFB_session * session)
460 MHD_stop_daemon(session->httpd);