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