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;
45 int afb_request_one_page_api_redirect(
46 struct afb_hreq *request,
47 struct afb_hreq_post *post,
53 if (request->lentail >= 2 && request->tail[1] == '#')
56 * Here we have for example:
57 * url = "/pre/dir/page" lenurl = 13
58 * tail = "/dir/page" lentail = 9
60 * We will produce "/pre/#!dir/page"
62 * Let compute plen that include the / at end (for "/pre/")
64 plen = request->lenurl - request->lentail + 1;
65 url = alloca(request->lenurl + 3);
66 memcpy(url, request->url, plen);
69 memcpy(&url[plen], &request->tail[1], request->lentail);
70 return afb_hreq_redirect_to(request, url);
73 struct afb_hsrv_handler *afb_hsrv_handler_new(
74 struct afb_hsrv_handler *head,
76 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
80 struct afb_hsrv_handler *link, *iter, *previous;
83 /* get the length of the prefix without its leading / */
84 length = strlen(prefix);
85 while (length && prefix[length - 1] == '/')
88 /* allocates the new link */
89 link = malloc(sizeof *link);
94 link->prefix = prefix;
95 link->length = length;
96 link->handler = handler;
98 link->priority = priority;
103 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
108 if (previous == NULL)
110 previous->next = link;
114 int afb_req_add_handler(
115 AFB_session * session,
117 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
121 struct afb_hsrv_handler *head;
123 head = afb_hsrv_handler_new(session->handlers, prefix, handler, data, priority);
126 session->handlers = head;
130 static int relay_to_doRestApi(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
132 return doRestApi(request->connection, request->session, &request->tail[1], get_method_name(request->method),
133 post->upload_data, post->upload_data_size, (void **)request->recorder);
136 static int handle_alias(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
138 struct afb_diralias *da = data;
140 if (request->method != afb_method_get) {
141 afb_hreq_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
145 if (!afb_hreq_valid_tail(request)) {
146 afb_hreq_reply_error(request, MHD_HTTP_FORBIDDEN);
150 return afb_hreq_reply_file(request, da->dirfd, &request->tail[1]);
153 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
155 struct afb_diralias *da;
158 dirfd = open(alias, O_PATH|O_DIRECTORY);
163 da = malloc(sizeof *da);
166 da->directory = alias;
167 da->lendir = strlen(da->directory);
169 if (afb_req_add_handler(session, prefix, handle_alias, da, priority))
177 static int my_default_init(AFB_session * session)
181 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
184 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
185 if (!afb_req_add_alias
186 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
189 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
192 if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
198 static int access_handler(
200 struct MHD_Connection *connection,
202 const char *methodstr,
204 const char *upload_data,
205 size_t * upload_data_size,
208 struct afb_hreq_post post;
209 struct afb_hreq request;
210 enum afb_method method;
211 AFB_session *session;
212 struct afb_hsrv_handler *iter;
215 post.upload_data = upload_data;
216 post.upload_data_size = upload_data_size;
219 struct afb_hreq *previous;
221 previous = *recorder;
223 assert((void **)previous->recorder == recorder);
224 assert(previous->session == session);
225 assert(previous->connection == connection);
226 assert(previous->method == get_method(methodstr));
227 assert(previous->url == url);
231 assert(previous->post_handler != NULL);
232 previous->post_handler(previous, &post);
238 method = get_method(methodstr);
239 if (method == afb_method_none) {
240 afb_hreq_reply_error(&request, MHD_HTTP_BAD_REQUEST);
244 /* init the request */
245 request.session = cls;
246 request.connection = connection;
247 request.method = method;
248 request.tail = request.url = url;
249 request.lentail = request.lenurl = strlen(url);
250 request.recorder = (struct afb_hreq **)recorder;
251 request.post_handler = NULL;
252 request.post_completed = NULL;
253 request.post_data = NULL;
255 /* search an handler for the request */
256 iter = session->handlers;
258 if (afb_hreq_unprefix(&request, iter->prefix, iter->length)) {
259 if (iter->handler(&request, &post, iter->data))
261 request.tail = request.url;
262 request.lentail = request.lenurl;
268 afb_hreq_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
272 /* Because of POST call multiple time requestApi we need to free POST handle here */
273 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
274 enum MHD_RequestTerminationCode toe)
276 AFB_PostHandle *posthandle = *con_cls;
278 /* if post handle was used let's free everything */
279 if (posthandle != NULL)
280 endPostRequest(posthandle);
283 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
288 #if defined(USE_MAGIC_MIME_TYPE)
290 #if !defined(MAGIC_DB)
291 #define MAGIC_DB "/usr/share/misc/magic.mgc"
294 static int init_lib_magic (AFB_session *session)
296 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
298 printf("Loading mimetype default magic database\n");
300 session->magic = magic_open(MAGIC_MIME_TYPE);
301 if (session->magic == NULL) {
302 fprintf(stderr,"ERROR: unable to initialize magic library\n");
306 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
307 if (magic_load(session->magic, MAGIC_DB) != 0) {
308 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
310 magic_close(session->magic);
311 session->magic = NULL;
320 AFB_error httpdStart(AFB_session * session)
323 if (!my_default_init(session)) {
324 printf("Error: initialisation of httpd failed");
328 #if defined(USE_MAGIC_MIME_TYPE)
329 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
330 init_lib_magic (session);
334 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
335 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
338 session->httpd = MHD_start_daemon(
339 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
340 (uint16_t) session->config->httpdPort, /* port */
341 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
342 access_handler, session, /* Http Request Call back + extra attribute */
343 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
344 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
345 MHD_OPTION_END); /* options-end */
347 if (session->httpd == NULL) {
348 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
355 AFB_error httpdLoop(AFB_session * session)
358 const union MHD_DaemonInfo *info;
361 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
363 printf("Error: httpLoop no pollfd");
366 pfd.fd = info->listen_fd;
370 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
373 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
374 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
375 MHD_run(session->httpd);
379 /* should never return from here */
383 int httpdStatus(AFB_session * session)
385 return MHD_run(session->httpd);
388 void httpdStop(AFB_session * session)
390 MHD_stop_daemon(session->httpd);