2 * Copyright 2016 IoT.bzh
3 * Author: José Bollo <jose.bollo@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
28 #include <microhttpd.h>
30 #include "local-def.h"
31 #include "afb-method.h"
32 #include "afb-req-itf.h"
36 #define SIZE_RESPONSE_BUFFER 8000
38 static char empty_string[] = "";
40 static const char uuid_header[] = "x-afb-uuid";
41 static const char uuid_arg[] = "uuid";
42 static const char uuid_cookie[] = "uuid";
44 static const char token_header[] = "x-afb-token";
45 static const char token_arg[] = "token";
46 static const char token_cookie[] = "token";
50 struct hreq_data *next;
57 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
58 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
59 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
60 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
61 static int req_session_create(struct afb_hreq *hreq);
62 static int req_session_check(struct afb_hreq *hreq, int refresh);
63 static void req_session_close(struct afb_hreq *hreq);
65 static const struct afb_req_itf afb_hreq_itf = {
66 .get = (void*)req_get,
67 .iterate = (void*)req_iterate,
68 .fail = (void*)req_fail,
69 .success = (void*)req_success,
70 .session_create = (void*)req_session_create,
71 .session_check = (void*)req_session_check,
72 .session_close = (void*)req_session_close
75 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
77 struct hreq_data *data = hreq->data;
80 while (data != NULL) {
81 if (!strcasecmp(data->key, key))
86 data = calloc(1, sizeof *data);
88 data->key = strdup(key);
89 if (data->key == NULL) {
93 data->next = hreq->data;
101 /* a valid subpath is a relative path not looking deeper than root using .. */
102 static int validsubpath(const char *subpath)
107 switch (subpath[i++]) {
111 if (subpath[i] == '/') {
115 if (subpath[i++] == '.') {
121 if (subpath[i++] == '/') {
128 while (subpath[i] && subpath[i] != '/')
138 void afb_hreq_free(struct afb_hreq *hreq)
140 struct hreq_data *data;
142 if (hreq->postform != NULL)
143 MHD_destroy_post_processor(hreq->postform);
144 for (data = hreq->data; data; data = hreq->data) {
145 hreq->data = data->next;
150 ctxClientPut(hreq->context);
156 * Removes the 'prefix' of 'length' from the tail of 'hreq'
157 * if and only if the prefix exists and is terminated by a leading
160 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
162 /* check the prefix ? */
163 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
164 || strncasecmp(prefix, hreq->tail, length))
167 /* removes successives / */
168 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
171 /* update the tail */
172 hreq->lentail -= length;
173 hreq->tail += length;
177 int afb_hreq_valid_tail(struct afb_hreq *hreq)
179 return validsubpath(hreq->tail);
182 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
186 struct MHD_Response *response;
188 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
190 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
192 buffer = "<html><body>error</body></html>";
193 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
195 if (!MHD_queue_response(hreq->connection, status, response))
196 fprintf(stderr, "Failed to reply error code %u", status);
197 MHD_destroy_response(response);
200 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
206 char etag[1 + 2 * sizeof(int)];
208 struct MHD_Response *response;
210 /* Opens the file or directory */
212 fd = openat(dirfd, filename, O_RDONLY);
216 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
222 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
227 /* Retrieves file's status */
228 if (fstat(fd, &st) != 0) {
230 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
234 /* serve directory */
235 if (S_ISDIR(st.st_mode)) {
236 if (hreq->url[hreq->lenurl - 1] != '/') {
237 /* the redirect is needed for reliability of relative path */
238 char *tourl = alloca(hreq->lenurl + 2);
239 memcpy(tourl, hreq->url, hreq->lenurl);
240 tourl[hreq->lenurl] = '/';
241 tourl[hreq->lenurl + 1] = 0;
242 rc = afb_hreq_redirect_to(hreq, tourl);
244 rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
250 /* Don't serve special files */
251 if (!S_ISREG(st.st_mode)) {
253 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
257 /* Check the method */
258 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
260 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
264 /* computes the etag */
265 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
267 /* checks the etag */
268 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
269 if (inm && 0 == strcmp(inm, etag)) {
270 /* etag ok, return NOT MODIFIED */
273 fprintf(stderr, "Not Modified: [%s]\n", filename);
274 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
275 status = MHD_HTTP_NOT_MODIFIED;
278 if (st.st_size != (off_t) (size_t) st.st_size) {
280 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
284 /* create the response */
285 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
286 status = MHD_HTTP_OK;
288 #if defined(USE_MAGIC_MIME_TYPE)
290 if (hreq->session->magic) {
291 const char *mimetype = magic_descriptor(hreq->session->magic, fd);
292 if (mimetype != NULL)
293 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
298 /* fills the value and send */
299 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
300 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
301 MHD_queue_response(hreq->connection, status, response);
302 MHD_destroy_response(response);
306 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
308 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
310 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
314 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
316 struct MHD_Response *response;
318 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
319 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
320 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
321 MHD_destroy_response(response);
323 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
327 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
329 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
332 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
334 struct hreq_data *data = get_data(hreq, name, 0);
335 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
338 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
340 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
343 void afb_hreq_post_end(struct afb_hreq *hreq)
345 struct hreq_data *data = hreq->data;
347 if (data->file > 0) {
355 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
358 struct hreq_data *hdat = get_data(hreq, key, 1);
362 p = realloc(hdat->value, hdat->length + size + 1);
367 memcpy(&hdat->value[hdat->length], data, size);
368 hdat->length += size;
369 hdat->value[hdat->length] = 0;
373 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
375 struct hreq_data *hdat = get_data(hreq, key, 1);
377 /* continuation with reopening */
378 if (hdat->file < 0) {
379 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
380 if (hdat->file == 0) {
387 if (hdat->file > 0) {
388 write(hdat->file, data, size);
398 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
400 struct hreq_data *hdat = get_data(hreq, key, 0);
401 return hdat != NULL && hdat->file != 0;
405 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
407 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
410 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
412 struct hreq_data *hdat = get_data(hreq, name, 0);
414 return (struct afb_arg){
416 .value = hdat->value,
417 .size = hdat->length,
418 .is_file = (hdat->file != 0)
421 return (struct afb_arg){
423 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
431 struct afb_hreq *hreq;
432 int (*iterator)(void *closure, struct afb_arg arg);
436 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
438 if (get_data(id->hreq, key, 0))
440 return id->iterator(id->closure, (struct afb_arg){
448 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
450 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
451 struct hreq_data *hdat = hreq->data;
453 if (!iterator(closure, (struct afb_arg){
455 .value = hdat->value,
456 .size = hdat->length,
457 .is_file = (hdat->file != 0)}))
461 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
464 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
466 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
470 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
472 json_object *root, *request;
473 struct MHD_Response *response;
475 root = json_object_new_object();
476 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
477 request = json_object_new_object();
478 json_object_object_add(root, "request", request);
479 json_object_object_add(request, "status", json_object_new_string(status));
481 json_object_object_add(request, "info", json_object_new_string(info));
483 json_object_object_add(root, "response", resp);
485 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
486 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
489 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
490 MHD_queue_response(hreq->connection, retcode, response);
491 MHD_destroy_response(response);
494 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
496 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
499 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
501 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
504 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
508 if (hreq->context == NULL) {
509 uuid = afb_hreq_get_header(hreq, uuid_header);
511 uuid = afb_hreq_get_argument(hreq, uuid_arg);
513 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
514 hreq->context = ctxClientGet(uuid);
516 return hreq->context;
519 static int req_session_create(struct afb_hreq *hreq)
521 struct AFB_clientCtx *context = afb_hreq_context(hreq);
524 if (context->created)
526 return req_session_check(hreq, 1);
529 static int req_session_check(struct afb_hreq *hreq, int refresh)
533 struct AFB_clientCtx *context = afb_hreq_context(hreq);
538 token = afb_hreq_get_header(hreq, token_header);
540 token = afb_hreq_get_argument(hreq, token_arg);
542 token = afb_hreq_get_cookie(hreq, token_cookie);
546 if (!ctxTokenCheck (context, token))
550 ctxTokenNew (context);
556 static void req_session_close(struct afb_hreq *hreq)
558 struct AFB_clientCtx *context = afb_hreq_context(hreq);
560 ctxClientClose(context);