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_req_handler {
30 struct afb_req_handler *next;
33 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *);
39 int afb_request_one_page_api_redirect(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
44 if (request->lentail >= 2 && request->tail[1] == '#')
47 * Here we have for example:
48 * url = "/pre/dir/page" lenurl = 13
49 * tail = "/dir/page" lentail = 9
51 * We will produce "/pre/#!dir/page"
53 * Let compute plen that include the / at end (for "/pre/")
55 plen = request->lenurl - request->lentail + 1;
56 url = alloca(request->lenurl + 3);
57 memcpy(url, request->url, plen);
60 memcpy(&url[plen], &request->tail[1], request->lentail);
61 return afb_hreq_redirect_to(request, url);
64 struct afb_req_handler *afb_req_handler_new(struct afb_req_handler *head, const char *prefix,
65 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
66 void *data, int priority)
68 struct afb_req_handler *link, *iter, *previous;
71 /* get the length of the prefix without its leading / */
72 length = strlen(prefix);
73 while (length && prefix[length - 1] == '/')
76 /* allocates the new link */
77 link = malloc(sizeof *link);
82 link->prefix = prefix;
83 link->length = length;
84 link->handler = handler;
86 link->priority = priority;
91 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
98 previous->next = link;
102 int afb_req_add_handler(AFB_session * session, const char *prefix,
103 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *), void *data, int priority)
105 struct afb_req_handler *head;
107 head = afb_req_handler_new(session->handlers, prefix, handler, data, priority);
110 session->handlers = head;
114 static int relay_to_doRestApi(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
116 return doRestApi(request->connection, request->session, &request->tail[1], get_method_name(request->method),
117 post->upload_data, post->upload_data_size, (void **)request->recorder);
120 struct afb_diralias {
122 const char *directory;
127 static int handle_alias(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
129 struct afb_diralias *da = data;
131 if (request->method != afb_method_get) {
132 afb_hreq_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
136 if (!afb_hreq_valid_tail(request)) {
137 afb_hreq_reply_error(request, MHD_HTTP_FORBIDDEN);
141 return afb_hreq_reply_file(request, da->dirfd, &request->tail[request->lentail + 1]);
144 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
146 struct afb_diralias *da;
149 dirfd = open(alias, O_PATH|O_DIRECTORY);
154 da = malloc(sizeof *da);
157 da->directory = alias;
158 da->lendir = strlen(da->directory);
160 if (afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority))
168 static int my_default_init(AFB_session * session)
172 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
175 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
176 if (!afb_req_add_alias
177 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
180 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
183 if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
189 static int access_handler(
191 struct MHD_Connection *connection,
193 const char *methodstr,
195 const char *upload_data,
196 size_t * upload_data_size,
199 struct afb_hreq_post post;
200 struct afb_hreq request;
201 enum afb_method method;
202 AFB_session *session;
203 struct afb_req_handler *iter;
206 post.upload_data = upload_data;
207 post.upload_data_size = upload_data_size;
210 struct afb_hreq *previous;
212 previous = *recorder;
214 assert((void **)previous->recorder == recorder);
215 assert(previous->session == session);
216 assert(previous->connection == connection);
217 assert(previous->method == get_method(methodstr));
218 assert(previous->url == url);
222 assert(previous->post_handler != NULL);
223 previous->post_handler(previous, &post);
229 method = get_method(methodstr);
230 if (method == afb_method_none) {
231 afb_hreq_reply_error(&request, MHD_HTTP_BAD_REQUEST);
235 /* init the request */
236 request.session = cls;
237 request.connection = connection;
238 request.method = method;
239 request.tail = request.url = url;
240 request.lentail = request.lenurl = strlen(url);
241 request.recorder = (struct afb_hreq **)recorder;
242 request.post_handler = NULL;
243 request.post_completed = NULL;
244 request.post_data = NULL;
246 /* search an handler for the request */
247 iter = session->handlers;
249 if (afb_hreq_unprefix(&request, iter->prefix, iter->length)) {
250 if (iter->handler(&request, &post, iter->data))
252 request.tail = request.url;
253 request.lentail = request.lenurl;
259 afb_hreq_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
263 /* Because of POST call multiple time requestApi we need to free POST handle here */
264 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
265 enum MHD_RequestTerminationCode toe)
267 AFB_PostHandle *posthandle = *con_cls;
269 /* if post handle was used let's free everything */
270 if (posthandle != NULL)
271 endPostRequest(posthandle);
274 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
279 #if defined(USE_MAGIC_MIME_TYPE)
281 #if !defined(MAGIC_DB)
282 #define MAGIC_DB "/usr/share/misc/magic.mgc"
285 static int init_lib_magic (AFB_session *session)
287 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
289 printf("Loading mimetype default magic database\n");
291 session->magic = magic_open(MAGIC_MIME_TYPE);
292 if (session->magic == NULL) {
293 fprintf(stderr,"ERROR: unable to initialize magic library\n");
297 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
298 if (magic_load(session->magic, MAGIC_DB) != 0) {
299 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
301 magic_close(session->magic);
302 session->magic = NULL;
311 AFB_error httpdStart(AFB_session * session)
314 if (!my_default_init(session)) {
315 printf("Error: initialisation of httpd failed");
319 /* Initialise Client Session Hash Table */
320 ctxStoreInit(CTX_NBCLIENTS);
322 #if defined(USE_MAGIC_MIME_TYPE)
323 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
324 init_lib_magic (session);
328 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
329 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
332 session->httpd = MHD_start_daemon(
333 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
334 (uint16_t) session->config->httpdPort, /* port */
335 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
336 access_handler, session, /* Http Request Call back + extra attribute */
337 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
338 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
339 MHD_OPTION_END); /* options-end */
341 if (session->httpd == NULL) {
342 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
349 AFB_error httpdLoop(AFB_session * session)
352 const union MHD_DaemonInfo *info;
355 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
357 printf("Error: httpLoop no pollfd");
360 pfd.fd = info->listen_fd;
364 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
367 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
368 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
369 MHD_run(session->httpd);
373 /* should never return from here */
377 int httpdStatus(AFB_session * session)
379 return MHD_run(session->httpd);
382 void httpdStop(AFB_session * session)
384 MHD_stop_daemon(session->httpd);