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"
37 #define SIZE_RESPONSE_BUFFER 8000
39 static char empty_string[] = "";
41 static const char uuid_header[] = "x-afb-uuid";
42 static const char uuid_arg[] = "uuid";
43 static const char uuid_cookie[] = "uuid";
45 static const char token_header[] = "x-afb-token";
46 static const char token_arg[] = "token";
47 static const char token_cookie[] = "token";
51 struct hreq_data *next;
58 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
59 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
60 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
61 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
62 static int req_session_create(struct afb_hreq *hreq);
63 static int req_session_check(struct afb_hreq *hreq, int refresh);
64 static void req_session_close(struct afb_hreq *hreq);
66 static const struct afb_req_itf afb_hreq_itf = {
67 .get = (void*)req_get,
68 .iterate = (void*)req_iterate,
69 .fail = (void*)req_fail,
70 .success = (void*)req_success,
71 .session_create = (void*)req_session_create,
72 .session_check = (void*)req_session_check,
73 .session_close = (void*)req_session_close
76 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
78 struct hreq_data *data = hreq->data;
81 while (data != NULL) {
82 if (!strcasecmp(data->key, key))
87 data = calloc(1, sizeof *data);
89 data->key = strdup(key);
90 if (data->key == NULL) {
94 data->next = hreq->data;
102 /* a valid subpath is a relative path not looking deeper than root using .. */
103 static int validsubpath(const char *subpath)
108 switch (subpath[i++]) {
112 if (subpath[i] == '/') {
116 if (subpath[i++] == '.') {
122 if (subpath[i++] == '/') {
129 while (subpath[i] && subpath[i] != '/')
139 void afb_hreq_free(struct afb_hreq *hreq)
141 struct hreq_data *data;
143 if (hreq->postform != NULL)
144 MHD_destroy_post_processor(hreq->postform);
145 for (data = hreq->data; data; data = hreq->data) {
146 hreq->data = data->next;
151 ctxClientPut(hreq->context);
157 * Removes the 'prefix' of 'length' from the tail of 'hreq'
158 * if and only if the prefix exists and is terminated by a leading
161 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
163 /* check the prefix ? */
164 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
165 || strncasecmp(prefix, hreq->tail, length))
168 /* removes successives / */
169 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
172 /* update the tail */
173 hreq->lentail -= length;
174 hreq->tail += length;
178 int afb_hreq_valid_tail(struct afb_hreq *hreq)
180 return validsubpath(hreq->tail);
183 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
187 struct MHD_Response *response;
189 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
191 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
193 buffer = "<html><body>error</body></html>";
194 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
196 if (!MHD_queue_response(hreq->connection, status, response))
197 fprintf(stderr, "Failed to reply error code %u", status);
198 MHD_destroy_response(response);
201 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
207 char etag[1 + 2 * sizeof(int)];
209 struct MHD_Response *response;
211 /* Opens the file or directory */
213 fd = openat(dirfd, filename, O_RDONLY);
217 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
223 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
228 /* Retrieves file's status */
229 if (fstat(fd, &st) != 0) {
231 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
235 /* serve directory */
236 if (S_ISDIR(st.st_mode)) {
237 if (hreq->url[hreq->lenurl - 1] != '/') {
238 /* the redirect is needed for reliability of relative path */
239 char *tourl = alloca(hreq->lenurl + 2);
240 memcpy(tourl, hreq->url, hreq->lenurl);
241 tourl[hreq->lenurl] = '/';
242 tourl[hreq->lenurl + 1] = 0;
243 rc = afb_hreq_redirect_to(hreq, tourl);
245 rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
251 /* Don't serve special files */
252 if (!S_ISREG(st.st_mode)) {
254 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
258 /* Check the method */
259 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
261 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
265 /* computes the etag */
266 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
268 /* checks the etag */
269 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
270 if (inm && 0 == strcmp(inm, etag)) {
271 /* etag ok, return NOT MODIFIED */
274 fprintf(stderr, "Not Modified: [%s]\n", filename);
275 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
276 status = MHD_HTTP_NOT_MODIFIED;
279 if (st.st_size != (off_t) (size_t) st.st_size) {
281 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
285 /* create the response */
286 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
287 status = MHD_HTTP_OK;
289 #if defined(USE_MAGIC_MIME_TYPE)
291 if (hreq->session->magic) {
292 const char *mimetype = magic_descriptor(hreq->session->magic, fd);
293 if (mimetype != NULL)
294 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
299 /* fills the value and send */
300 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
301 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
302 MHD_queue_response(hreq->connection, status, response);
303 MHD_destroy_response(response);
307 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
309 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
311 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
315 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
317 struct MHD_Response *response;
319 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
320 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
321 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
322 MHD_destroy_response(response);
324 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
328 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
330 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
333 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
335 struct hreq_data *data = get_data(hreq, name, 0);
336 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
339 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
341 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
344 void afb_hreq_post_end(struct afb_hreq *hreq)
346 struct hreq_data *data = hreq->data;
348 if (data->file > 0) {
356 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
359 struct hreq_data *hdat = get_data(hreq, key, 1);
363 p = realloc(hdat->value, hdat->length + size + 1);
368 memcpy(&hdat->value[hdat->length], data, size);
369 hdat->length += size;
370 hdat->value[hdat->length] = 0;
374 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
376 struct hreq_data *hdat = get_data(hreq, key, 1);
378 /* continuation with reopening */
379 if (hdat->file < 0) {
380 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
381 if (hdat->file == 0) {
388 if (hdat->file > 0) {
389 write(hdat->file, data, size);
399 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
401 struct hreq_data *hdat = get_data(hreq, key, 0);
402 return hdat != NULL && hdat->file != 0;
406 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
408 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
411 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
413 struct hreq_data *hdat = get_data(hreq, name, 0);
415 return (struct afb_arg){
417 .value = hdat->value,
418 .size = hdat->length,
419 .is_file = (hdat->file != 0)
422 return (struct afb_arg){
424 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
432 struct afb_hreq *hreq;
433 int (*iterator)(void *closure, struct afb_arg arg);
437 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
439 if (get_data(id->hreq, key, 0))
441 return id->iterator(id->closure, (struct afb_arg){
449 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
451 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
452 struct hreq_data *hdat = hreq->data;
454 if (!iterator(closure, (struct afb_arg){
456 .value = hdat->value,
457 .size = hdat->length,
458 .is_file = (hdat->file != 0)}))
462 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
465 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
467 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
471 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
473 json_object *root, *request;
474 struct MHD_Response *response;
476 root = json_object_new_object();
477 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
478 request = json_object_new_object();
479 json_object_object_add(root, "request", request);
480 json_object_object_add(request, "status", json_object_new_string(status));
482 json_object_object_add(request, "info", json_object_new_string(info));
484 json_object_object_add(root, "response", resp);
486 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
487 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
490 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
491 MHD_queue_response(hreq->connection, retcode, response);
492 MHD_destroy_response(response);
495 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
497 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
500 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
502 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
505 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
509 if (hreq->context == NULL) {
510 uuid = afb_hreq_get_header(hreq, uuid_header);
512 uuid = afb_hreq_get_argument(hreq, uuid_arg);
514 uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
515 hreq->context = ctxClientGet(uuid);
517 return hreq->context;
520 static int req_session_create(struct afb_hreq *hreq)
522 struct AFB_clientCtx *context = afb_hreq_context(hreq);
525 if (context->created)
527 return req_session_check(hreq, 1);
530 static int req_session_check(struct afb_hreq *hreq, int refresh)
534 struct AFB_clientCtx *context = afb_hreq_context(hreq);
539 token = afb_hreq_get_header(hreq, token_header);
541 token = afb_hreq_get_argument(hreq, token_arg);
543 token = afb_hreq_get_cookie(hreq, token_cookie);
547 if (!ctxTokenCheck (context, token))
551 ctxTokenNew (context);
557 static void req_session_close(struct afb_hreq *hreq)
559 struct AFB_clientCtx *context = afb_hreq_context(hreq);
561 ctxClientClose(context);