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