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