2 * Copyright (C) 2016 "IoT.bzh"
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include <microhttpd.h>
23 #include "../include/local-def.h"
32 afb_method_connect = 8,
33 afb_method_delete = 16,
34 afb_method_options = 32,
35 afb_method_patch = 64,
37 afb_method_trace = 256,
42 const char *upload_data;
43 size_t *upload_data_size;
48 struct MHD_Connection *connection;
49 enum afb_method method;
54 struct afb_req **recorder;
55 int (*post_handler) (struct afb_req *, struct afb_req_post *);
56 int (*post_completed) (struct afb_req *, struct afb_req_post *);
60 struct afb_req_handler {
61 struct afb_req_handler *next;
64 int (*handler) (struct afb_req *, struct afb_req_post *, void *);
69 static char empty_string[1] = "";
71 enum afb_method get_method(const char *method)
73 switch (method[0] & ~' ') {
75 return afb_method_connect;
77 return afb_method_delete;
79 return afb_method_get;
81 return afb_method_head;
83 return afb_method_options;
85 switch (method[1] & ~' ') {
87 return afb_method_patch;
89 return afb_method_post;
91 return afb_method_put;
95 return afb_method_trace;
97 return afb_method_none;
100 #if !defined(MHD_HTTP_METHOD_PATCH)
101 #define MHD_HTTP_METHOD_PATCH "PATCH"
103 const char *get_method_name(enum afb_method method)
107 return MHD_HTTP_METHOD_GET;
108 case afb_method_post:
109 return MHD_HTTP_METHOD_POST;
110 case afb_method_head:
111 return MHD_HTTP_METHOD_HEAD;
112 case afb_method_connect:
113 return MHD_HTTP_METHOD_CONNECT;
114 case afb_method_delete:
115 return MHD_HTTP_METHOD_DELETE;
116 case afb_method_options:
117 return MHD_HTTP_METHOD_OPTIONS;
118 case afb_method_patch:
119 return MHD_HTTP_METHOD_PATCH;
121 return MHD_HTTP_METHOD_PUT;
122 case afb_method_trace:
123 return MHD_HTTP_METHOD_TRACE;
129 /* a valid subpath is a relative path not looking deeper than root using .. */
130 static int validsubpath(const char *subpath)
135 switch (subpath[i++]) {
139 if (subpath[i] == '/') {
143 if (subpath[i++] == '.') {
149 if (subpath[i++] == '/') {
156 while (subpath[i] && subpath[i] != '/')
167 * Removes the 'prefix' of 'length' frome the tail of 'request'
168 * if and only if the prefix exists and is terminated by a leading
171 int afb_req_unprefix(struct afb_req *request, const char *prefix, size_t length)
173 /* check the prefix ? */
174 if (length > request->lentail || (request->tail[length] && request->tail[length] != '/')
175 || memcmp(prefix, request->tail, length))
178 /* removes successives / */
179 while (length < request->lentail && request->tail[length + 1] == '/')
182 /* update the tail */
183 request->lentail -= length;
184 request->tail += length;
188 int afb_req_valid_tail(struct afb_req *request)
190 return validsubpath(request->tail);
193 void afb_req_reply_error(struct afb_req *request, unsigned int status)
197 struct MHD_Response *response;
199 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
201 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
203 buffer = "<html><body>error</body></html>";
204 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
206 if (!MHD_queue_response(request->connection, status, response))
207 fprintf(stderr, "Failed to reply error code %u", status);
208 MHD_destroy_response(response);
211 int afb_request_redirect_to(struct afb_req *request, const char *url)
213 struct MHD_Response *response;
215 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
216 MHD_add_response_header(response, "Location", url);
217 MHD_queue_response(request->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
218 MHD_destroy_response(response);
220 fprintf(stderr, "redirect from [%s] to [%s]\n", request->url, url);
224 int afb_request_one_page_api_redirect(struct afb_req *request, struct afb_req_post *post, void *data)
229 if (request->lentail >= 2 && request->tail[1] == '#')
232 * Here we have for example:
233 * url = "/pre/dir/page" lenurl = 13
234 * tail = "/dir/page" lentail = 9
236 * We will produce "/pre/#!dir/page"
238 * Let compute plen that include the / at end (for "/pre/")
240 plen = request->lenurl - request->lentail + 1;
241 url = alloca(request->lenurl + 3);
242 memcpy(url, request->url, plen);
245 memcpy(&url[plen], &request->tail[1], request->lentail);
246 return afb_request_redirect_to(request, url);
249 struct afb_req_handler *afb_req_handler_new(struct afb_req_handler *head, const char *prefix,
250 int (*handler) (struct afb_req *, struct afb_req_post *, void *),
251 void *data, int priority)
253 struct afb_req_handler *link, *iter, *previous;
256 /* get the length of the prefix without its leading / */
257 length = strlen(prefix);
258 while (length && prefix[length - 1] == '/')
261 /* allocates the new link */
262 link = malloc(sizeof *link);
267 link->prefix = prefix;
268 link->length = length;
269 link->handler = handler;
271 link->priority = priority;
276 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
281 if (previous == NULL)
283 previous->next = link;
287 int afb_req_add_handler(AFB_session * session, const char *prefix,
288 int (*handler) (struct afb_req *, struct afb_req_post *, void *), void *data, int priority)
290 struct afb_req_handler *head;
292 head = afb_req_handler_new(session->handlers, prefix, handler, data, priority);
295 session->handlers = head;
299 static int relay_to_doRestApi(struct afb_req *request, struct afb_req_post *post, void *data)
301 return doRestApi(request->connection, request->session, &request->tail[1], get_method_name(request->method),
302 post->upload_data, post->upload_data_size, (void **)request->recorder);
305 static int afb_req_reply_file_if_exist(struct afb_req *request, int dirfd, const char *filename)
311 char etag[1 + 2 * sizeof(int)];
313 struct MHD_Response *response;
315 /* Opens the file or directory */
316 fd = openat(dirfd, filename, O_RDONLY);
320 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
324 /* Retrieves file's status */
325 if (fstat(fd, &st) != 0) {
327 afb_req_reply_error(request, MHD_HTTP_INTERNAL_SERVER_ERROR);
331 /* Don't serve directory */
332 if (S_ISDIR(st.st_mode)) {
333 rc = afb_req_reply_file_if_exist(request, fd, "index.html");
338 /* Don't serve special files */
339 if (!S_ISREG(st.st_mode)) {
341 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
345 /* Check the method */
346 if ((request->method & (afb_method_get | afb_method_head)) == 0) {
348 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
352 /* computes the etag */
353 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
355 /* checks the etag */
356 inm = MHD_lookup_connection_value(request->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
357 if (inm && 0 == strcmp(inm, etag)) {
358 /* etag ok, return NOT MODIFIED */
361 fprintf(stderr, "Not Modified: [%s]\n", filename);
362 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
363 status = MHD_HTTP_NOT_MODIFIED;
366 if (st.st_size != (off_t) (size_t) st.st_size) {
368 afb_req_reply_error(request, MHD_HTTP_INTERNAL_SERVER_ERROR);
372 /* create the response */
373 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
374 status = MHD_HTTP_OK;
376 #if defined(USE_MAGIC_MIME_TYPE)
378 if (request->session->magic) {
379 const char *mimetype = magic_descriptor(request->session->magic, fd);
380 if (mimetype != NULL)
381 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
386 /* fills the value and send */
387 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, request->session->cacheTimeout);
388 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
389 MHD_queue_response(request->connection, status, response);
390 MHD_destroy_response(response);
394 static int afb_req_reply_file(struct afb_req *request, int dirfd, const char *filename)
396 int rc = afb_req_reply_file_if_exist(request, dirfd, filename);
398 afb_req_reply_error(request, MHD_HTTP_NOT_FOUND);
402 static int handle_alias(struct afb_req *request, struct afb_req_post *post, void *data)
405 const char *alias = data;
408 if (request->method != afb_method_get) {
409 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
413 if (!validsubpath(request->tail)) {
414 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
418 lenalias = strlen(alias);
419 path = alloca(lenalias + request->lentail + 1);
420 memcpy(path, alias, lenalias);
421 memcpy(&path[lenalias], request->tail, request->lentail + 1);
422 return afb_req_reply_file(request, AT_FDCWD, path);
425 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
427 return afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority);
430 static int my_default_init(AFB_session * session)
434 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
437 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
438 if (!afb_req_add_alias
439 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
442 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
445 if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
451 static int access_handler(void *cls,
452 struct MHD_Connection *connection,
454 const char *methodstr,
455 const char *version, const char *upload_data, size_t * upload_data_size, void **recorder)
457 struct afb_req_post post;
458 struct afb_req request;
459 enum afb_method method;
460 AFB_session *session;
461 struct afb_req_handler *iter;
464 post.upload_data = upload_data;
465 post.upload_data_size = upload_data_size;
468 struct afb_req *previous;
470 previous = *recorder;
472 assert((void **)previous->recorder == recorder);
473 assert(previous->session == session);
474 assert(previous->connection == connection);
475 assert(previous->method == get_method(methodstr));
476 assert(previous->url == url);
480 assert(previous->post_handler != NULL);
481 previous->post_handler(previous, &post);
487 method = get_method(methodstr);
488 if (method == afb_method_none) {
489 afb_req_reply_error(&request, MHD_HTTP_BAD_REQUEST);
493 /* init the request */
494 request.session = cls;
495 request.connection = connection;
496 request.method = method;
497 request.tail = request.url = url;
498 request.lentail = request.lenurl = strlen(url);
499 request.recorder = (struct afb_req **)recorder;
500 request.post_handler = NULL;
501 request.post_completed = NULL;
502 request.post_data = NULL;
504 /* search an handler for the request */
505 iter = session->handlers;
507 if (afb_req_unprefix(&request, iter->prefix, iter->length)) {
508 if (iter->handler(&request, &post, iter->data))
510 request.tail = request.url;
511 request.lentail = request.lenurl;
517 afb_req_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
521 /* Because of POST call multiple time requestApi we need to free POST handle here */
522 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
523 enum MHD_RequestTerminationCode toe)
525 AFB_PostHandle *posthandle = *con_cls;
527 /* if post handle was used let's free everything */
528 if (posthandle != NULL)
529 endPostRequest(posthandle);
532 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
537 #if defined(USE_MAGIC_MIME_TYPE)
539 #if !defined(MAGIC_DB)
540 #define MAGIC_DB "/usr/share/misc/magic.mgc"
543 static int init_lib_magic (AFB_session *session)
545 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
547 printf("Loading mimetype default magic database\n");
549 session->magic = magic_open(MAGIC_MIME_TYPE);
550 if (session->magic == NULL) {
551 fprintf(stderr,"ERROR: unable to initialize magic library\n");
555 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
556 if (magic_load(session->magic, MAGIC_DB) != 0) {
557 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
559 magic_close(session->magic);
560 session->magic = NULL;
569 AFB_error httpdStart(AFB_session * session)
572 if (!my_default_init(session)) {
573 printf("Error: initialisation of httpd failed");
577 /* Initialise Client Session Hash Table */
578 ctxStoreInit(CTX_NBCLIENTS);
580 #if defined(USE_MAGIC_MIME_TYPE)
581 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
582 init_lib_magic (session);
586 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
587 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
590 session->httpd = MHD_start_daemon(
591 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
592 (uint16_t) session->config->httpdPort, /* port */
593 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
594 access_handler, session, /* Http Request Call back + extra attribute */
595 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
596 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
597 MHD_OPTION_END); /* options-end */
599 if (session->httpd == NULL) {
600 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
607 AFB_error httpdLoop(AFB_session * session)
610 const union MHD_DaemonInfo *info;
613 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
615 printf("Error: httpLoop no pollfd");
618 pfd.fd = info->listen_fd;
622 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
625 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
626 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
627 MHD_run(session->httpd);
631 /* should never return from here */
635 int httpdStatus(AFB_session * session)
637 return MHD_run(session->httpd);
640 void httpdStop(AFB_session * session)
642 MHD_stop_daemon(session->httpd);