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;
60 struct MHD_Daemon *httpd;
61 struct afb_hsrv_handler *handlers;
65 static struct upoll *upoll = NULL;
67 static struct afb_hsrv_handler *new_handler(
68 struct afb_hsrv_handler *head,
70 int (*handler) (struct afb_hreq *, void *),
74 struct afb_hsrv_handler *link, *iter, *previous;
77 /* get the length of the prefix without its leading / */
78 length = strlen(prefix);
79 while (length && prefix[length - 1] == '/')
82 /* allocates the new link */
83 link = malloc(sizeof *link);
88 link->prefix = prefix;
89 link->length = length;
90 link->handler = handler;
92 link->priority = priority;
97 while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
102 if (previous == NULL)
104 previous->next = link;
108 int afb_hsrv_add_handler(
109 AFB_session * session,
111 int (*handler) (struct afb_hreq *, void *),
115 struct afb_hsrv_handler *head;
117 head = new_handler(session->handlers, prefix, handler, data, priority);
120 session->handlers = head;
124 int afb_hreq_one_page_api_redirect(
125 struct afb_hreq *hreq,
131 if (hreq->lentail >= 2 && hreq->tail[1] == '#')
134 * Here we have for example:
135 * url = "/pre/dir/page" lenurl = 13
136 * tail = "/dir/page" lentail = 9
138 * We will produce "/pre/#!dir/page"
140 * Let compute plen that include the / at end (for "/pre/")
142 plen = hreq->lenurl - hreq->lentail + 1;
143 url = alloca(hreq->lenurl + 3);
144 memcpy(url, hreq->url, plen);
147 memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
148 return afb_hreq_redirect_to(hreq, url);
151 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
155 afb_hreq_context(hreq);
156 if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
160 struct afb_websock *ws = afb_websock_create(hreq);
167 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
169 const char *api, *verb;
170 size_t lenapi, lenverb;
171 struct AFB_clientCtx *context;
173 api = &hreq->tail[strspn(hreq->tail, "/")];
174 lenapi = strcspn(api, "/");
176 verb = &verb[strspn(verb, "/")];
177 lenverb = strcspn(verb, "/");
179 if (!(*api && *verb && lenapi && lenverb))
182 context = afb_hreq_context(hreq);
183 return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
186 static int handle_alias(struct afb_hreq *hreq, void *data)
188 struct afb_diralias *da = data;
190 if (hreq->method != afb_method_get) {
191 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
195 if (!afb_hreq_valid_tail(hreq)) {
196 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
200 return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
203 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
205 struct afb_diralias *da;
208 dirfd = open(alias, O_PATH|O_DIRECTORY);
213 da = malloc(sizeof *da);
216 da->directory = alias;
217 da->lendir = strlen(da->directory);
219 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
227 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
231 struct MHD_Response *response;
233 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
235 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
237 buffer = "<html><body>error</body></html>";
238 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
240 if (!MHD_queue_response(connection, status, response))
241 fprintf(stderr, "Failed to reply error code %u", status);
242 MHD_destroy_response(response);
245 static int postproc(void *cls,
246 enum MHD_ValueKind kind,
248 const char *filename,
249 const char *content_type,
250 const char *transfer_encoding,
255 struct afb_hreq *hreq = cls;
256 if (filename != NULL)
257 return afb_hreq_post_add_file(hreq, key, filename, data, size);
259 return afb_hreq_post_add(hreq, key, data, size);
262 static int access_handler(
264 struct MHD_Connection *connection,
266 const char *methodstr,
268 const char *upload_data,
269 size_t *upload_data_size,
273 struct afb_hreq *hreq;
274 enum afb_method method;
275 AFB_session *session;
276 struct afb_hsrv_handler *iter;
282 /* create the request */
283 hreq = calloc(1, sizeof *hreq);
289 method = get_method(methodstr);
290 method &= afb_method_get | afb_method_post;
291 if (method == afb_method_none)
294 /* init the request */
296 hreq->connection = connection;
297 hreq->method = method;
298 hreq->version = version;
299 hreq->tail = hreq->url = url;
300 hreq->lentail = hreq->lenurl = strlen(url);
302 /* init the post processing */
303 if (method == afb_method_post) {
304 type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
306 /* an empty post, let's process it as a get */
307 hreq->method = afb_method_get;
308 } else if (strcasestr(type, FORM_CONTENT) != NULL) {
309 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
310 if (hreq->postform == NULL)
313 } else if (strcasestr(type, JSON_CONTENT) == NULL) {
314 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
320 /* process further data */
321 if (*upload_data_size) {
322 if (hreq->postform != NULL) {
323 if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
326 if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
329 *upload_data_size = 0;
334 if (hreq->postform != NULL) {
335 rc = MHD_destroy_post_processor(hreq->postform);
336 hreq->postform = NULL;
341 /* search an handler for the request */
342 iter = session->handlers;
344 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
345 if (iter->handler(hreq, iter->data))
347 hreq->tail = hreq->url;
348 hreq->lentail = hreq->lenurl;
354 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
358 afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
362 afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
366 /* Because of POST call multiple time requestApi we need to free POST handle here */
367 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
368 enum MHD_RequestTerminationCode toe)
370 struct afb_hreq *hreq;
374 MHD_suspend_connection (connection);
378 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
383 static int my_default_init(AFB_session * session)
387 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
390 if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
393 for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
394 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
397 if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
400 if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
407 static void hsrv_handle_event(struct MHD_Daemon *httpd)
412 int afb_hsrv_start(AFB_session * session)
414 struct MHD_Daemon *httpd;
415 const union MHD_DaemonInfo *info;
417 if (!my_default_init(session)) {
418 printf("Error: initialisation of httpd failed");
423 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
424 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
427 httpd = MHD_start_daemon(
428 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
429 (uint16_t) session->config->httpdPort, /* port */
430 new_client_handler, NULL, /* Tcp Accept call back + extra attribute */
431 access_handler, session, /* Http Request Call back + extra attribute */
432 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
433 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15, /* 15 seconds */
434 MHD_OPTION_END); /* options-end */
437 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
441 info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
443 MHD_stop_daemon(httpd);
444 fprintf(stderr, "Error: httpStart no pollfd");
448 upoll = upoll_open(info->listen_fd, httpd);
450 MHD_stop_daemon(httpd);
451 fprintf(stderr, "Error: connection to upoll of httpd failed");
454 upoll_on_readable(upoll, (void*)hsrv_handle_event);
456 session->httpd = httpd;
460 void afb_hsrv_stop(AFB_session * session)
465 if (session->httpd != NULL)
466 MHD_stop_daemon(session->httpd);
467 session->httpd = NULL;