simplification
[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 int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
207 {
208         return MHD_YES;
209 }
210
211 static struct hsrv_handler *new_handler(
212                 struct hsrv_handler *head,
213                 const char *prefix,
214                 int (*handler) (struct afb_hreq *, void *),
215                 void *data,
216                 int priority)
217 {
218         struct hsrv_handler *link, *iter, *previous;
219         size_t length;
220
221         /* get the length of the prefix without its leading / */
222         length = strlen(prefix);
223         while (length && prefix[length - 1] == '/')
224                 length--;
225
226         /* allocates the new link */
227         link = malloc(sizeof *link);
228         if (link == NULL)
229                 return NULL;
230
231         /* initialize it */
232         link->prefix = prefix;
233         link->length = length;
234         link->handler = handler;
235         link->data = data;
236         link->priority = priority;
237
238         /* adds it */
239         previous = NULL;
240         iter = head;
241         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
242                 previous = iter;
243                 iter = iter->next;
244         }
245         link->next = iter;
246         if (previous == NULL)
247                 return link;
248         previous->next = link;
249         return head;
250 }
251
252 static int handle_alias(struct afb_hreq *hreq, void *data)
253 {
254         struct hsrv_alias *da = data;
255
256         if (hreq->method != afb_method_get) {
257                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
258                 return 1;
259         }
260
261         if (!afb_hreq_valid_tail(hreq)) {
262                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
263                 return 1;
264         }
265
266         return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
267 }
268
269 int afb_hsrv_add_handler(
270                 struct afb_hsrv *hsrv,
271                 const char *prefix,
272                 int (*handler) (struct afb_hreq *, void *),
273                 void *data,
274                 int priority)
275 {
276         struct hsrv_handler *head;
277
278         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
279         if (head == NULL)
280                 return 0;
281         hsrv->handlers = head;
282         return 1;
283 }
284
285 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, const char *alias, int priority)
286 {
287         struct hsrv_alias *da;
288         int dirfd;
289
290         dirfd = open(alias, O_PATH|O_DIRECTORY);
291         if (dirfd < 0) {
292                 /* TODO message */
293                 return 0;
294         }
295         da = malloc(sizeof *da);
296         if (da != NULL) {
297                 da->alias = prefix;
298                 da->directory = alias;
299                 da->lendir = strlen(da->directory);
300                 da->dirfd = dirfd;
301                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority))
302                         return 1;
303                 free(da);
304         }
305         close(dirfd);
306         return 0;
307 }
308
309 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
310 {
311         int rc;
312         char *dur;
313
314         rc = asprintf(&dur, "%d", duration);
315         if (rc < 0)
316                 return 0;
317
318         free(hsrv->cache_to);
319         hsrv->cache_to = dur;
320         return 1;
321 }
322
323 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
324 {
325         struct upoll *upoll;
326         struct MHD_Daemon *httpd;
327         const union MHD_DaemonInfo *info;
328
329         httpd = MHD_start_daemon(
330                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
331                 port,                           /* port */
332                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
333                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
334                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
335                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
336                 MHD_OPTION_END);        /* options-end */
337
338         if (httpd == NULL) {
339                 printf("Error: httpStart invalid httpd port: %d", (int)port);
340                 return 0;
341         }
342
343         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
344         if (info == NULL) {
345                 MHD_stop_daemon(httpd);
346                 fprintf(stderr, "Error: httpStart no pollfd");
347                 return 0;
348         }
349
350         upoll = upoll_open(info->listen_fd, httpd);
351         if (upoll == NULL) {
352                 MHD_stop_daemon(httpd);
353                 fprintf(stderr, "Error: connection to upoll of httpd failed");
354                 return 0;
355         }
356         upoll_on_readable(upoll, (void*)MHD_run);
357
358         hsrv->httpd = httpd;
359         hsrv->upoll = upoll;
360         return 1;
361 }
362
363 void afb_hsrv_stop(struct afb_hsrv *hsrv)
364 {
365         if (hsrv->upoll)
366                 upoll_close(hsrv->upoll);
367         hsrv->upoll = NULL;
368         if (hsrv->httpd != NULL)
369                 MHD_stop_daemon(hsrv->httpd);
370         hsrv->httpd = NULL;
371 }
372
373 struct afb_hsrv *afb_hsrv_create()
374 {
375         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
376         if (result != NULL)
377                 result->refcount = 1;
378         return result;
379 }
380
381 void afb_hsrv_put(struct afb_hsrv *hsrv)
382 {
383         assert(hsrv->refcount != 0);
384         if (!--hsrv->refcount) {
385                 afb_hsrv_stop(hsrv);
386                 free(hsrv);
387         }
388 }
389