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"
30 struct afb_hsrv_handler {
31 struct afb_hsrv_handler *next;
34 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *);
41 const char *directory;
46 int afb_hreq_one_page_api_redirect(
47 struct afb_hreq *hreq,
48 struct afb_hreq_post *post,
54 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
57 * Here we have for example:
58 * url = "/pre/dir/page" lenurl = 13
59 * tail = "/dir/page" lentail = 9
61 * We will produce "/pre/#!dir/page"
63 * Let compute plen that include the / at end (for "/pre/")
65 plen = hreq->lenurl - hreq->lentail + 1;
66 url = alloca(hreq->lenurl + 3);
67 memcpy(url, hreq->url, plen);
70 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
71 return afb_hreq_redirect_to(hreq, url);
74 struct afb_hsrv_handler *afb_hsrv_handler_new(
75 struct afb_hsrv_handler *head,
77 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
81 struct afb_hsrv_handler *link, *iter, *previous;
84 /* get the length of the prefix without its leading / */
85 length = strlen(prefix);
86 while (length && prefix[length - 1] == '/')
89 /* allocates the new link */
90 link = malloc(sizeof *link);
95 link->prefix = prefix;
96 link->length = length;
97 link->handler = handler;
99 link->priority = priority;
104 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
109 if (previous == NULL)
111 previous->next = link;
115 int afb_req_add_handler(
116 AFB_session * session,
118 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
122 struct afb_hsrv_handler *head;
124 head = afb_hsrv_handler_new(session->handlers, prefix, handler, data, priority);
127 session->handlers = head;
131 static int relay_to_doRestApi(struct afb_hreq *hreq, struct afb_hreq_post *post, void *data)
134 if (afb_websock_check(hreq, &later)) {
136 struct afb_websock *ws = afb_websock_create(hreq->connection);
141 return doRestApi(hreq->connection, hreq->session, &hreq->tail[1], get_method_name(hreq->method),
142 post->upload_data, post->upload_data_size, (void **)hreq->recorder);
145 static int handle_alias(struct afb_hreq *hreq, struct afb_hreq_post *post, void *data)
147 struct afb_diralias *da = data;
149 if (hreq->method != afb_method_get) {
150 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
154 if (!afb_hreq_valid_tail(hreq)) {
155 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
159 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
162 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
164 struct afb_diralias *da;
167 dirfd = open(alias, O_PATH|O_DIRECTORY);
172 da = malloc(sizeof *da);
175 da->directory = alias;
176 da->lendir = strlen(da->directory);
178 if (afb_req_add_handler(session, prefix, handle_alias, da, priority))
186 static int my_default_init(AFB_session * session)
190 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
193 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
194 if (!afb_req_add_alias
195 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
198 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
201 if (!afb_req_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
207 static int access_handler(
209 struct MHD_Connection *connection,
211 const char *methodstr,
213 const char *upload_data,
214 size_t * upload_data_size,
217 struct afb_hreq_post post;
218 struct afb_hreq hreq;
219 enum afb_method method;
220 AFB_session *session;
221 struct afb_hsrv_handler *iter;
224 post.upload_data = upload_data;
225 post.upload_data_size = upload_data_size;
228 struct afb_hreq *previous;
230 previous = *recorder;
232 assert((void **)previous->recorder == recorder);
233 assert(previous->session == session);
234 assert(previous->connection == connection);
235 assert(previous->method == get_method(methodstr));
236 assert(previous->url == url);
240 assert(previous->post_handler != NULL);
241 previous->post_handler(previous, &post);
247 method = get_method(methodstr);
248 if (method == afb_method_none) {
249 afb_hreq_reply_error(&hreq, MHD_HTTP_BAD_REQUEST);
253 /* init the request */
255 hreq.connection = connection;
256 hreq.method = method;
257 hreq.version = version;
258 hreq.tail = hreq.url = url;
259 hreq.lentail = hreq.lenurl = strlen(url);
260 hreq.recorder = (struct afb_hreq **)recorder;
261 hreq.post_handler = NULL;
262 hreq.post_completed = NULL;
263 hreq.post_data = NULL;
265 /* search an handler for the request */
266 iter = session->handlers;
268 if (afb_hreq_unprefix(&hreq, iter->prefix, iter->length)) {
269 if (iter->handler(&hreq, &post, iter->data))
271 hreq.tail = hreq.url;
272 hreq.lentail = hreq.lenurl;
278 afb_hreq_reply_error(&hreq, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
282 /* Because of POST call multiple time requestApi we need to free POST handle here */
283 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
284 enum MHD_RequestTerminationCode toe)
286 AFB_PostHandle *posthandle = *con_cls;
288 /* if post handle was used let's free everything */
289 if (posthandle != NULL)
290 endPostRequest(posthandle);
293 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
298 #if defined(USE_MAGIC_MIME_TYPE)
300 #if !defined(MAGIC_DB)
301 #define MAGIC_DB "/usr/share/misc/magic.mgc"
304 static int init_lib_magic (AFB_session *session)
306 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
308 printf("Loading mimetype default magic database\n");
310 session->magic = magic_open(MAGIC_MIME_TYPE);
311 if (session->magic == NULL) {
312 fprintf(stderr,"ERROR: unable to initialize magic library\n");
316 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
317 if (magic_load(session->magic, MAGIC_DB) != 0) {
318 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
320 magic_close(session->magic);
321 session->magic = NULL;
330 AFB_error httpdStart(AFB_session * session)
333 if (!my_default_init(session)) {
334 printf("Error: initialisation of httpd failed");
338 #if defined(USE_MAGIC_MIME_TYPE)
339 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
340 init_lib_magic (session);
344 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
345 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
348 session->httpd = MHD_start_daemon(
349 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
350 (uint16_t) session->config->httpdPort, /* port */
351 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
352 access_handler, session, /* Http Request Call back + extra attribute */
353 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
354 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
355 MHD_OPTION_END); /* options-end */
357 if (session->httpd == NULL) {
358 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
365 AFB_error httpdLoop(AFB_session * session)
368 const union MHD_DaemonInfo *info;
371 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
373 printf("Error: httpLoop no pollfd");
376 pfd.fd = info->listen_fd;
380 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
383 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
384 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
385 MHD_run(session->httpd);
389 /* should never return from here */
393 int httpdStatus(AFB_session * session)
395 return MHD_run(session->httpd);
398 void httpdStop(AFB_session * session)
400 MHD_stop_daemon(session->httpd);