Switch to libsystemd events
[src/app-framework-binder.git] / src / afb-hsrv.c
1 /*
2  * Copyright 2016 IoT.bzh
3  * Author: José Bollo <jose.bollo@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <assert.h>
24 #include <poll.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <sys/stat.h>
28
29 #include <microhttpd.h>
30 #include <systemd/sd-event.h>
31
32 #include "afb-method.h"
33 #include "afb-hreq.h"
34 #include "afb-hsrv.h"
35 #include "afb-req-itf.h"
36 #include "verbose.h"
37
38 #include "afb-common.h"
39
40
41
42 #define JSON_CONTENT  "application/json"
43 #define FORM_CONTENT  MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
44
45
46 struct hsrv_handler {
47         struct hsrv_handler *next;
48         const char *prefix;
49         size_t length;
50         int (*handler) (struct afb_hreq *, void *);
51         void *data;
52         int priority;
53 };
54
55 struct hsrv_alias {
56         const char *alias;
57         const char *directory;
58         size_t lendir;
59         int dirfd;
60 };
61
62 struct afb_hsrv {
63         unsigned refcount;
64         struct hsrv_handler *handlers;
65         struct MHD_Daemon *httpd;
66         sd_event_source *evsrc;
67         int in_run;
68         char *cache_to;
69 };
70
71 static int global_reqids = 0;
72
73 static void reply_error(struct MHD_Connection *connection, unsigned int status)
74 {
75         struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
76         MHD_queue_response(connection, status, response);
77         MHD_destroy_response(response);
78 }
79
80 static int postproc(void *cls,
81                     enum MHD_ValueKind kind,
82                     const char *key,
83                     const char *filename,
84                     const char *content_type,
85                     const char *transfer_encoding,
86                     const char *data,
87                     uint64_t off,
88                     size_t size)
89 {
90         struct afb_hreq *hreq = cls;
91         if (filename != NULL)
92                 return afb_hreq_post_add_file(hreq, key, filename, data, size);
93         else
94                 return afb_hreq_post_add(hreq, key, data, size);
95 }
96
97 static int access_handler(
98                 void *cls,
99                 struct MHD_Connection *connection,
100                 const char *url,
101                 const char *methodstr,
102                 const char *version,
103                 const char *upload_data,
104                 size_t *upload_data_size,
105                 void **recordreq)
106 {
107         int rc;
108         struct afb_hreq *hreq;
109         enum afb_method method;
110         struct afb_hsrv *hsrv;
111         struct hsrv_handler *iter;
112         const char *type;
113
114         hsrv = cls;
115         hreq = *recordreq;
116         if (hreq == NULL) {
117                 /* get the method */
118                 method = get_method(methodstr);
119                 method &= afb_method_get | afb_method_post;
120                 if (method == afb_method_none) {
121                         reply_error(connection, MHD_HTTP_BAD_REQUEST);
122                         return MHD_YES;
123                 }
124
125                 /* create the request */
126                 hreq = calloc(1, sizeof *hreq);
127                 if (hreq == NULL) {
128                         reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
129                         return MHD_YES;
130                 }
131
132                 /* init the request */
133                 hreq->hsrv = hsrv;
134                 hreq->cacheTimeout = hsrv->cache_to;
135                 hreq->reqid = ++global_reqids;
136                 hreq->scanned = 0;
137                 hreq->suspended = 0;
138                 hreq->replied = 0;
139                 hreq->connection = connection;
140                 hreq->method = method;
141                 hreq->version = version;
142                 hreq->tail = hreq->url = url;
143                 hreq->lentail = hreq->lenurl = strlen(url);
144                 *recordreq = hreq;
145
146                 /* init the post processing */
147                 if (method == afb_method_post) {
148                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
149                         if (type == NULL) {
150                                 /* an empty post, let's process it as a get */
151                                 hreq->method = afb_method_get;
152                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
153                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
154                                 if (hreq->postform == NULL)
155                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
156                                 return MHD_YES;
157                         } else if (strcasestr(type, JSON_CONTENT) == NULL) {
158                                 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
159                                 return MHD_YES;
160                         }
161                 }
162         }
163
164         /* process further data */
165         if (*upload_data_size) {
166                 if (hreq->postform != NULL) {
167                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
168                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
169                                 return MHD_YES;
170                         }
171                 } else {
172                         if (!afb_hreq_post_add(hreq, "", upload_data, *upload_data_size)) {
173                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
174                                 return MHD_YES;
175                         }
176                 }
177                 *upload_data_size = 0;
178                 return MHD_YES;
179         }
180
181         /* flush the data */
182         if (hreq->postform != NULL) {
183                 rc = MHD_destroy_post_processor(hreq->postform);
184                 hreq->postform = NULL;
185                 if (rc == MHD_NO) {
186                         afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
187                         return MHD_YES;
188                 }
189         }
190
191         if (hreq->scanned != 0) {
192                 if (hreq->replied == 0 && hreq->suspended == 0) {
193                         MHD_suspend_connection (connection);
194                         hreq->suspended = 1;
195                 }
196                 return MHD_YES;
197         }
198
199         /* search an handler for the request */
200         hreq->scanned = 1;
201         iter = hsrv->handlers;
202         while (iter) {
203                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
204                         if (iter->handler(hreq, iter->data)) {
205                                 if (hreq->replied == 0 && hreq->suspended == 0) {
206                                         MHD_suspend_connection (connection);
207                                         hreq->suspended = 1;
208                                 }
209                                 return MHD_YES;
210                         }
211                         hreq->tail = hreq->url;
212                         hreq->lentail = hreq->lenurl;
213                 }
214                 iter = iter->next;
215         }
216
217         /* no handler */
218         afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
219         return MHD_YES;
220 }
221
222 /* Because of POST call multiple time requestApi we need to free POST handle here */
223 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
224                         enum MHD_RequestTerminationCode toe)
225 {
226         struct afb_hreq *hreq;
227
228         hreq = *recordreq;
229         if (hreq->upgrade)
230                 MHD_suspend_connection (connection);
231         afb_hreq_free(hreq);
232 }
233
234 void run_micro_httpd(struct afb_hsrv *hsrv)
235 {
236         if (hsrv->in_run != 0)
237                 hsrv->in_run = 2;
238         else {
239                 sd_event_source_set_io_events(hsrv->evsrc, 0);
240                 do {
241                         hsrv->in_run = 1;
242                         MHD_run(hsrv->httpd);
243                 } while(hsrv->in_run == 2);
244                 hsrv->in_run = 0;
245                 sd_event_source_set_io_events(hsrv->evsrc, EPOLLIN);
246         }
247 }
248
249 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *hsrv)
250 {
251         run_micro_httpd(hsrv);
252         return 0;
253 }
254
255 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
256 {
257         return MHD_YES;
258 }
259
260 static struct hsrv_handler *new_handler(
261                 struct hsrv_handler *head,
262                 const char *prefix,
263                 int (*handler) (struct afb_hreq *, void *),
264                 void *data,
265                 int priority)
266 {
267         struct hsrv_handler *link, *iter, *previous;
268         size_t length;
269
270         /* get the length of the prefix without its leading / */
271         length = strlen(prefix);
272         while (length && prefix[length - 1] == '/')
273                 length--;
274
275         /* allocates the new link */
276         link = malloc(sizeof *link);
277         if (link == NULL)
278                 return NULL;
279
280         /* initialize it */
281         link->prefix = prefix;
282         link->length = length;
283         link->handler = handler;
284         link->data = data;
285         link->priority = priority;
286
287         /* adds it */
288         previous = NULL;
289         iter = head;
290         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
291                 previous = iter;
292                 iter = iter->next;
293         }
294         link->next = iter;
295         if (previous == NULL)
296                 return link;
297         previous->next = link;
298         return head;
299 }
300
301 static int handle_alias(struct afb_hreq *hreq, void *data)
302 {
303         struct hsrv_alias *da = data;
304
305         if (hreq->method != afb_method_get) {
306                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
307                 return 1;
308         }
309
310         if (!afb_hreq_valid_tail(hreq)) {
311                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
312                 return 1;
313         }
314
315         return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
316 }
317
318 int afb_hsrv_add_handler(
319                 struct afb_hsrv *hsrv,
320                 const char *prefix,
321                 int (*handler) (struct afb_hreq *, void *),
322                 void *data,
323                 int priority)
324 {
325         struct hsrv_handler *head;
326
327         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
328         if (head == NULL)
329                 return 0;
330         hsrv->handlers = head;
331         return 1;
332 }
333
334 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, const char *alias, int priority)
335 {
336         struct hsrv_alias *da;
337         int dirfd;
338
339         dirfd = open(alias, O_PATH|O_DIRECTORY);
340         if (dirfd < 0) {
341                 /* TODO message */
342                 return 0;
343         }
344         da = malloc(sizeof *da);
345         if (da != NULL) {
346                 da->alias = prefix;
347                 da->directory = alias;
348                 da->lendir = strlen(da->directory);
349                 da->dirfd = dirfd;
350                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority))
351                         return 1;
352                 free(da);
353         }
354         close(dirfd);
355         return 0;
356 }
357
358 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
359 {
360         int rc;
361         char *dur;
362
363         rc = asprintf(&dur, "%d", duration);
364         if (rc < 0)
365                 return 0;
366
367         free(hsrv->cache_to);
368         hsrv->cache_to = dur;
369         return 1;
370 }
371
372 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
373 {
374         sd_event_source *evsrc;
375         int rc;
376         struct MHD_Daemon *httpd;
377         const union MHD_DaemonInfo *info;
378
379         httpd = MHD_start_daemon(
380                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
381                 port,                           /* port */
382                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
383                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
384                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
385                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
386                 MHD_OPTION_END);        /* options-end */
387
388         if (httpd == NULL) {
389                 fprintf(stderr, "Error: httpStart invalid httpd port: %d", (int)port);
390                 return 0;
391         }
392
393         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
394         if (info == NULL) {
395                 MHD_stop_daemon(httpd);
396                 fprintf(stderr, "Error: httpStart no pollfd");
397                 return 0;
398         }
399
400         rc = sd_event_add_io(afb_common_get_event_loop(), &evsrc, info->listen_fd, EPOLLIN, io_event_callback, hsrv);
401         if (rc < 0) {
402                 MHD_stop_daemon(httpd);
403                 errno = -rc;
404                 fprintf(stderr, "Error: connection to events for httpd failed");
405                 return 0;
406         }
407
408         hsrv->httpd = httpd;
409         hsrv->evsrc = evsrc;
410         return 1;
411 }
412
413 void afb_hsrv_stop(struct afb_hsrv *hsrv)
414 {
415         if (hsrv->evsrc != NULL) {
416                 sd_event_source_unref(hsrv->evsrc);
417                 hsrv->evsrc = NULL;
418         }
419         if (hsrv->httpd != NULL)
420                 MHD_stop_daemon(hsrv->httpd);
421         hsrv->httpd = NULL;
422 }
423
424 struct afb_hsrv *afb_hsrv_create()
425 {
426         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
427         if (result != NULL)
428                 result->refcount = 1;
429         return result;
430 }
431
432 void afb_hsrv_put(struct afb_hsrv *hsrv)
433 {
434         assert(hsrv->refcount != 0);
435         if (!--hsrv->refcount) {
436                 afb_hsrv_stop(hsrv);
437                 free(hsrv);
438         }
439 }
440