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.
27 #include <microhttpd.h>
29 #include "local-def.h"
30 #include "afb-method.h"
33 #include "afb-websock.h"
35 #include "afb-req-itf.h"
37 #include "utils-upoll.h"
39 #define JSON_CONTENT "application/json"
40 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
43 struct afb_hsrv_handler {
44 struct afb_hsrv_handler *next;
47 int (*handler) (struct afb_hreq *, void *);
54 const char *directory;
61 struct afb_hsrv_handler *handlers;
62 struct MHD_Daemon *httpd;
69 static struct afb_hsrv_handler *new_handler(
70 struct afb_hsrv_handler *head,
72 int (*handler) (struct afb_hreq *, void *),
76 struct afb_hsrv_handler *link, *iter, *previous;
79 /* get the length of the prefix without its leading / */
80 length = strlen(prefix);
81 while (length && prefix[length - 1] == '/')
84 /* allocates the new link */
85 link = malloc(sizeof *link);
90 link->prefix = prefix;
91 link->length = length;
92 link->handler = handler;
94 link->priority = priority;
99 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
104 if (previous == NULL)
106 previous->next = link;
110 int afb_hsrv_add_handler(
111 struct afb_hsrv *hsrv,
113 int (*handler) (struct afb_hreq *, void *),
117 struct afb_hsrv_handler *head;
119 head = new_handler(hsrv->handlers, prefix, handler, data, priority);
122 hsrv->handlers = head;
126 int afb_hreq_one_page_api_redirect(
127 struct afb_hreq *hreq,
133 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
136 * Here we have for example:
137 * url = "/pre/dir/page" lenurl = 13
138 * tail = "/dir/page" lentail = 9
140 * We will produce "/pre/#!dir/page"
142 * Let compute plen that include the / at end (for "/pre/")
144 plen = hreq->lenurl - hreq->lentail + 1;
145 url = alloca(hreq->lenurl + 3);
146 memcpy(url, hreq->url, plen);
149 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
150 return afb_hreq_redirect_to(hreq, url);
153 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
157 afb_hreq_context(hreq);
158 if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
162 struct afb_websock *ws = afb_websock_create(hreq);
169 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
171 const char *api, *verb;
172 size_t lenapi, lenverb;
173 struct AFB_clientCtx *context;
175 api = &hreq->tail[strspn(hreq->tail, "/")];
176 lenapi = strcspn(api, "/");
178 verb = &verb[strspn(verb, "/")];
179 lenverb = strcspn(verb, "/");
181 if (!(*api && *verb && lenapi && lenverb))
184 context = afb_hreq_context(hreq);
185 return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
188 static int handle_alias(struct afb_hreq *hreq, void *data)
190 struct afb_diralias *da = data;
192 if (hreq->method != afb_method_get) {
193 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
197 if (!afb_hreq_valid_tail(hreq)) {
198 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
202 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
205 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, const char *alias, int priority)
207 struct afb_diralias *da;
210 dirfd = open(alias, O_PATH|O_DIRECTORY);
215 da = malloc(sizeof *da);
218 da->directory = alias;
219 da->lendir = strlen(da->directory);
221 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority))
229 static void reply_error(struct MHD_Connection *connection, unsigned int status)
233 struct MHD_Response *response;
235 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
237 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
239 buffer = "<html><body>error</body></html>";
240 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
242 if (!MHD_queue_response(connection, status, response))
243 fprintf(stderr, "Failed to reply error code %u", status);
244 MHD_destroy_response(response);
247 static int postproc(void *cls,
248 enum MHD_ValueKind kind,
250 const char *filename,
251 const char *content_type,
252 const char *transfer_encoding,
257 struct afb_hreq *hreq = cls;
258 if (filename != NULL)
259 return afb_hreq_post_add_file(hreq, key, filename, data, size);
261 return afb_hreq_post_add(hreq, key, data, size);
264 static int access_handler(
266 struct MHD_Connection *connection,
268 const char *methodstr,
270 const char *upload_data,
271 size_t *upload_data_size,
275 struct afb_hreq *hreq;
276 enum afb_method method;
277 struct afb_hsrv *hsrv;
278 struct afb_hsrv_handler *iter;
284 /* create the request */
285 hreq = calloc(1, sizeof *hreq);
291 method = get_method(methodstr);
292 method &= afb_method_get | afb_method_post;
293 if (method == afb_method_none)
296 /* init the request */
297 hreq->cacheTimeout = hsrv->cache_to;
298 hreq->connection = connection;
299 hreq->method = method;
300 hreq->version = version;
301 hreq->tail = hreq->url = url;
302 hreq->lentail = hreq->lenurl = strlen(url);
304 /* init the post processing */
305 if (method == afb_method_post) {
306 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
308 /* an empty post, let's process it as a get */
309 hreq->method = afb_method_get;
310 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
311 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
312 if (hreq->postform == NULL)
315 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
316 reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
322 /* process further data */
323 if (*upload_data_size) {
324 if (hreq->postform != NULL) {
325 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
328 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
331 *upload_data_size = 0;
336 if (hreq->postform != NULL) {
337 rc = MHD_destroy_post_processor(hreq->postform);
338 hreq->postform = NULL;
343 /* search an handler for the request */
344 iter = hsrv->handlers;
346 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
347 if (iter->handler(hreq, iter->data))
349 hreq->tail = hreq->url;
350 hreq->lentail = hreq->lenurl;
356 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
360 reply_error(connection, MHD_HTTP_BAD_REQUEST);
364 reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
368 /* Because of POST call multiple time requestApi we need to free POST handle here */
369 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
370 enum MHD_RequestTerminationCode toe)
372 struct afb_hreq *hreq;
376 MHD_suspend_connection (connection);
380 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
386 static void hsrv_handle_event(struct MHD_Daemon *httpd)
391 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
396 rc = asprintf(&dur, "%d", duration);
400 free(hsrv->cache_to);
401 hsrv->cache_to = dur;
405 int _afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
408 struct MHD_Daemon *httpd;
409 const union MHD_DaemonInfo *info;
411 httpd = MHD_start_daemon(
412 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
414 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
415 access_handler, hsrv, /* Http Request Call back + extra attribute */
416 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
417 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
418 MHD_OPTION_END); /* options-end */
421 printf("Error: httpStart invalid httpd port: %d", (int)port);
425 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
427 MHD_stop_daemon(httpd);
428 fprintf(stderr, "Error: httpStart no pollfd");
432 upoll = upoll_open(info->listen_fd, httpd);
434 MHD_stop_daemon(httpd);
435 fprintf(stderr, "Error: connection to upoll of httpd failed");
438 upoll_on_readable(upoll, (void*)hsrv_handle_event);
445 void _afb_hsrv_stop(struct afb_hsrv *hsrv)
448 upoll_close(hsrv->upoll);
450 if (hsrv->httpd != NULL)
451 MHD_stop_daemon(hsrv->httpd);
455 struct afb_hsrv *afb_hsrv_create()
457 struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
459 result->refcount = 1;
463 void afb_hsrv_put(struct afb_hsrv *hsrv)
465 assert(hsrv->refcount != 0);
466 if (!--hsrv->refcount) {
467 _afb_hsrv_stop(hsrv);
472 static int my_default_init(struct afb_hsrv *hsrv, AFB_session * session)
476 if (!afb_hsrv_add_handler(hsrv, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
479 if (!afb_hsrv_add_handler(hsrv, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
482 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
483 if (!afb_hsrv_add_alias (hsrv, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
486 if (!afb_hsrv_add_alias(hsrv, "", session->config->rootdir, -10))
489 if (!afb_hsrv_add_handler(hsrv, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
495 int afb_hsrv_start(AFB_session * session)
498 struct afb_hsrv *hsrv;
500 hsrv = afb_hsrv_create();
502 fprintf(stderr, "memory allocation failure\n");
506 if (!afb_hsrv_set_cache_timeout(hsrv, session->config->cacheTimeout)
507 || !my_default_init(hsrv, session)) {
508 printf("Error: initialisation of httpd failed");
514 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
515 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
518 rc = _afb_hsrv_start(hsrv, (uint16_t) session->config->httpdPort, 15);
522 session->hsrv = hsrv;
526 void afb_hsrv_stop(AFB_session * session)
528 _afb_hsrv_stop(session->hsrv);