websocket: initial (not integrated)
[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.version = version;
249         request.tail = request.url = url;
250         request.lentail = request.lenurl = strlen(url);
251         request.recorder = (struct afb_hreq **)recorder;
252         request.post_handler = NULL;
253         request.post_completed = NULL;
254         request.post_data = NULL;
255
256         /* search an handler for the request */
257         iter = session->handlers;
258         while (iter) {
259                 if (afb_hreq_unprefix(&request, iter->prefix, iter->length)) {
260                         if (iter->handler(&request, &post, iter->data))
261                                 return MHD_YES;
262                         request.tail = request.url;
263                         request.lentail = request.lenurl;
264                 }
265                 iter = iter->next;
266         }
267
268         /* no handler */
269         afb_hreq_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
270         return MHD_YES;
271 }
272
273 /* Because of POST call multiple time requestApi we need to free POST handle here */
274 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
275                         enum MHD_RequestTerminationCode toe)
276 {
277         AFB_PostHandle *posthandle = *con_cls;
278
279         /* if post handle was used let's free everything */
280         if (posthandle != NULL)
281                 endPostRequest(posthandle);
282 }
283
284 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
285 {
286         return MHD_YES;
287 }
288
289 #if defined(USE_MAGIC_MIME_TYPE)
290
291 #if !defined(MAGIC_DB)
292 #define MAGIC_DB "/usr/share/misc/magic.mgc"
293 #endif
294
295 static int init_lib_magic (AFB_session *session)
296 {
297         /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
298         if (verbose)
299                 printf("Loading mimetype default magic database\n");
300
301         session->magic = magic_open(MAGIC_MIME_TYPE);
302         if (session->magic == NULL) {
303                 fprintf(stderr,"ERROR: unable to initialize magic library\n");
304                 return 0;
305         }
306
307         /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
308         if (magic_load(session->magic, MAGIC_DB) != 0) {
309                 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
310 /*
311                 magic_close(session->magic);
312                 session->magic = NULL;
313                 return 0;
314 */
315         }
316
317         return 1;
318 }
319 #endif
320
321 AFB_error httpdStart(AFB_session * session)
322 {
323
324         if (!my_default_init(session)) {
325                 printf("Error: initialisation of httpd failed");
326                 return AFB_FATAL;
327         }
328
329 #if defined(USE_MAGIC_MIME_TYPE)
330         /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
331         init_lib_magic (session);
332 #endif
333
334         if (verbose) {
335                 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
336                 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
337         }
338
339         session->httpd = MHD_start_daemon(
340                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
341                 (uint16_t) session->config->httpdPort,  /* port */
342                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
343                 access_handler, session,        /* Http Request Call back + extra attribute */
344                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
345                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15,        /* 15 seconds */
346                 MHD_OPTION_END);        /* options-end */
347
348         if (session->httpd == NULL) {
349                 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
350                 return AFB_FATAL;
351         }
352         return AFB_SUCCESS;
353 }
354
355 /* infinite loop */
356 AFB_error httpdLoop(AFB_session * session)
357 {
358         int count = 0;
359         const union MHD_DaemonInfo *info;
360         struct pollfd pfd;
361
362         info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
363         if (info == NULL) {
364                 printf("Error: httpLoop no pollfd");
365                 goto error;
366         }
367         pfd.fd = info->listen_fd;
368         pfd.events = POLLIN;
369
370         if (verbose)
371                 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
372         while (TRUE) {
373                 if (verbose)
374                         fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
375                 poll(&pfd, 1, 15000);   /* 15 seconds (as above timeout when starting) */
376                 MHD_run(session->httpd);
377         }
378
379  error:
380         /* should never return from here */
381         return AFB_FATAL;
382 }
383
384 int httpdStatus(AFB_session * session)
385 {
386         return MHD_run(session->httpd);
387 }
388
389 void httpdStop(AFB_session * session)
390 {
391         MHD_stop_daemon(session->httpd);
392 }