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