splitting rest-api in two parts
[src/app-framework-binder.git] / src / http-svc.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 #include <microhttpd.h>
20 #include <assert.h>
21 #include <poll.h>
22 #include <sys/stat.h>
23
24 #include "../include/local-def.h"
25 #include "afb-method.h"
26 #include "afb-hreq.h"
27 #include "afb-websock.h"
28
29
30 struct afb_hsrv_handler {
31         struct afb_hsrv_handler *next;
32         const char *prefix;
33         size_t length;
34         int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *);
35         void *data;
36         int priority;
37 };
38
39 struct afb_diralias {
40         const char *alias;
41         const char *directory;
42         size_t lendir;
43         int dirfd;
44 };
45
46 int afb_hreq_one_page_api_redirect(
47                 struct afb_hreq *hreq,
48                 struct afb_hreq_post *post,
49                 void *data)
50 {
51         size_t plen;
52         char *url;
53
54         if (hreq->lentail >= 2 && hreq->tail[1] == '#')
55                 return 0;
56         /*
57          * Here we have for example:
58          *    url  = "/pre/dir/page"   lenurl = 13
59          *    tail =     "/dir/page"   lentail = 9
60          *
61          * We will produce "/pre/#!dir/page"
62          *
63          * Let compute plen that include the / at end (for "/pre/")
64          */
65         plen = hreq->lenurl - hreq->lentail + 1;
66         url = alloca(hreq->lenurl + 3);
67         memcpy(url, hreq->url, plen);
68         url[plen++] = '#';
69         url[plen++] = '!';
70         memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
71         return afb_hreq_redirect_to(hreq, url);
72 }
73
74 struct afb_hsrv_handler *afb_hsrv_handler_new(
75                 struct afb_hsrv_handler *head,
76                 const char *prefix,
77                 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
78                 void *data,
79                 int priority)
80 {
81         struct afb_hsrv_handler *link, *iter, *previous;
82         size_t length;
83
84         /* get the length of the prefix without its leading / */
85         length = strlen(prefix);
86         while (length && prefix[length - 1] == '/')
87                 length--;
88
89         /* allocates the new link */
90         link = malloc(sizeof *link);
91         if (link == NULL)
92                 return NULL;
93
94         /* initialize it */
95         link->prefix = prefix;
96         link->length = length;
97         link->handler = handler;
98         link->data = data;
99         link->priority = priority;
100
101         /* adds it */
102         previous = NULL;
103         iter = head;
104         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
105                 previous = iter;
106                 iter = iter->next;
107         }
108         link->next = iter;
109         if (previous == NULL)
110                 return link;
111         previous->next = link;
112         return head;
113 }
114
115 int afb_req_add_handler(
116                 AFB_session * session,
117                 const char *prefix,
118                 int (*handler) (struct afb_hreq *, struct afb_hreq_post *, void *),
119                 void *data,
120                 int priority)
121 {
122         struct afb_hsrv_handler *head;
123
124         head = afb_hsrv_handler_new(session->handlers, prefix, handler, data, priority);
125         if (head == NULL)
126                 return 0;
127         session->handlers = head;
128         return 1;
129 }
130
131 static int relay_to_doRestApi(struct afb_hreq *hreq, struct afb_hreq_post *post, void *data)
132 {
133         int later;
134         if (afb_websock_check(hreq, &later)) {
135                 if (!later) {
136                         struct afb_websock *ws = afb_websock_create(hreq->connection);
137                 }
138                 return 1;
139         }
140
141         return doRestApi(hreq->connection, hreq->session, &hreq->tail[1], get_method_name(hreq->method),
142                          post->upload_data, post->upload_data_size, (void **)hreq->recorder);
143 }
144
145 static int handle_alias(struct afb_hreq *hreq, struct afb_hreq_post *post, void *data)
146 {
147         struct afb_diralias *da = data;
148
149         if (hreq->method != afb_method_get) {
150                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
151                 return 1;
152         }
153
154         if (!afb_hreq_valid_tail(hreq)) {
155                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
156                 return 1;
157         }
158
159         return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
160 }
161
162 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
163 {
164         struct afb_diralias *da;
165         int dirfd;
166
167         dirfd = open(alias, O_PATH|O_DIRECTORY);
168         if (dirfd < 0) {
169                 /* TODO message */
170                 return 0;
171         }
172         da = malloc(sizeof *da);
173         if (da != NULL) {
174                 da->alias = prefix;
175                 da->directory = alias;
176                 da->lendir = strlen(da->directory);
177                 da->dirfd = dirfd;
178                 if (afb_req_add_handler(session, prefix, handle_alias, da, priority))
179                         return 1;
180                 free(da);
181         }
182         close(dirfd);
183         return 0;
184 }
185
186 static int my_default_init(AFB_session * session)
187 {
188         int idx;
189
190         if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
191                 return 0;
192
193         for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
194                 if (!afb_req_add_alias
195                     (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
196                         return 0;
197
198         if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
199                 return 0;
200
201         if (!afb_req_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
202                 return 0;
203
204         return 1;
205 }
206
207 static int access_handler(
208                 void *cls,
209                 struct MHD_Connection *connection,
210                 const char *url,
211                 const char *methodstr,
212                 const char *version,
213                 const char *upload_data,
214                 size_t * upload_data_size,
215                 void **recorder)
216 {
217         struct afb_hreq_post post;
218         struct afb_hreq hreq;
219         enum afb_method method;
220         AFB_session *session;
221         struct afb_hsrv_handler *iter;
222
223         session = cls;
224         post.upload_data = upload_data;
225         post.upload_data_size = upload_data_size;
226
227 #if 0
228         struct afb_hreq *previous;
229
230         previous = *recorder;
231         if (previous) {
232                 assert((void **)previous->recorder == recorder);
233                 assert(previous->session == session);
234                 assert(previous->connection == connection);
235                 assert(previous->method == get_method(methodstr));
236                 assert(previous->url == url);
237
238                 /* TODO */
239 /*
240                 assert(previous->post_handler != NULL);
241                 previous->post_handler(previous, &post);
242                 return MHD_NO;
243 */
244         }
245 #endif
246
247         method = get_method(methodstr);
248         if (method == afb_method_none) {
249                 afb_hreq_reply_error(&hreq, MHD_HTTP_BAD_REQUEST);
250                 return MHD_YES;
251         }
252
253         /* init the request */
254         hreq.session = cls;
255         hreq.connection = connection;
256         hreq.method = method;
257         hreq.version = version;
258         hreq.tail = hreq.url = url;
259         hreq.lentail = hreq.lenurl = strlen(url);
260         hreq.recorder = (struct afb_hreq **)recorder;
261         hreq.post_handler = NULL;
262         hreq.post_completed = NULL;
263         hreq.post_data = NULL;
264
265         /* search an handler for the request */
266         iter = session->handlers;
267         while (iter) {
268                 if (afb_hreq_unprefix(&hreq, iter->prefix, iter->length)) {
269                         if (iter->handler(&hreq, &post, iter->data))
270                                 return MHD_YES;
271                         hreq.tail = hreq.url;
272                         hreq.lentail = hreq.lenurl;
273                 }
274                 iter = iter->next;
275         }
276
277         /* no handler */
278         afb_hreq_reply_error(&hreq, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
279         return MHD_YES;
280 }
281
282 /* Because of POST call multiple time requestApi we need to free POST handle here */
283 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
284                         enum MHD_RequestTerminationCode toe)
285 {
286         AFB_PostHandle *posthandle = *con_cls;
287
288         /* if post handle was used let's free everything */
289         if (posthandle != NULL)
290                 endPostRequest(posthandle);
291 }
292
293 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
294 {
295         return MHD_YES;
296 }
297
298 #if defined(USE_MAGIC_MIME_TYPE)
299
300 #if !defined(MAGIC_DB)
301 #define MAGIC_DB "/usr/share/misc/magic.mgc"
302 #endif
303
304 static int init_lib_magic (AFB_session *session)
305 {
306         /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
307         if (verbose)
308                 printf("Loading mimetype default magic database\n");
309
310         session->magic = magic_open(MAGIC_MIME_TYPE);
311         if (session->magic == NULL) {
312                 fprintf(stderr,"ERROR: unable to initialize magic library\n");
313                 return 0;
314         }
315
316         /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
317         if (magic_load(session->magic, MAGIC_DB) != 0) {
318                 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
319 /*
320                 magic_close(session->magic);
321                 session->magic = NULL;
322                 return 0;
323 */
324         }
325
326         return 1;
327 }
328 #endif
329
330 AFB_error httpdStart(AFB_session * session)
331 {
332
333         if (!my_default_init(session)) {
334                 printf("Error: initialisation of httpd failed");
335                 return AFB_FATAL;
336         }
337
338 #if defined(USE_MAGIC_MIME_TYPE)
339         /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
340         init_lib_magic (session);
341 #endif
342
343         if (verbose) {
344                 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
345                 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
346         }
347
348         session->httpd = MHD_start_daemon(
349                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
350                 (uint16_t) session->config->httpdPort,  /* port */
351                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
352                 access_handler, session,        /* Http Request Call back + extra attribute */
353                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
354                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15,        /* 15 seconds */
355                 MHD_OPTION_END);        /* options-end */
356
357         if (session->httpd == NULL) {
358                 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
359                 return AFB_FATAL;
360         }
361         return AFB_SUCCESS;
362 }
363
364 /* infinite loop */
365 AFB_error httpdLoop(AFB_session * session)
366 {
367         int count = 0;
368         const union MHD_DaemonInfo *info;
369         struct pollfd pfd;
370
371         info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
372         if (info == NULL) {
373                 printf("Error: httpLoop no pollfd");
374                 goto error;
375         }
376         pfd.fd = info->listen_fd;
377         pfd.events = POLLIN;
378
379         if (verbose)
380                 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
381         while (TRUE) {
382                 if (verbose)
383                         fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
384                 poll(&pfd, 1, 15000);   /* 15 seconds (as above timeout when starting) */
385                 MHD_run(session->httpd);
386         }
387
388  error:
389         /* should never return from here */
390         return AFB_FATAL;
391 }
392
393 int httpdStatus(AFB_session * session)
394 {
395         return MHD_run(session->httpd);
396 }
397
398 void httpdStop(AFB_session * session)
399 {
400         MHD_stop_daemon(session->httpd);
401 }