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"
29 struct afb_hsrv_handler {
30 struct afb_hsrv_handler *next;
33 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *);
40 const char *directory;
46 int afb_request_one_page_api_redirect(
47 struct afb_hreq *request,
48 struct afb_hreq_post *post,
54 if (request->lentail >= 2 && request->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 = request->lenurl - request->lentail + 1;
66 url = alloca(request->lenurl + 3);
67 memcpy(url, request->url, plen);
70 memcpy(&url[plen], &request->tail[1], request->lentail);
71 return afb_hreq_redirect_to(request, 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 *request, struct afb_hreq_post *post, void *data)
133 return doRestApi(request->connection, request->session, &request->tail[1], get_method_name(request->method),
134 post->upload_data, post->upload_data_size, (void **)request->recorder);
137 static int handle_alias(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
139 struct afb_diralias *da = data;
141 if (request->method != afb_method_get) {
142 afb_hreq_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
146 if (!afb_hreq_valid_tail(request)) {
147 afb_hreq_reply_error(request, MHD_HTTP_FORBIDDEN);
151 return afb_hreq_reply_file(request, da->dirfd, &request->tail[1]);
154 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
156 struct afb_diralias *da;
159 dirfd = open(alias, O_PATH|O_DIRECTORY);
164 da = malloc(sizeof *da);
167 da->directory = alias;
168 da->lendir = strlen(da->directory);
170 if (afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority))
178 static int my_default_init(AFB_session * session)
182 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
185 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
186 if (!afb_req_add_alias
187 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
190 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
193 if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
199 static int access_handler(
201 struct MHD_Connection *connection,
203 const char *methodstr,
205 const char *upload_data,
206 size_t * upload_data_size,
209 struct afb_hreq_post post;
210 struct afb_hreq request;
211 enum afb_method method;
212 AFB_session *session;
213 struct afb_hsrv_handler *iter;
216 post.upload_data = upload_data;
217 post.upload_data_size = upload_data_size;
220 struct afb_hreq *previous;
222 previous = *recorder;
224 assert((void **)previous->recorder == recorder);
225 assert(previous->session == session);
226 assert(previous->connection == connection);
227 assert(previous->method == get_method(methodstr));
228 assert(previous->url == url);
232 assert(previous->post_handler != NULL);
233 previous->post_handler(previous, &post);
239 method = get_method(methodstr);
240 if (method == afb_method_none) {
241 afb_hreq_reply_error(&request, MHD_HTTP_BAD_REQUEST);
245 /* init the request */
246 request.session = cls;
247 request.connection = connection;
248 request.method = method;
249 request.tail = request.url = url;
250 request.lentail = request.lenurl = strlen(url);
251 request.recorder = (struct afb_hreq **)recorder;
252 request.post_handler = NULL;
253 request.post_completed = NULL;
254 request.post_data = NULL;
256 /* search an handler for the request */
257 iter = session->handlers;
259 if (afb_hreq_unprefix(&request, iter->prefix, iter->length)) {
260 if (iter->handler(&request, &post, iter->data))
262 request.tail = request.url;
263 request.lentail = request.lenurl;
269 afb_hreq_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
273 /* Because of POST call multiple time requestApi we need to free POST handle here */
274 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
275 enum MHD_RequestTerminationCode toe)
277 AFB_PostHandle *posthandle = *con_cls;
279 /* if post handle was used let's free everything */
280 if (posthandle != NULL)
281 endPostRequest(posthandle);
284 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
289 #if defined(USE_MAGIC_MIME_TYPE)
291 #if !defined(MAGIC_DB)
292 #define MAGIC_DB "/usr/share/misc/magic.mgc"
295 static int init_lib_magic (AFB_session *session)
297 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
299 printf("Loading mimetype default magic database\n");
301 session->magic = magic_open(MAGIC_MIME_TYPE);
302 if (session->magic == NULL) {
303 fprintf(stderr,"ERROR: unable to initialize magic library\n");
307 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
308 if (magic_load(session->magic, MAGIC_DB) != 0) {
309 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
311 magic_close(session->magic);
312 session->magic = NULL;
321 AFB_error httpdStart(AFB_session * session)
324 if (!my_default_init(session)) {
325 printf("Error: initialisation of httpd failed");
329 /* Initialise Client Session Hash Table */
330 ctxStoreInit(CTX_NBCLIENTS);
332 #if defined(USE_MAGIC_MIME_TYPE)
333 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
334 init_lib_magic (session);
338 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
339 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
342 session->httpd = MHD_start_daemon(
343 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
344 (uint16_t) session->config->httpdPort, /* port */
345 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
346 access_handler, session, /* Http Request Call back + extra attribute */
347 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
348 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
349 MHD_OPTION_END); /* options-end */
351 if (session->httpd == NULL) {
352 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
359 AFB_error httpdLoop(AFB_session * session)
362 const union MHD_DaemonInfo *info;
365 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
367 printf("Error: httpLoop no pollfd");
370 pfd.fd = info->listen_fd;
374 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
377 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
378 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
379 MHD_run(session->httpd);
383 /* should never return from here */
387 int httpdStatus(AFB_session * session)
389 return MHD_run(session->httpd);
392 void httpdStop(AFB_session * session)
394 MHD_stop_daemon(session->httpd);