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