adds accepted lang to global hreq
[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->lang = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
146                 hreq->tail = hreq->url = url;
147                 hreq->lentail = hreq->lenurl = strlen(url);
148                 *recordreq = hreq;
149
150                 /* init the post processing */
151                 if (method == afb_method_post) {
152                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
153                         if (type == NULL) {
154                                 /* an empty post, let's process it as a get */
155                                 hreq->method = afb_method_get;
156                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
157                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
158                                 if (hreq->postform == NULL)
159                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
160                                 return MHD_YES;
161                         } else if (strcasestr(type, JSON_CONTENT) != NULL) {
162                                 return MHD_YES;
163                         } else {
164                                 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
165                                 return MHD_YES;
166                         }
167                 }
168         }
169
170         /* process further data */
171         if (*upload_data_size) {
172                 if (hreq->postform != NULL) {
173                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
174                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
175                                 return MHD_YES;
176                         }
177                 } else {
178                         if (!afb_hreq_post_add(hreq, "", upload_data, *upload_data_size)) {
179                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
180                                 return MHD_YES;
181                         }
182                 }
183                 *upload_data_size = 0;
184                 return MHD_YES;
185         }
186
187         /* flush the data */
188         if (hreq->postform != NULL) {
189                 rc = MHD_destroy_post_processor(hreq->postform);
190                 hreq->postform = NULL;
191                 if (rc == MHD_NO) {
192                         afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
193                         return MHD_YES;
194                 }
195         }
196
197         if (hreq->scanned != 0) {
198                 if (hreq->replied == 0 && hreq->suspended == 0) {
199                         MHD_suspend_connection (connection);
200                         hreq->suspended = 1;
201                 }
202                 return MHD_YES;
203         }
204
205         /* search an handler for the request */
206         hreq->scanned = 1;
207         iter = hsrv->handlers;
208         while (iter) {
209                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
210                         if (iter->handler(hreq, iter->data)) {
211                                 if (hreq->replied == 0 && hreq->suspended == 0) {
212                                         MHD_suspend_connection (connection);
213                                         hreq->suspended = 1;
214                                 }
215                                 return MHD_YES;
216                         }
217                         hreq->tail = hreq->url;
218                         hreq->lentail = hreq->lenurl;
219                 }
220                 iter = iter->next;
221         }
222
223         /* no handler */
224         afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
225         return MHD_YES;
226 }
227
228 /* Because of POST call multiple time requestApi we need to free POST handle here */
229 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
230                         enum MHD_RequestTerminationCode toe)
231 {
232         struct afb_hreq *hreq;
233
234         hreq = *recordreq;
235         if (hreq->upgrade)
236                 MHD_suspend_connection (connection);
237         afb_hreq_unref(hreq);
238 }
239
240 void run_micro_httpd(struct afb_hsrv *hsrv)
241 {
242         if (hsrv->in_run != 0)
243                 hsrv->in_run = 2;
244         else {
245                 sd_event_source_set_io_events(hsrv->evsrc, 0);
246                 do {
247                         hsrv->in_run = 1;
248                         MHD_run(hsrv->httpd);
249                 } while(hsrv->in_run == 2);
250                 hsrv->in_run = 0;
251                 sd_event_source_set_io_events(hsrv->evsrc, EPOLLIN);
252         }
253 }
254
255 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *hsrv)
256 {
257         run_micro_httpd(hsrv);
258         return 0;
259 }
260
261 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
262 {
263         return MHD_YES;
264 }
265
266 static struct hsrv_handler *new_handler(
267                 struct hsrv_handler *head,
268                 const char *prefix,
269                 int (*handler) (struct afb_hreq *, void *),
270                 void *data,
271                 int priority)
272 {
273         struct hsrv_handler *link, *iter, *previous;
274         size_t length;
275
276         /* get the length of the prefix without its leading / */
277         length = strlen(prefix);
278         while (length && prefix[length - 1] == '/')
279                 length--;
280
281         /* allocates the new link */
282         link = malloc(sizeof *link);
283         if (link == NULL)
284                 return NULL;
285
286         /* initialize it */
287         link->prefix = prefix;
288         link->length = length;
289         link->handler = handler;
290         link->data = data;
291         link->priority = priority;
292
293         /* adds it */
294         previous = NULL;
295         iter = head;
296         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
297                 previous = iter;
298                 iter = iter->next;
299         }
300         link->next = iter;
301         if (previous == NULL)
302                 return link;
303         previous->next = link;
304         return head;
305 }
306
307 static int handle_alias(struct afb_hreq *hreq, void *data)
308 {
309         int rc;
310         struct hsrv_alias *da = data;
311
312         if (hreq->method != afb_method_get) {
313                 if (da->relax)
314                         return 0;
315                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
316                 return 1;
317         }
318
319         if (!afb_hreq_valid_tail(hreq)) {
320                 if (da->relax)
321                         return 0;
322                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
323                 return 1;
324         }
325
326         rc = afb_hreq_reply_file_if_exist(hreq, da->dirfd, &hreq->tail[1]);
327         if (rc == 0) {
328                 if (da->relax)
329                         return 0;
330                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
331         }
332         return 1;
333 }
334
335 int afb_hsrv_add_handler(
336                 struct afb_hsrv *hsrv,
337                 const char *prefix,
338                 int (*handler) (struct afb_hreq *, void *),
339                 void *data,
340                 int priority)
341 {
342         struct hsrv_handler *head;
343
344         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
345         if (head == NULL)
346                 return 0;
347         hsrv->handlers = head;
348         return 1;
349 }
350
351 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, const char *alias, int priority, int relax)
352 {
353         struct hsrv_alias *da;
354         int dirfd;
355
356         dirfd = open(alias, O_PATH|O_DIRECTORY);
357         if (dirfd < 0) {
358                 /* TODO message */
359                 return 0;
360         }
361         da = malloc(sizeof *da);
362         if (da != NULL) {
363                 da->alias = prefix;
364                 da->directory = alias;
365                 da->lendir = strlen(da->directory);
366                 da->dirfd = dirfd;
367                 da->relax = relax;
368                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority))
369                         return 1;
370                 free(da);
371         }
372         close(dirfd);
373         return 0;
374 }
375
376 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
377 {
378         int rc;
379         char *dur;
380
381         rc = asprintf(&dur, "%d", duration);
382         if (rc < 0)
383                 return 0;
384
385         free(hsrv->cache_to);
386         hsrv->cache_to = dur;
387         return 1;
388 }
389
390 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
391 {
392         sd_event_source *evsrc;
393         int rc;
394         struct MHD_Daemon *httpd;
395         const union MHD_DaemonInfo *info;
396
397         httpd = MHD_start_daemon(
398                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
399                 port,                           /* port */
400                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
401                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
402                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
403                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
404                 MHD_OPTION_END);        /* options-end */
405
406         if (httpd == NULL) {
407                 ERROR("httpStart invalid httpd port: %d", (int)port);
408                 return 0;
409         }
410
411         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
412         if (info == NULL) {
413                 MHD_stop_daemon(httpd);
414                 ERROR("httpStart no pollfd");
415                 return 0;
416         }
417
418         rc = sd_event_add_io(afb_common_get_event_loop(), &evsrc, info->listen_fd, EPOLLIN, io_event_callback, hsrv);
419         if (rc < 0) {
420                 MHD_stop_daemon(httpd);
421                 errno = -rc;
422                 ERROR("connection to events for httpd failed");
423                 return 0;
424         }
425
426         hsrv->httpd = httpd;
427         hsrv->evsrc = evsrc;
428         return 1;
429 }
430
431 void afb_hsrv_stop(struct afb_hsrv *hsrv)
432 {
433         if (hsrv->evsrc != NULL) {
434                 sd_event_source_unref(hsrv->evsrc);
435                 hsrv->evsrc = NULL;
436         }
437         if (hsrv->httpd != NULL)
438                 MHD_stop_daemon(hsrv->httpd);
439         hsrv->httpd = NULL;
440 }
441
442 struct afb_hsrv *afb_hsrv_create()
443 {
444         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
445         if (result != NULL)
446                 result->refcount = 1;
447         return result;
448 }
449
450 void afb_hsrv_put(struct afb_hsrv *hsrv)
451 {
452         assert(hsrv->refcount != 0);
453         if (!--hsrv->refcount) {
454                 afb_hsrv_stop(hsrv);
455                 free(hsrv);
456         }
457 }
458