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 static char empty_string[] = "";
38 struct hreq_data *next;
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);
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
56 void (*fail)(void *data, const char *status, const char *info);
57 void (*success)(void *data, json_object *obj, const char *info);
59 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
61 struct hreq_data *data = hreq->data;
64 while (data != NULL) {
65 if (!strcasecmp(data->key, key))
70 data = calloc(1, sizeof *data);
72 data->key = strdup(key);
73 if (data->key == NULL) {
77 data->next = hreq->data;
85 /* a valid subpath is a relative path not looking deeper than root using .. */
86 static int validsubpath(const char *subpath)
91 switch (subpath[i++]) {
95 if (subpath[i] == '/') {
99 if (subpath[i++] == '.') {
105 if (subpath[i++] == '/') {
112 while (subpath[i] && subpath[i] != '/')
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
127 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
129 /* check the prefix ? */
130 if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
131 || strncasecmp(prefix, hreq->tail, length))
134 /* removes successives / */
135 while (length < hreq->lentail && hreq->tail[length + 1] == '/')
138 /* update the tail */
139 hreq->lentail -= length;
140 hreq->tail += length;
144 int afb_hreq_valid_tail(struct afb_hreq *hreq)
146 return validsubpath(hreq->tail);
149 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
153 struct MHD_Response *response;
155 length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
157 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
159 buffer = "<html><body>error</body></html>";
160 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
162 if (!MHD_queue_response(hreq->connection, status, response))
163 fprintf(stderr, "Failed to reply error code %u", status);
164 MHD_destroy_response(response);
167 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
173 char etag[1 + 2 * sizeof(int)];
175 struct MHD_Response *response;
177 /* Opens the file or directory */
179 fd = openat(dirfd, filename, O_RDONLY);
183 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
189 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
194 /* Retrieves file's status */
195 if (fstat(fd, &st) != 0) {
197 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
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);
211 rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
217 /* Don't serve special files */
218 if (!S_ISREG(st.st_mode)) {
220 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
224 /* Check the method */
225 if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
227 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
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));
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 */
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;
245 if (st.st_size != (off_t) (size_t) st.st_size) {
247 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
251 /* create the response */
252 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
253 status = MHD_HTTP_OK;
255 #if defined(USE_MAGIC_MIME_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);
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);
273 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
275 int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
277 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
281 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
283 struct MHD_Response *response;
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);
290 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
294 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
296 return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
299 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
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);
305 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
307 return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
310 void afb_hreq_post_end(struct afb_hreq *hreq)
312 struct hreq_data *data = hreq->data;
314 if (data->file > 0) {
322 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
325 struct hreq_data *hdat = get_data(hreq, key, 1);
329 p = realloc(hdat->value, hdat->length + size + 1);
334 memcpy(&hdat->value[hdat->length], data, size);
335 hdat->length += size;
336 hdat->value[hdat->length] = 0;
340 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
342 struct hreq_data *hdat = get_data(hreq, key, 1);
344 /* continuation with reopening */
345 if (hdat->file < 0) {
346 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
347 if (hdat->file == 0) {
354 if (hdat->file > 0) {
355 write(hdat->file, data, size);
365 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
367 struct hreq_data *hdat = get_data(hreq, key, 0);
368 return hdat != NULL && hdat->file != 0;
372 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
374 return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
377 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
379 struct hreq_data *hdat = get_data(hreq, name, 0);
381 return (struct afb_arg){
383 .value = hdat->value,
384 .size = hdat->length,
385 .is_file = (hdat->file != 0)
388 return (struct afb_arg){
390 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
398 struct afb_hreq *hreq;
399 int (*iterator)(void *closure, struct afb_arg arg);
403 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
405 if (get_data(id->hreq, key, 0))
407 return id->iterator(id->closure, (struct afb_arg){
415 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
417 struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
418 struct hreq_data *hdat = hreq->data;
420 if (!iterator(closure, (struct afb_arg){
422 .value = hdat->value,
423 .size = hdat->length,
424 .is_file = (hdat->file != 0)}))
428 MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
431 void afb_hreq_drop_data(struct afb_hreq *hreq)
433 struct hreq_data *data = hreq->data;
435 hreq->data = data->next;
442 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
444 ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
448 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
450 json_object *root, *request;
451 struct MHD_Response *response;
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));
459 json_object_object_add(request, "info", json_object_new_string(info));
461 json_object_object_add(root, "response", resp);
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);
468 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
470 req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
473 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
475 req_reply(hreq, MHD_HTTP_OK, "success", info, obj);