avoid reentering MHD_run
[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 enum afb_hsrv_state {
58         hsrv_idle = 0,
59         hsrv_run,
60         hsrv_rerun
61 };
62
63 struct afb_hsrv {
64         unsigned refcount;
65         enum afb_hsrv_state state;
66         struct hsrv_handler *handlers;
67         struct MHD_Daemon *httpd;
68         struct upoll *upoll;
69         char *cache_to;
70 };
71
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                 /* create the request */
118                 hreq = calloc(1, sizeof *hreq);
119                 if (hreq == NULL)
120                         goto internal_error;
121                 *recordreq = hreq;
122
123                 /* get the method */
124                 method = get_method(methodstr);
125                 method &= afb_method_get | afb_method_post;
126                 if (method == afb_method_none)
127                         goto bad_request;
128
129                 /* init the request */
130                 hreq->cacheTimeout = hsrv->cache_to;
131                 hreq->connection = connection;
132                 hreq->method = method;
133                 hreq->version = version;
134                 hreq->tail = hreq->url = url;
135                 hreq->lentail = hreq->lenurl = strlen(url);
136
137                 /* init the post processing */
138                 if (method == afb_method_post) {
139                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
140                         if (type == NULL) {
141                                 /* an empty post, let's process it as a get */
142                                 hreq->method = afb_method_get;
143                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
144                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
145                                 if (hreq->postform == NULL)
146                                         goto internal_error;
147                                 return MHD_YES;
148                         } else if (strcasestr(type, JSON_CONTENT) == NULL) {
149                                 reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
150                                 return MHD_YES;
151                         }
152                 }
153         }
154
155         /* process further data */
156         if (*upload_data_size) {
157                 if (hreq->postform != NULL) {
158                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
159                                 goto internal_error;
160                 } else {
161                         if (!afb_hreq_post_add(hreq, "", upload_data, *upload_data_size))
162                                 goto internal_error;
163                 }
164                 *upload_data_size = 0;
165                 return MHD_YES;         
166         }
167
168         /* flush the data */
169         if (hreq->postform != NULL) {
170                 rc = MHD_destroy_post_processor(hreq->postform);
171                 hreq->postform = NULL;
172                 if (rc == MHD_NO)
173                         goto bad_request;
174         }
175
176         /* search an handler for the request */
177         iter = hsrv->handlers;
178         while (iter) {
179                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
180                         if (iter->handler(hreq, iter->data))
181                                 return MHD_YES;
182                         hreq->tail = hreq->url;
183                         hreq->lentail = hreq->lenurl;
184                 }
185                 iter = iter->next;
186         }
187
188         /* no handler */
189         afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
190         return MHD_YES;
191
192 bad_request:
193         reply_error(connection, MHD_HTTP_BAD_REQUEST);
194         return MHD_YES;
195
196 internal_error:
197         reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
198         return MHD_YES;
199 }
200
201 /* Because of POST call multiple time requestApi we need to free POST handle here */
202 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
203                         enum MHD_RequestTerminationCode toe)
204 {
205         struct afb_hreq *hreq;
206
207         hreq = *recordreq;
208         if (hreq->upgrade)
209                 MHD_suspend_connection (connection);
210         afb_hreq_free(hreq);
211 }
212
213 static void handle_epoll_readable(struct afb_hsrv *hsrv)
214 {
215         if (hsrv->state != hsrv_idle)
216                 hsrv->state = hsrv_rerun;
217         else {
218                 do {
219                         hsrv->state = hsrv_run;
220                         MHD_run(hsrv->httpd);
221                 } while (hsrv->state == hsrv_rerun);
222                 hsrv->state = hsrv_idle;
223         }
224 };
225
226 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
227 {
228         return MHD_YES;
229 }
230
231 static struct hsrv_handler *new_handler(
232                 struct hsrv_handler *head,
233                 const char *prefix,
234                 int (*handler) (struct afb_hreq *, void *),
235                 void *data,
236                 int priority)
237 {
238         struct hsrv_handler *link, *iter, *previous;
239         size_t length;
240
241         /* get the length of the prefix without its leading / */
242         length = strlen(prefix);
243         while (length && prefix[length - 1] == '/')
244                 length--;
245
246         /* allocates the new link */
247         link = malloc(sizeof *link);
248         if (link == NULL)
249                 return NULL;
250
251         /* initialize it */
252         link->prefix = prefix;
253         link->length = length;
254         link->handler = handler;
255         link->data = data;
256         link->priority = priority;
257
258         /* adds it */
259         previous = NULL;
260         iter = head;
261         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
262                 previous = iter;
263                 iter = iter->next;
264         }
265         link->next = iter;
266         if (previous == NULL)
267                 return link;
268         previous->next = link;
269         return head;
270 }
271
272 static int handle_alias(struct afb_hreq *hreq, void *data)
273 {
274         struct hsrv_alias *da = data;
275
276         if (hreq->method != afb_method_get) {
277                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
278                 return 1;
279         }
280
281         if (!afb_hreq_valid_tail(hreq)) {
282                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
283                 return 1;
284         }
285
286         return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
287 }
288
289 int afb_hsrv_add_handler(
290                 struct afb_hsrv *hsrv,
291                 const char *prefix,
292                 int (*handler) (struct afb_hreq *, void *),
293                 void *data,
294                 int priority)
295 {
296         struct hsrv_handler *head;
297
298         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
299         if (head == NULL)
300                 return 0;
301         hsrv->handlers = head;
302         return 1;
303 }
304
305 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, const char *alias, int priority)
306 {
307         struct hsrv_alias *da;
308         int dirfd;
309
310         dirfd = open(alias, O_PATH|O_DIRECTORY);
311         if (dirfd < 0) {
312                 /* TODO message */
313                 return 0;
314         }
315         da = malloc(sizeof *da);
316         if (da != NULL) {
317                 da->alias = prefix;
318                 da->directory = alias;
319                 da->lendir = strlen(da->directory);
320                 da->dirfd = dirfd;
321                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority))
322                         return 1;
323                 free(da);
324         }
325         close(dirfd);
326         return 0;
327 }
328
329 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
330 {
331         int rc;
332         char *dur;
333
334         rc = asprintf(&dur, "%d", duration);
335         if (rc < 0)
336                 return 0;
337
338         free(hsrv->cache_to);
339         hsrv->cache_to = dur;
340         return 1;
341 }
342
343 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
344 {
345         struct upoll *upoll;
346         struct MHD_Daemon *httpd;
347         const union MHD_DaemonInfo *info;
348
349         httpd = MHD_start_daemon(
350                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
351                 port,                           /* port */
352                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
353                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
354                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
355                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
356                 MHD_OPTION_END);        /* options-end */
357
358         if (httpd == NULL) {
359                 fprintf(stderr, "Error: httpStart invalid httpd port: %d", (int)port);
360                 return 0;
361         }
362
363         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
364         if (info == NULL) {
365                 MHD_stop_daemon(httpd);
366                 fprintf(stderr, "Error: httpStart no pollfd");
367                 return 0;
368         }
369
370         upoll = upoll_open(info->listen_fd, hsrv);
371         if (upoll == NULL) {
372                 MHD_stop_daemon(httpd);
373                 fprintf(stderr, "Error: connection to upoll of httpd failed");
374                 return 0;
375         }
376         upoll_on_readable(upoll, (void*)handle_epoll_readable);
377
378         hsrv->httpd = httpd;
379         hsrv->upoll = upoll;
380         return 1;
381 }
382
383 void afb_hsrv_stop(struct afb_hsrv *hsrv)
384 {
385         if (hsrv->upoll)
386                 upoll_close(hsrv->upoll);
387         hsrv->upoll = NULL;
388         if (hsrv->httpd != NULL)
389                 MHD_stop_daemon(hsrv->httpd);
390         hsrv->httpd = NULL;
391 }
392
393 struct afb_hsrv *afb_hsrv_create()
394 {
395         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
396         if (result != NULL)
397                 result->refcount = 1;
398         return result;
399 }
400
401 void afb_hsrv_put(struct afb_hsrv *hsrv)
402 {
403         assert(hsrv->refcount != 0);
404         if (!--hsrv->refcount) {
405                 afb_hsrv_stop(hsrv);
406                 free(hsrv);
407         }
408 }
409