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"
35 #define SIZE_RESPONSE_BUFFER 8000
37 static char empty_string[] = "";
40 struct hreq_data *next;
47 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
48 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
49 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
50 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
52 static const struct afb_req_itf afb_hreq_itf = {
53 .get = (void*)req_get,
54 .iterate = (void*)req_iterate,
55 .fail = (void*)req_fail,
56 .success = (void*)req_success
58 void (*fail)(void *data, const char *status, const char *info);
59 void (*success)(void *data, json_object *obj, const char *info);
61 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
63 struct hreq_data *data = hreq->data;
66 while (data != NULL) {
67 if (!strcasecmp(data->key, key))
72 data = calloc(1, sizeof *data);
74 data->key = strdup(key);
75 if (data->key == NULL) {
79 data->next = hreq->data;
87 /* a valid subpath is a relative path not looking deeper than root using .. */
88 static int validsubpath(const char *subpath)
93 switch (subpath[i++]) {
97 if (subpath[i] == '/') {
101 if (subpath[i++] == '.') {
107 if (subpath[i++] == '/') {
114 while (subpath[i] && subpath[i] != '/')
125 * Removes the 'prefix' of 'length' frome the tail of 'hreq'
126 * if and only if the prefix exists and is terminated by a leading
129 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
131 /* check the prefix ? */
132 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
133 || strncasecmp(prefix, hreq->tail, length))
136 /* removes successives / */
137 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
140 /* update the tail */
141 hreq->lentail -= length;
142 hreq->tail += length;
146 int afb_hreq_valid_tail(struct afb_hreq *hreq)
148 return validsubpath(hreq->tail);
151 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
155 struct MHD_Response *response;
157 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
159 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
161 buffer = "<html><body>error</body></html>";
162 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
164 if (!MHD_queue_response(hreq->connection, status, response))
165 fprintf(stderr, "Failed to reply error code %u", status);
166 MHD_destroy_response(response);
169 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
175 char etag[1 + 2 * sizeof(int)];
177 struct MHD_Response *response;
179 /* Opens the file or directory */
181 fd = openat(dirfd, filename, O_RDONLY);
185 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
191 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
196 /* Retrieves file's status */
197 if (fstat(fd, &st) != 0) {
199 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
203 /* serve directory */
204 if (S_ISDIR(st.st_mode)) {
205 if (hreq->url[hreq->lenurl - 1] != '/') {
206 /* the redirect is needed for reliability of relative path */
207 char *tourl = alloca(hreq->lenurl + 2);
208 memcpy(tourl, hreq->url, hreq->lenurl);
209 tourl[hreq->lenurl] = '/';
210 tourl[hreq->lenurl + 1] = 0;
211 rc = afb_hreq_redirect_to(hreq, tourl);
213 rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
219 /* Don't serve special files */
220 if (!S_ISREG(st.st_mode)) {
222 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
226 /* Check the method */
227 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
229 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
233 /* computes the etag */
234 sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
236 /* checks the etag */
237 inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
238 if (inm && 0 == strcmp(inm, etag)) {
239 /* etag ok, return NOT MODIFIED */
242 fprintf(stderr, "Not Modified: [%s]\n", filename);
243 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
244 status = MHD_HTTP_NOT_MODIFIED;
247 if (st.st_size != (off_t) (size_t) st.st_size) {
249 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
253 /* create the response */
254 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
255 status = MHD_HTTP_OK;
257 #if defined(USE_MAGIC_MIME_TYPE)
259 if (hreq->session->magic) {
260 const char *mimetype = magic_descriptor(hreq->session->magic, fd);
261 if (mimetype != NULL)
262 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
267 /* fills the value and send */
268 MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
269 MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
270 MHD_queue_response(hreq->connection, status, response);
271 MHD_destroy_response(response);
275 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
277 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
279 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
283 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
285 struct MHD_Response *response;
287 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
288 MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
289 MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
290 MHD_destroy_response(response);
292 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
296 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
298 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
301 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
303 struct hreq_data *data = get_data(hreq, name, 0);
304 return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
307 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
309 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
312 void afb_hreq_post_end(struct afb_hreq *hreq)
314 struct hreq_data *data = hreq->data;
316 if (data->file > 0) {
324 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
327 struct hreq_data *hdat = get_data(hreq, key, 1);
331 p = realloc(hdat->value, hdat->length + size + 1);
336 memcpy(&hdat->value[hdat->length], data, size);
337 hdat->length += size;
338 hdat->value[hdat->length] = 0;
342 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
344 struct hreq_data *hdat = get_data(hreq, key, 1);
346 /* continuation with reopening */
347 if (hdat->file < 0) {
348 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
349 if (hdat->file == 0) {
356 if (hdat->file > 0) {
357 write(hdat->file, data, size);
367 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
369 struct hreq_data *hdat = get_data(hreq, key, 0);
370 return hdat != NULL && hdat->file != 0;
374 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
376 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
379 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
381 struct hreq_data *hdat = get_data(hreq, name, 0);
383 return (struct afb_arg){
385 .value = hdat->value,
386 .size = hdat->length,
387 .is_file = (hdat->file != 0)
390 return (struct afb_arg){
392 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
400 struct afb_hreq *hreq;
401 int (*iterator)(void *closure, struct afb_arg arg);
405 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
407 if (get_data(id->hreq, key, 0))
409 return id->iterator(id->closure, (struct afb_arg){
417 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
419 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
420 struct hreq_data *hdat = hreq->data;
422 if (!iterator(closure, (struct afb_arg){
424 .value = hdat->value,
425 .size = hdat->length,
426 .is_file = (hdat->file != 0)}))
430 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
433 void afb_hreq_drop_data(struct afb_hreq *hreq)
435 struct hreq_data *data = hreq->data;
437 hreq->data = data->next;
444 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
446 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
450 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
452 json_object *root, *request;
453 struct MHD_Response *response;
455 root = json_object_new_object();
456 json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
457 request = json_object_new_object();
458 json_object_object_add(root, "request", request);
459 json_object_object_add(request, "status", json_object_new_string(status));
461 json_object_object_add(request, "info", json_object_new_string(info));
463 json_object_object_add(root, "response", resp);
465 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
466 MHD_queue_response(hreq->connection, retcode, response);
467 MHD_destroy_response(response);
470 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
472 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
475 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
477 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);