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 const char *upload_data;
30 size_t *upload_data_size;
35 struct MHD_Connection *connection;
36 enum afb_method method;
41 struct afb_req **recorder;
42 int (*post_handler) (struct afb_req *, struct afb_req_post *);
43 int (*post_completed) (struct afb_req *, struct afb_req_post *);
47 struct afb_req_handler {
48 struct afb_req_handler *next;
51 int (*handler) (struct afb_req *, struct afb_req_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_req *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_req *request)
119 return validsubpath(request->tail);
122 void afb_req_reply_error(struct afb_req *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_req *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_req *request, struct afb_req_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_req *, struct afb_req_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_req *, struct afb_req_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_req *request, struct afb_req_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_req *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_req *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 static int handle_alias(struct afb_req *request, struct afb_req_post *post, void *data)
334 const char *alias = data;
337 if (request->method != afb_method_get) {
338 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
342 if (!validsubpath(request->tail)) {
343 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
347 lenalias = strlen(alias);
348 path = alloca(lenalias + request->lentail + 1);
349 memcpy(path, alias, lenalias);
350 memcpy(&path[lenalias], request->tail, request->lentail + 1);
351 return afb_req_reply_file(request, AT_FDCWD, path);
354 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
356 return afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority);
359 static int my_default_init(AFB_session * session)
363 if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
366 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
367 if (!afb_req_add_alias
368 (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
371 if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
374 if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
380 static int access_handler(void *cls,
381 struct MHD_Connection *connection,
383 const char *methodstr,
384 const char *version, const char *upload_data, size_t * upload_data_size, void **recorder)
386 struct afb_req_post post;
387 struct afb_req request;
388 enum afb_method method;
389 AFB_session *session;
390 struct afb_req_handler *iter;
393 post.upload_data = upload_data;
394 post.upload_data_size = upload_data_size;
397 struct afb_req *previous;
399 previous = *recorder;
401 assert((void **)previous->recorder == recorder);
402 assert(previous->session == session);
403 assert(previous->connection == connection);
404 assert(previous->method == get_method(methodstr));
405 assert(previous->url == url);
409 assert(previous->post_handler != NULL);
410 previous->post_handler(previous, &post);
416 method = get_method(methodstr);
417 if (method == afb_method_none) {
418 afb_req_reply_error(&request, MHD_HTTP_BAD_REQUEST);
422 /* init the request */
423 request.session = cls;
424 request.connection = connection;
425 request.method = method;
426 request.tail = request.url = url;
427 request.lentail = request.lenurl = strlen(url);
428 request.recorder = (struct afb_req **)recorder;
429 request.post_handler = NULL;
430 request.post_completed = NULL;
431 request.post_data = NULL;
433 /* search an handler for the request */
434 iter = session->handlers;
436 if (afb_req_unprefix(&request, iter->prefix, iter->length)) {
437 if (iter->handler(&request, &post, iter->data))
439 request.tail = request.url;
440 request.lentail = request.lenurl;
446 afb_req_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
450 /* Because of POST call multiple time requestApi we need to free POST handle here */
451 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
452 enum MHD_RequestTerminationCode toe)
454 AFB_PostHandle *posthandle = *con_cls;
456 /* if post handle was used let's free everything */
457 if (posthandle != NULL)
458 endPostRequest(posthandle);
461 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
466 #if defined(USE_MAGIC_MIME_TYPE)
468 #if !defined(MAGIC_DB)
469 #define MAGIC_DB "/usr/share/misc/magic.mgc"
472 static int init_lib_magic (AFB_session *session)
474 /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
476 printf("Loading mimetype default magic database\n");
478 session->magic = magic_open(MAGIC_MIME_TYPE);
479 if (session->magic == NULL) {
480 fprintf(stderr,"ERROR: unable to initialize magic library\n");
484 /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
485 if (magic_load(session->magic, MAGIC_DB) != 0) {
486 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
488 magic_close(session->magic);
489 session->magic = NULL;
498 AFB_error httpdStart(AFB_session * session)
501 if (!my_default_init(session)) {
502 printf("Error: initialisation of httpd failed");
506 /* Initialise Client Session Hash Table */
507 ctxStoreInit(CTX_NBCLIENTS);
509 #if defined(USE_MAGIC_MIME_TYPE)
510 /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
511 init_lib_magic (session);
515 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
516 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
519 session->httpd = MHD_start_daemon(
520 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
521 (uint16_t) session->config->httpdPort, /* port */
522 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
523 access_handler, session, /* Http Request Call back + extra attribute */
524 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
525 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
526 MHD_OPTION_END); /* options-end */
528 if (session->httpd == NULL) {
529 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
536 AFB_error httpdLoop(AFB_session * session)
539 const union MHD_DaemonInfo *info;
542 info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
544 printf("Error: httpLoop no pollfd");
547 pfd.fd = info->listen_fd;
551 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
554 fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
555 poll(&pfd, 1, 15000); /* 15 seconds (as above timeout when starting) */
556 MHD_run(session->httpd);
560 /* should never return from here */
564 int httpdStatus(AFB_session * session)
566 return MHD_run(session->httpd);
569 void httpdStop(AFB_session * session)
571 MHD_stop_daemon(session->httpd);