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"
28 struct afb_hreq_post {
29 const char *upload_data;
30 size_t *upload_data_size;
35 struct MHD_Connection *connection;
36 enum afb_method method;
41 struct afb_hreq **recorder;
42 int (*post_handler) (struct afb_hreq *, struct afb_hreq_post *);
43 int (*post_completed) (struct afb_hreq *, struct afb_hreq_post *);
47 struct afb_req_handler {
48 struct afb_req_handler *next;
51 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *);
56 static char empty_string[1] = "";
58 /* a valid subpath is a relative path not looking deeper than root using .. */
59 static int validsubpath(const char *subpath)
64 switch (subpath[i++]) {
68 if (subpath[i] == '/') {
72 if (subpath[i++] == '.') {
78 if (subpath[i++] == '/') {
85 while (subpath[i] && subpath[i] != '/')
96 * Removes the 'prefix' of 'length' frome the tail of 'request'
97 * if and only if the prefix exists and is terminated by a leading
100 int afb_req_unprefix(struct afb_hreq *request, const char *prefix, size_t length)
102 /* check the prefix ? */
103 if (length > request->lentail || (request->tail[length] && request->tail[length] != '/')
104 || memcmp(prefix, request->tail, length))
107 /* removes successives / */
108 while (length < request->lentail && request->tail[length + 1] == '/')
111 /* update the tail */
112 request->lentail -= length;
113 request->tail += length;
117 int afb_req_valid_tail(struct afb_hreq *request)
119 return validsubpath(request->tail);
122 void afb_req_reply_error(struct afb_hreq *request, unsigned int status)
126 struct MHD_Response *response;
128 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
130 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
132 buffer = "<html><body>error</body></html>";
133 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
135 if (!MHD_queue_response(request->connection, status, response))
136 fprintf(stderr, "Failed to reply error code %u", status);
137 MHD_destroy_response(response);
140 int afb_request_redirect_to(struct afb_hreq *request, const char *url)
142 struct MHD_Response *response;
144 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
145 MHD_add_response_header(response, "Location", url);
146 MHD_queue_response(request->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
147 MHD_destroy_response(response);
149 fprintf(stderr, "redirect from [%s] to [%s]\n", request->url, url);
153 int afb_request_one_page_api_redirect(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
158 if (request->lentail >= 2 && request->tail[1] == '#')
161 * Here we have for example:
162 * url = "/pre/dir/page" lenurl = 13
163 * tail = "/dir/page" lentail = 9
165 * We will produce "/pre/#!dir/page"
167 * Let compute plen that include the / at end (for "/pre/")
169 plen = request->lenurl - request->lentail + 1;
170 url = alloca(request->lenurl + 3);
171 memcpy(url, request->url, plen);
174 memcpy(&url[plen], &request->tail[1], request->lentail);
175 return afb_request_redirect_to(request, url);
178 struct afb_req_handler *afb_req_handler_new(struct afb_req_handler *head, const char *prefix,
179 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
180 void *data, int priority)
182 struct afb_req_handler *link, *iter, *previous;
185 /* get the length of the prefix without its leading / */
186 length = strlen(prefix);
187 while (length && prefix[length - 1] == '/')
190 /* allocates the new link */
191 link = malloc(sizeof *link);
196 link->prefix = prefix;
197 link->length = length;
198 link->handler = handler;
200 link->priority = priority;
205 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
210 if (previous == NULL)
212 previous->next = link;
216 int afb_req_add_handler(AFB_session * session, const char *prefix,
217 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *), void *data, int priority)
219 struct afb_req_handler *head;
221 head = afb_req_handler_new(session->handlers, prefix, handler, data, priority);
224 session->handlers = head;
228 static int relay_to_doRestApi(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
230 return doRestApi(request->connection, request->session, &request->tail[1], get_method_name(request->method),
231 post->upload_data, post->upload_data_size, (void **)request->recorder);
234 static int afb_req_reply_file_if_exist(struct afb_hreq *request, int dirfd, const char *filename)
240 char etag[1 + 2 * sizeof(int)];
242 struct MHD_Response *response;
244 /* Opens the file or directory */
245 fd = openat(dirfd, filename, O_RDONLY);
249 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
253 /* Retrieves file's status */
254 if (fstat(fd, &st) != 0) {
256 afb_req_reply_error(request, MHD_HTTP_INTERNAL_SERVER_ERROR);
260 /* Don't serve directory */
261 if (S_ISDIR(st.st_mode)) {
262 rc = afb_req_reply_file_if_exist(request, fd, "index.html");
267 /* Don't serve special files */
268 if (!S_ISREG(st.st_mode)) {
270 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
274 /* Check the method */
275 if ((request->method & (afb_method_get | afb_method_head)) == 0) {
277 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
281 /* computes the etag */
282 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
284 /* checks the etag */
285 inm = MHD_lookup_connection_value(request->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
286 if (inm && 0 == strcmp(inm, etag)) {
287 /* etag ok, return NOT MODIFIED */
290 fprintf(stderr, "Not Modified: [%s]\n", filename);
291 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
292 status = MHD_HTTP_NOT_MODIFIED;
295 if (st.st_size != (off_t) (size_t) st.st_size) {
297 afb_req_reply_error(request, MHD_HTTP_INTERNAL_SERVER_ERROR);
301 /* create the response */
302 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
303 status = MHD_HTTP_OK;
305 #if defined(USE_MAGIC_MIME_TYPE)
307 if (request->session->magic) {
308 const char *mimetype = magic_descriptor(request->session->magic, fd);
309 if (mimetype != NULL)
310 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
315 /* fills the value and send */
316 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, request->session->cacheTimeout);
317 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
318 MHD_queue_response(request->connection, status, response);
319 MHD_destroy_response(response);
323 static int afb_req_reply_file(struct afb_hreq *request, int dirfd, const char *filename)
325 int rc = afb_req_reply_file_if_exist(request, dirfd, filename);
327 afb_req_reply_error(request, MHD_HTTP_NOT_FOUND);
331 struct afb_diralias {
333 const char *directory;
338 static int handle_alias(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
341 struct afb_diralias *da = data;
344 if (request->method != afb_method_get) {
345 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
349 if (!validsubpath(request->tail)) {
350 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
354 return afb_req_reply_file(request, da->dirfd, &request->tail[request->lentail + 1]);
357 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
359 struct afb_diralias *da;
362 dirfd = open(alias, O_PATH|O_DIRECTORY);
367 da = malloc(sizeof *da);
370 da->directory = alias;
371 da->lendir = strlen(da->directory);
373 if (afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority))
381 static int my_default_init(AFB_session * session)
385 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
388 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
389 if (!afb_req_add_alias
390 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
393 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
396 if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
402 static int access_handler(
404 struct MHD_Connection *connection,
406 const char *methodstr,
408 const char *upload_data,
409 size_t * upload_data_size,
412 struct afb_hreq_post post;
413 struct afb_hreq request;
414 enum afb_method method;
415 AFB_session *session;
416 struct afb_req_handler *iter;
419 post.upload_data = upload_data;
420 post.upload_data_size = upload_data_size;
423 struct afb_hreq *previous;
425 previous = *recorder;
427 assert((void **)previous->recorder == recorder);
428 assert(previous->session == session);
429 assert(previous->connection == connection);
430 assert(previous->method == get_method(methodstr));
431 assert(previous->url == url);
435 assert(previous->post_handler != NULL);
436 previous->post_handler(previous, &post);
442 method = get_method(methodstr);
443 if (method == afb_method_none) {
444 afb_req_reply_error(&request, MHD_HTTP_BAD_REQUEST);
448 /* init the request */
449 request.session = cls;
450 request.connection = connection;
451 request.method = method;
452 request.tail = request.url = url;
453 request.lentail = request.lenurl = strlen(url);
454 request.recorder = (struct afb_hreq **)recorder;
455 request.post_handler = NULL;
456 request.post_completed = NULL;
457 request.post_data = NULL;
459 /* search an handler for the request */
460 iter = session->handlers;
462 if (afb_req_unprefix(&request, iter->prefix, iter->length)) {
463 if (iter->handler(&request, &post, iter->data))
465 request.tail = request.url;
466 request.lentail = request.lenurl;
472 afb_req_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
476 /* Because of POST call multiple time requestApi we need to free POST handle here */
477 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
478 enum MHD_RequestTerminationCode toe)
480 AFB_PostHandle *posthandle = *con_cls;
482 /* if post handle was used let's free everything */
483 if (posthandle != NULL)
484 endPostRequest(posthandle);
487 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
492 #if defined(USE_MAGIC_MIME_TYPE)
494 #if !defined(MAGIC_DB)
495 #define MAGIC_DB "/usr/share/misc/magic.mgc"
498 static int init_lib_magic (AFB_session *session)
500 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
502 printf("Loading mimetype default magic database\n");
504 session->magic = magic_open(MAGIC_MIME_TYPE);
505 if (session->magic == NULL) {
506 fprintf(stderr,"ERROR: unable to initialize magic library\n");
510 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
511 if (magic_load(session->magic, MAGIC_DB) != 0) {
512 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
514 magic_close(session->magic);
515 session->magic = NULL;
524 AFB_error httpdStart(AFB_session * session)
527 if (!my_default_init(session)) {
528 printf("Error: initialisation of httpd failed");
532 /* Initialise Client Session Hash Table */
533 ctxStoreInit(CTX_NBCLIENTS);
535 #if defined(USE_MAGIC_MIME_TYPE)
536 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
537 init_lib_magic (session);
541 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
542 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
545 session->httpd = MHD_start_daemon(
546 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
547 (uint16_t) session->config->httpdPort, /* port */
548 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
549 access_handler, session, /* Http Request Call back + extra attribute */
550 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
551 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
552 MHD_OPTION_END); /* options-end */
554 if (session->httpd == NULL) {
555 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
562 AFB_error httpdLoop(AFB_session * session)
565 const union MHD_DaemonInfo *info;
568 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
570 printf("Error: httpLoop no pollfd");
573 pfd.fd = info->listen_fd;
577 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
580 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
581 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
582 MHD_run(session->httpd);
586 /* should never return from here */
590 int httpdStatus(AFB_session * session)
592 return MHD_run(session->httpd);
595 void httpdStop(AFB_session * session)
597 MHD_stop_daemon(session->httpd);