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