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