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