work in progress
[src/app-framework-binder.git] / src / afb-hreq.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 <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <sys/stat.h>
27
28 #include <microhttpd.h>
29
30 #include "local-def.h"
31 #include "afb-method.h"
32 #include "afb-req-itf.h"
33 #include "afb-hreq.h"
34
35 static char empty_string[] = "";
36
37 struct hreq_data {
38         struct hreq_data *next;
39         char *key;
40         int file;
41         size_t length;
42         char *value;
43 };
44
45 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
46 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
47 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
48 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
49
50 static const struct afb_req_itf afb_hreq_itf = {
51         .get = (void*)req_get,
52         .iterate = (void*)req_iterate,
53         .fail = (void*)req_fail,
54         .success = (void*)req_success
55 };
56         void (*fail)(void *data, const char *status, const char *info);
57         void (*success)(void *data, json_object *obj, const char *info);
58
59 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
60 {
61         struct hreq_data *data = hreq->data;
62         if (key == NULL)
63                 key = empty_string;
64         while (data != NULL) {
65                 if (!strcasecmp(data->key, key))
66                         return data;
67                 data = data->next;
68         }
69         if (create) {
70                 data = calloc(1, sizeof *data);
71                 if (data != NULL) {
72                         data->key = strdup(key);
73                         if (data->key == NULL) {
74                                 free(data);
75                                 data = NULL;
76                         } else {
77                                 data->next = hreq->data;
78                                 hreq->data = data;
79                         }
80                 }
81         }
82         return data;
83 }
84
85 /* a valid subpath is a relative path not looking deeper than root using .. */
86 static int validsubpath(const char *subpath)
87 {
88         int l = 0, i = 0;
89
90         while (subpath[i]) {
91                 switch (subpath[i++]) {
92                 case '.':
93                         if (!subpath[i])
94                                 break;
95                         if (subpath[i] == '/') {
96                                 i++;
97                                 break;
98                         }
99                         if (subpath[i++] == '.') {
100                                 if (!subpath[i]) {
101                                         if (--l < 0)
102                                                 return 0;
103                                         break;
104                                 }
105                                 if (subpath[i++] == '/') {
106                                         if (--l < 0)
107                                                 return 0;
108                                         break;
109                                 }
110                         }
111                 default:
112                         while (subpath[i] && subpath[i] != '/')
113                                 i++;
114                         l++;
115                 case '/':
116                         break;
117                 }
118         }
119         return 1;
120 }
121
122 /*
123  * Removes the 'prefix' of 'length' frome the tail of 'hreq'
124  * if and only if the prefix exists and is terminated by a leading
125  * slash
126  */
127 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
128 {
129         /* check the prefix ? */
130         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
131             || strncasecmp(prefix, hreq->tail, length))
132                 return 0;
133
134         /* removes successives / */
135         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
136                 length++;
137
138         /* update the tail */
139         hreq->lentail -= length;
140         hreq->tail += length;
141         return 1;
142 }
143
144 int afb_hreq_valid_tail(struct afb_hreq *hreq)
145 {
146         return validsubpath(hreq->tail);
147 }
148
149 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
150 {
151         char *buffer;
152         int length;
153         struct MHD_Response *response;
154
155         length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
156         if (length > 0)
157                 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
158         else {
159                 buffer = "<html><body>error</body></html>";
160                 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
161         }
162         if (!MHD_queue_response(hreq->connection, status, response))
163                 fprintf(stderr, "Failed to reply error code %u", status);
164         MHD_destroy_response(response);
165 }
166
167 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
168 {
169         int rc;
170         int fd;
171         unsigned int status;
172         struct stat st;
173         char etag[1 + 2 * sizeof(int)];
174         const char *inm;
175         struct MHD_Response *response;
176
177         /* Opens the file or directory */
178         if (filename[0]) {
179                 fd = openat(dirfd, filename, O_RDONLY);
180                 if (fd < 0) {
181                         if (errno == ENOENT)
182                                 return 0;
183                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
184                         return 1;
185                 }
186         } else {
187                 fd = dup(dirfd);
188                 if (fd < 0) {
189                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
190                         return 1;
191                 }
192         }
193
194         /* Retrieves file's status */
195         if (fstat(fd, &st) != 0) {
196                 close(fd);
197                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
198                 return 1;
199         }
200
201         /* serve directory */
202         if (S_ISDIR(st.st_mode)) {
203                 if (hreq->url[hreq->lenurl - 1] != '/') {
204                         /* the redirect is needed for reliability of relative path */
205                         char *tourl = alloca(hreq->lenurl + 2);
206                         memcpy(tourl, hreq->url, hreq->lenurl);
207                         tourl[hreq->lenurl] = '/';
208                         tourl[hreq->lenurl + 1] = 0;
209                         rc = afb_hreq_redirect_to(hreq, tourl);
210                 } else {
211                         rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
212                 }
213                 close(fd);
214                 return rc;
215         }
216
217         /* Don't serve special files */
218         if (!S_ISREG(st.st_mode)) {
219                 close(fd);
220                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
221                 return 1;
222         }
223
224         /* Check the method */
225         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
226                 close(fd);
227                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
228                 return 1;
229         }
230
231         /* computes the etag */
232         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
233
234         /* checks the etag */
235         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
236         if (inm && 0 == strcmp(inm, etag)) {
237                 /* etag ok, return NOT MODIFIED */
238                 close(fd);
239                 if (verbose)
240                         fprintf(stderr, "Not Modified: [%s]\n", filename);
241                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
242                 status = MHD_HTTP_NOT_MODIFIED;
243         } else {
244                 /* check the size */
245                 if (st.st_size != (off_t) (size_t) st.st_size) {
246                         close(fd);
247                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
248                         return 1;
249                 }
250
251                 /* create the response */
252                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
253                 status = MHD_HTTP_OK;
254
255 #if defined(USE_MAGIC_MIME_TYPE)
256                 /* set the type */
257                 if (hreq->session->magic) {
258                         const char *mimetype = magic_descriptor(hreq->session->magic, fd);
259                         if (mimetype != NULL)
260                                 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
261                 }
262 #endif
263         }
264
265         /* fills the value and send */
266         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
267         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
268         MHD_queue_response(hreq->connection, status, response);
269         MHD_destroy_response(response);
270         return 1;
271 }
272
273 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
274 {
275         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
276         if (rc == 0)
277                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
278         return 1;
279 }
280
281 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
282 {
283         struct MHD_Response *response;
284
285         response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
286         MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
287         MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
288         MHD_destroy_response(response);
289         if (verbose)
290                 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
291         return 1;
292 }
293
294 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
295 {
296         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
297 }
298
299 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
300 {
301         struct hreq_data *data = get_data(hreq, name, 0);
302         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
303 }
304
305 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
306 {
307         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
308 }
309
310 void afb_hreq_post_end(struct afb_hreq *hreq)
311 {
312         struct hreq_data *data = hreq->data;
313         while(data) {
314                 if (data->file > 0) {
315                         close(data->file);
316                         data->file = -1;
317                 }
318                 data = data->next;
319         }
320 }
321
322 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
323 {
324         void *p;
325         struct hreq_data *hdat = get_data(hreq, key, 1);
326         if (hdat->file) {
327                 return 0;
328         }
329         p = realloc(hdat->value, hdat->length + size + 1);
330         if (p == NULL) {
331                 return 0;
332         }
333         hdat->value = p;
334         memcpy(&hdat->value[hdat->length], data, size);
335         hdat->length += size;
336         hdat->value[hdat->length] = 0;
337         return 1;
338 }
339
340 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
341 {
342         struct hreq_data *hdat = get_data(hreq, key, 1);
343
344         /* continuation with reopening */
345         if (hdat->file < 0) {
346                 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
347                 if (hdat->file == 0) {
348                         hdat->file = dup(0);
349                         close(0);
350                 }
351                 if (hdat->file <= 0)
352                         return 0;
353         }
354         if (hdat->file > 0) {
355                 write(hdat->file, data, size);
356                 return 1;
357         }
358
359         /* creation */
360         /* TODO */
361         return 0;
362         
363 }
364
365 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
366 {
367         struct hreq_data *hdat = get_data(hreq, key, 0);
368         return hdat != NULL && hdat->file != 0;
369 }
370
371
372 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
373 {
374         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
375 }
376
377 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
378 {
379         struct hreq_data *hdat = get_data(hreq, name, 0);
380         if (hdat)
381                 return (struct afb_arg){
382                         .name = hdat->key,
383                         .value = hdat->value,
384                         .size = hdat->length,
385                         .is_file = (hdat->file != 0)
386                 };
387                 
388         return (struct afb_arg){
389                 .name = name,
390                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
391                 .size = 0,
392                 .is_file = 0
393         };
394 }
395
396 struct iterdata
397 {
398         struct afb_hreq *hreq;
399         int (*iterator)(void *closure, struct afb_arg arg);
400         void *closure;
401 };
402
403 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
404 {
405         if (get_data(id->hreq, key, 0))
406                 return 1;
407         return id->iterator(id->closure, (struct afb_arg){
408                 .name = key,
409                 .value = value,
410                 .size = 0,
411                 .is_file = 0
412         });
413 }
414
415 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
416 {
417         struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
418         struct hreq_data *hdat = hreq->data;
419         while (hdat) {
420                 if (!iterator(closure, (struct afb_arg){
421                         .name = hdat->key,
422                         .value = hdat->value,
423                         .size = hdat->length,
424                         .is_file = (hdat->file != 0)}))
425                         return;
426                 hdat = hdat->next;
427         }
428         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
429 }
430
431 void afb_hreq_drop_data(struct afb_hreq *hreq)
432 {
433         struct hreq_data *data = hreq->data;
434         while (data) {
435                 hreq->data = data->next;
436                 free(data->key);
437                 free(data->value);
438                 free(data);
439                 data = hreq->data;
440         }
441 }
442 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
443 {
444         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
445         return len ? : -1;
446 }
447
448 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
449 {
450         json_object *root, *request;
451         struct MHD_Response *response;
452
453         root = json_object_new_object();
454         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
455         request = json_object_new_object();
456         json_object_object_add(root, "request", request);
457         json_object_object_add(request, "status", json_object_new_string(status));
458         if (info)
459                 json_object_object_add(request, "info", json_object_new_string(info));
460         if (resp)
461                 json_object_object_add(root, "response", resp);
462
463         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 65500, (void*)send_json_cb, root, (void*)json_object_put);
464         MHD_queue_response(hreq->connection, retcode, response);
465         MHD_destroy_response(response);
466 }
467
468 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
469 {
470         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
471 }
472
473 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
474 {
475         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
476 }
477