2 * Copyright (C) 2016 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author José Bollo <jose.bollo@iot.bzh>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * Contain all generic part to handle REST/API
21 * https://www.gnu.org/software/libmicrohttpd/tutorial.html [search 'largepost.c']
26 #include "../include/local-def.h"
36 #define AFB_MSG_JTYPE "AJB_reply"
38 #define JSON_CONTENT "application/json"
39 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
41 static json_object *afbJsonType;
43 // Because of POST call multiple time requestApi we need to free POST handle here
44 // Note this method is called from http-svc just before closing session
45 PUBLIC void endPostRequest(AFB_PostHandle * postHandle)
48 if (postHandle->type == AFB_POST_JSON) {
49 // if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
52 if (postHandle->type == AFB_POST_FORM) {
54 fprintf(stderr, "End PostForm Request UID=%d\n", postHandle->uid);
56 if (postHandle->privatebuf)
57 free(postHandle->privatebuf);
61 // Check of apiurl is declare in this plugin and call it
62 static AFB_error doCallPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
64 enum AFB_sessionE session;
65 json_object *jresp, *jcall, *jreqt;
66 AFB_clientCtx *clientCtx = NULL;
68 // Request was found and at least partially executed
69 jreqt = json_object_new_object();
70 json_object_object_add(jreqt, "jtype", json_object_get(afbJsonType));
72 // prepare an object to store calling values
73 jcall = json_object_new_object();
74 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
75 json_object_object_add(jcall, "api", json_object_new_string(request->method));
77 // Out of SessionNone every call get a client context session
78 session = afb_apis_get(apiidx, verbidx)->session;
79 if (AFB_SESSION_NONE != session) {
81 // add client context to request
82 clientCtx = ctxClientGet(request);
83 if (clientCtx == NULL) {
84 request->errcode = MHD_HTTP_INSUFFICIENT_STORAGE;
85 json_object_object_add(jcall, "status", json_object_new_string("fail"));
86 json_object_object_add(jcall, "info", json_object_new_string("Client Session Context Full !!!"));
87 json_object_object_add(jreqt, "request", jcall);
90 request->context = clientCtx->contexts[apiidx];
91 request->uuid = clientCtx->uuid;
94 fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[%p] Uuid=[%s] Token=[%s]\n", request->prefix, request->method, session, clientCtx, clientCtx->uuid, clientCtx->token);
98 case AFB_SESSION_CREATE:
99 if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
100 request->errcode = MHD_HTTP_UNAUTHORIZED;
101 json_object_object_add(jcall, "status", json_object_new_string("exist"));
102 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Session already exist"));
103 json_object_object_add(jreqt, "request", jcall);
107 if (AFB_SUCCESS != ctxTokenCreate(clientCtx, request)) {
108 request->errcode = MHD_HTTP_UNAUTHORIZED;
109 json_object_object_add(jcall, "status", json_object_new_string("fail"));
110 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Invalid Initial Token"));
111 json_object_object_add(jreqt, "request", jcall);
114 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
115 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
116 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
120 case AFB_SESSION_RENEW:
121 if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
122 request->errcode = MHD_HTTP_UNAUTHORIZED;
123 json_object_object_add(jcall, "status", json_object_new_string("fail"));
124 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
125 json_object_object_add(jreqt, "request", jcall);
128 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
129 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
130 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
134 case AFB_SESSION_CLOSE:
135 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
136 request->errcode = MHD_HTTP_UNAUTHORIZED;
137 json_object_object_add(jcall, "status", json_object_new_string("empty"));
138 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CLOSE Not a Valid Access Token"));
139 json_object_object_add(jreqt, "request", jcall);
142 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
146 case AFB_SESSION_CHECK:
148 // default action is check
149 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
150 request->errcode = MHD_HTTP_UNAUTHORIZED;
151 json_object_object_add(jcall, "status", json_object_new_string("fail"));
152 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CHECK Invalid Active Token"));
153 json_object_object_add(jreqt, "request", jcall);
160 // Effectively CALL PLUGIN API with a subset of the context
161 jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
163 // Store context in case it was updated by plugins
164 if (request->context != NULL)
165 clientCtx->contexts[apiidx] = request->context;
167 // handle intermediary Post Iterates out of band
168 if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
171 // Session close is done after the API call so API can still use session in closing API
172 if (AFB_SESSION_CLOSE == session)
173 ctxTokenReset(clientCtx, request);
175 // API should return NULL of a valid Json Object
177 json_object_object_add(jcall, "status", json_object_new_string("null"));
178 json_object_object_add(jreqt, "request", jcall);
179 request->errcode = MHD_HTTP_NO_RESPONSE;
182 json_object_object_add(jcall, "status", json_object_new_string("processed"));
183 json_object_object_add(jreqt, "request", jcall);
184 json_object_object_add(jreqt, "response", jresp);
188 request->jresp = jreqt;
192 // Check of apiurl is declare in this plugin and call it
193 extern __thread sigjmp_buf *error_handler;
194 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
196 sigjmp_buf jmpbuf, *older;
198 json_object *jcall, *jreqt;
201 // save context before calling the API
202 status = setjmp(jmpbuf);
205 // Request was found and at least partially executed
206 jreqt = json_object_new_object();
207 json_object_object_add(jreqt, "jtype", json_object_get(afbJsonType));
209 // prepare an object to store calling values
210 jcall = json_object_new_object();
211 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
212 json_object_object_add(jcall, "api", json_object_new_string(request->method));
214 // Plugin aborted somewhere during its execution
215 json_object_object_add(jcall, "status", json_object_new_string("abort"));
216 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
217 json_object_object_add(jreqt, "request", jcall);
218 request->jresp = jreqt;
221 // Trigger a timer to protect from unacceptable long time execution
222 if (request->config->apiTimeout > 0)
223 alarm((unsigned)request->config->apiTimeout);
225 older = error_handler;
226 error_handler = &jmpbuf;
227 doCallPluginApi(request, apiidx, verbidx, context);
228 error_handler = older;
230 // cancel timeout and plugin signal handle before next call
236 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
241 if (!request->method || !request->prefix)
244 /* get the plugin if any */
245 apiidx = afb_apis_get_apiidx(request->prefix, 0);
247 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
248 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
252 /* get the verb if any */
253 verbidx = afb_apis_get_verbidx(apiidx, request->method);
255 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
256 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
260 /* Search for a plugin with this urlpath */
261 status = callPluginApi(request, apiidx, verbidx, context);
263 /* plugin callback did not return a valid Json Object */
264 if (status == AFB_FAIL) {
265 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
266 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
269 // Everything look OK
273 // This CB is call for every item with a form post it reformat iterator values
274 // and callback Plugin API for each Item within PostForm.
275 STATIC int doPostIterate(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *mimetype, const char *encoding, const char *data, uint64_t offset, size_t size)
281 // retrieve API request from Post iterator handle
282 AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
283 AFB_request *request = (AFB_request *) postHandle->privatebuf;
284 AFB_PostRequest postRequest;
287 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
289 // Create and Item value for Plugin API
292 item.filename = filename;
293 item.mimetype = mimetype;
294 item.encoding = encoding;
297 item.offset = offset;
299 // Reformat Request to make it somehow similar to GET/PostJson case
300 postRequest.data = (char *)postHandle;
301 postRequest.len = size;
302 postRequest.type = AFB_POST_FORM;;
303 request->post = &postRequest;
305 // effectively call plugin API
306 status = findAndCallApi(request, &item);
307 // when returning no processing of postform stop
308 if (status != AFB_SUCCESS)
311 // let's allow iterator to move to next item
315 STATIC void freeRequest(AFB_request * request)
318 free((void*)request->prefix);
319 free((void*)request->method);
323 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
326 AFB_request *request;
328 // Start with a clean request
329 request = calloc(1, sizeof(AFB_request));
330 char *urlcpy1, *urlcpy2;
331 char *baseapi, *baseurl;
333 // Extract plugin urlpath from request and make two copy because strsep overload copy
334 urlcpy1 = urlcpy2 = strdup(url);
335 baseurl = strsep(&urlcpy2, "/");
336 if (baseurl == NULL) {
337 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
338 request->errcode = MHD_HTTP_BAD_REQUEST;
341 // let's compute URL and call API
342 baseapi = strsep(&urlcpy2, "/");
343 if (baseapi == NULL) {
344 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
345 request->errcode = MHD_HTTP_BAD_REQUEST;
348 // build request structure
349 // request->connection = connection;
350 request->config = session->config;
352 request->prefix = strdup(baseurl);
353 request->method = strdup(baseapi);
374 static int doRestApiPost(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
377 static int postcount = 0; // static counter to debug POST protocol
378 json_object *errMessage;
380 struct MHD_Response *webResponse;
381 const char *serialized;
382 AFB_request *request = NULL;
383 AFB_PostHandle *postHandle;
384 AFB_PostRequest postRequest;
387 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
389 // if post data may come in multiple calls
390 const char *encoding, *param;
392 postHandle = *con_cls;
394 // This is the initial post event let's create form post structure POST data come in multiple events
395 if (postHandle == NULL) {
397 // allocate application POST processor handle to zero
398 postHandle = calloc(1, sizeof(AFB_PostHandle));
399 postHandle->uid = postcount++; // build a UID for DEBUG
400 *con_cls = postHandle; // update context with posthandle
402 // Let make sure we have the right encoding and a valid length
403 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
405 // We are facing an empty post let's process it as a get
406 if (encoding == NULL) {
407 postHandle->type = AFB_POST_EMPTY;
411 // Form post is handle through a PostProcessor and call API once per form key
412 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
414 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
416 request = createRequest(connection, session, url);
417 if (request->jresp != NULL)
419 postHandle->type = AFB_POST_FORM;
420 postHandle->privatebuf = (void *)request;
421 postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
423 if (NULL == postHandle->pp) {
424 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
430 // POST json is store into a buffer and present in one piece to API
431 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
433 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
435 sscanf(param, "%i", &contentlen);
437 // Because PostJson are build in RAM size is constrained
438 if (contentlen > MAX_POST_SIZE) {
439 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
442 // Size is OK, let's allocate a buffer to hold post data
443 postHandle->type = AFB_POST_JSON;
444 postHandle->privatebuf = malloc((unsigned)contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
446 // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
450 // We only support Json and Form Post format
451 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
455 // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
456 // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
457 // 'Internal application error, closing connection'.
458 if (*upload_data_size) {
460 if (postHandle->type == AFB_POST_FORM) {
461 // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
462 MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
464 // Process JsonPost request when buffer is completed let's call API
465 if (postHandle->type == AFB_POST_JSON) {
466 // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
467 memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
468 postHandle->len = postHandle->len + *upload_data_size;
471 *upload_data_size = 0;
476 if (postHandle->type == AFB_POST_FORM)
477 request = postHandle->privatebuf;
479 // Create a request structure to finalise the request
480 request = createRequest(connection, session, url);
482 if (request->jresp != NULL) {
483 errMessage = request->jresp;
486 postRequest.type = postHandle->type;
488 // Postform add application context handle to request
489 if (postHandle->type == AFB_POST_FORM) {
490 postRequest.data = (char *)postHandle;
491 request->post = &postRequest;
494 if (postHandle->type == AFB_POST_JSON) {
495 // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
497 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
499 sscanf(param, "%i", &contentlen);
501 // At this level we're may verify that we got everything and process DATA
502 if (postHandle->len != contentlen) {
503 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
506 // Before processing data, make sure buffer string is properly ended
507 postHandle->privatebuf[postHandle->len] = '\0';
508 postRequest.data = postHandle->privatebuf;
509 request->post = &postRequest;
511 // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
515 // Request is ready let's call API without any extra handle
516 status = findAndCallApi(request, NULL);
518 serialized = json_object_to_json_string(request->jresp);
519 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
521 // client did not pass token on URI let's use cookies
522 if ((!request->restfull) && (request->context != NULL)) {
524 snprintf(cookie, sizeof(cookie), "%s-%d=%s; Path=%s; Max-Age=%d; HttpOnly", COOKIE_NAME, request->config->httpdPort, request->uuid, request->config->rootapi, request->config->cntxTimeout);
525 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
527 // if requested add an error status
528 if (request->errcode != 0)
529 ret = MHD_queue_response(connection, request->errcode, webResponse);
531 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
533 MHD_destroy_response(webResponse);
534 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
535 freeRequest(request);
539 freeRequest(request);
540 serialized = json_object_to_json_string(errMessage);
541 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
542 MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
543 MHD_destroy_response(webResponse);
544 json_object_put(errMessage); // decrease reference rqtcount to free the json object
567 static int doRestApiGet(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
570 struct MHD_Response *webResponse;
571 const char *serialized;
572 AFB_request *request = NULL;
575 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
577 // if post data may come in multiple calls
578 // this is a get we only need a request
579 request = createRequest(connection, session, url);
581 // Request is ready let's call API without any extra handle
582 status = findAndCallApi(request, NULL);
584 serialized = json_object_to_json_string(request->jresp);
585 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
587 // client did not pass token on URI let's use cookies
588 if ((!request->restfull) && (request->context != NULL)) {
590 snprintf(cookie, sizeof(cookie), "%s-%d=%s; Path=%s; Max-Age=%d; HttpOnly", COOKIE_NAME, request->config->httpdPort, request->uuid, request->config->rootapi, request->config->cntxTimeout);
591 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
593 // if requested add an error status
594 if (request->errcode != 0)
595 ret = MHD_queue_response(connection, request->errcode, webResponse);
597 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
599 MHD_destroy_response(webResponse);
600 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
601 freeRequest(request);
605 int doRestApi(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
609 if (afbJsonType == NULL)
610 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
612 if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
613 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
615 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);